feat(watchlist): add company identity catalog

Embed a pinned FinanceDatabase equity snapshot, add authenticated company search and identity-based follows, preserve legacy assets, and map selected Yahoo symbols for collection.

Refs #19

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 15:08:22 +01:00
parent 1123360914
commit d65222169a
50 changed files with 49897 additions and 193 deletions

View File

@ -26,6 +26,8 @@ WORKDIR /app
COPY --from=builder /app/tradarr .
COPY --from=builder /app/internal/database/migrations ./internal/database/migrations
COPY --from=builder /app/internal/companycatalog/data/FINANCEDATABASE_LICENSE /usr/share/licenses/tradarr/FinanceDatabase-MIT.txt
ENV CHROME_PATH=/usr/bin/chromium
EXPOSE 8080

View File

@ -113,7 +113,7 @@ func run(ctx context.Context) error {
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
gin.SetMode(gin.TestMode)
gin.DefaultWriter = io.Discard
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: e2estack.FakeCompanyCatalog{Fakes: fakes}, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
return p.NewGenerationUseCaseWithFactory(feeds, e2estack.FakeLayaRanker{Provider: provider}, func(m models.ResolvedSummaryModel) (ai.Provider, error) {
selected := provider
selected.Model = m.Model

View File

@ -5,6 +5,7 @@ import (
"log"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/database"
@ -27,6 +28,10 @@ func main() {
if err != nil {
log.Fatalf("config: %v", err)
}
catalog, err := companycatalog.Default()
if err != nil {
log.Fatal("company catalog: invalid embedded snapshot")
}
db, err := database.Connect(cfg.DatabaseURL)
if err != nil {
log.Fatalf("database: %v", err)
@ -50,7 +55,7 @@ func main() {
models.SourceWatcherGuru: watcherguru.New(),
}
app := server.New(repo, cfg, server.Dependencies{LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
defer app.Close()
addr := fmt.Sprintf(":%s", cfg.Port)

View File

@ -0,0 +1,54 @@
package ai
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
func TestTicket19LayaReceivesCompanyNameAndSelectedInternalIdentity(t *testing.T) {
figi := "BBG00ZMFX1S5"
var request struct {
States []struct {
Indices []map[string]string `json:"indices"`
} `json:"states"`
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/systemone/batch" {
t.Errorf("Laya path=%s", r.URL.Path)
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Errorf("decode Laya payload: %v", err)
w.WriteHeader(400)
return
}
fmt.Fprint(w, `{"results":[{"answers":{"relevance":{"type":"score","score":0.1,"answer_confidence":0.9}},"usage":{"truncated":false,"state_tokens_dropped":0,"truncated_questions":[]}}],"total_usage":{"input_tokens":10,"output_tokens":0}}`)
}))
defer srv.Close()
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
_, err = ranker.Rank(context.Background(), "title", []models.UserAsset{{Name: "Baidu, Inc.", Symbol: "9888.HK", FIGI: &figi}}, []generation.Candidate{{ID: "candidate", Article: scraper.Article{Title: "synthetic market headline"}}})
if err != nil {
t.Fatal(err)
}
if len(request.States) != 1 || len(request.States[0].Indices) != 1 {
t.Fatalf("Laya indices payload=%+v", request.States)
}
index := request.States[0].Indices[0]
if index["name"] != "Baidu, Inc." || index["symbol"] != "9888.HK" || index["figi"] != figi {
t.Fatalf("Laya received wrong company identity: %+v", index)
}
if index["symbol"] == "SSAAPL INDEX" {
t.Fatalf("Bloomberg identifier was sent to Laya as ticker: %+v", index)
}
}

View File

@ -102,6 +102,12 @@ func (r *LayaHTTPRanker) Rank(ctx context.Context, mode string, assets []models.
indices := make([]map[string]string, 0, len(assets))
for _, a := range assets {
index := map[string]string{"name": a.Name, "symbol": a.Symbol}
if a.CompanyID != nil {
index["company_id"] = *a.CompanyID
}
if a.YahooSymbol != nil {
index["yahoo_symbol"] = *a.YahooSymbol
}
if a.FIGI != nil {
index["figi"] = *a.FIGI
}

View File

@ -0,0 +1,82 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
)
func TestTicket19CompanySearchIsAuthenticatedBoundedAndReturnsSafeCompanyDTO(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
const secret = "ticket-19-company-search-test-secret"
const userID = "00000000-0000-0000-0000-000000000019"
h := handlers.New(nil, &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
router := SetupRouter(h, secret)
call := func(token, path string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodGet, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
return response
}
unauthenticated := call("", "/api/companies/search?q=BYD&limit=2")
if unauthenticated.Code != http.StatusUnauthorized {
t.Errorf("anonymous company search status=%d, want 401 (body=%s)", unauthenticated.Code, unauthenticated.Body.String())
}
token, err := auth.GenerateToken(userID, "ticket19@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
valid := call(token, "/api/companies/search?q=BYD&limit=2")
if valid.Code != http.StatusOK {
t.Errorf("authenticated company search status=%d, want 200 (body=%s)", valid.Code, valid.Body.String())
} else {
var envelope struct {
Data []map[string]json.RawMessage `json:"data"`
}
if err := json.Unmarshal(valid.Body.Bytes(), &envelope); err != nil {
t.Fatalf("decode company results: %v", err)
}
if len(envelope.Data) == 0 {
t.Fatal("company search returned no local results for BYD")
}
for i, result := range envelope.Data {
var name, companyID string
if err := json.Unmarshal(result["name"], &name); err != nil || strings.TrimSpace(name) == "" {
t.Errorf("result %d lacks display name: %s", i, valid.Body.String())
}
if err := json.Unmarshal(result["company_id"], &companyID); err != nil || strings.TrimSpace(companyID) == "" {
t.Errorf("result %d lacks resolved company_id: %s", i, valid.Body.String())
}
if len(result["exchange"]) == 0 && len(result["country"]) == 0 {
t.Errorf("result %d lacks a company disambiguator: %s", i, valid.Body.String())
}
}
for _, privateKey := range []string{`"symbol":`, `"ticker":`, `"figi":`, `"composite_figi":`} {
if strings.Contains(valid.Body.String(), privateKey) {
t.Errorf("search DTO exposes private identity field %s: %s", privateKey, valid.Body.String())
}
}
}
maxValidLimit := call(token, "/api/companies/search?q=BYD&limit=20")
if maxValidLimit.Code != http.StatusOK {
t.Errorf("company search limit=20 status=%d, want 200 (body=%s)", maxValidLimit.Code, maxValidLimit.Body.String())
}
invalidLimit := call(token, "/api/companies/search?q=BYD&limit=21")
if invalidLimit.Code != http.StatusBadRequest {
t.Errorf("company search limit=21 status=%d, want 400 (body=%s)", invalidLimit.Code, invalidLimit.Body.String())
}
}

View File

@ -0,0 +1,59 @@
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/httputil"
"net/http"
"strconv"
"strings"
"unicode/utf8"
)
type CompanyCatalog = companycatalog.CompanyCatalog
func (h *Handler) SetCompanyCatalog(c CompanyCatalog) { h.companyCatalog = c }
type companyDTO struct {
CompanyID string `json:"company_id"`
Name string `json:"name"`
Exchange string `json:"exchange"`
Country string `json:"country"`
MIC string `json:"mic"`
}
func (h *Handler) SearchCompanies(c *gin.Context) {
query := strings.TrimSpace(c.Query("q"))
limit := 10
params := c.Request.URL.Query()
if values, ok := params["limit"]; ok {
if len(values) != 1 {
c.JSON(400, gin.H{"error": "invalid search parameters"})
return
}
v, err := strconv.Atoi(values[0])
if err != nil {
c.JSON(400, gin.H{"error": "invalid search parameters"})
return
}
limit = v
}
if len(params["q"]) != 1 || !utf8.ValidString(query) || utf8.RuneCountInString(query) < 1 || utf8.RuneCountInString(query) > 100 || limit < 1 || limit > 20 {
c.JSON(400, gin.H{"error": "invalid search parameters"})
return
}
if h.companyCatalog == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "company catalog unavailable"})
return
}
companies, err := h.companyCatalog.SearchCompanies(query, limit)
if err != nil {
c.JSON(503, gin.H{"error": "company catalog unavailable"})
return
}
results := make([]companyDTO, 0, len(companies))
for _, company := range companies {
results = append(results, companyDTO{company.CompanyID, company.Name, company.Exchange, company.Country, company.MIC})
}
httputil.OK(c, results)
}

View File

@ -0,0 +1,164 @@
package handlers
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
)
const (
ticket19OwnerA = "00000000-0000-0000-0000-000000000191"
ticket19OwnerB = "00000000-0000-0000-0000-000000000192"
ticket19BaiduCompany = "isin:KYG070341048"
ticket19NVDACompany = "figi:BBG000BBJQV0"
ticket19SpoofFIGI = "BBG-CLIENT-SPOOF"
)
// ticket19CompanyCatalogFake models the injected, local catalog. It supplies
// canonical domain records; the HTTP DTO remains outside this test contract.
type ticket19CompanyCatalogFake struct {
companies map[string]companycatalog.Company
}
func (f ticket19CompanyCatalogFake) SearchCompanies(query string, limit int) ([]companycatalog.Company, error) {
result := make([]companycatalog.Company, 0, limit)
for _, company := range f.companies {
if query != "" && containsFold(company.Name, query) {
result = append(result, company)
}
}
if len(result) > limit {
result = result[:limit]
}
return result, nil
}
func (f ticket19CompanyCatalogFake) ResolveCompany(companyID string) (companycatalog.Company, error) {
company, ok := f.companies[companyID]
if !ok {
return companycatalog.Company{}, fmt.Errorf("unknown company id")
}
return company, nil
}
func TestTicket19FollowCompanyResolvesOpaqueIdentityIdempotentlyPerOwnerPostgres(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
db := ticket4AssetDB(t)
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(string(migration)); err != nil {
t.Fatal(err)
}
catalog := ticket19CompanyCatalogFake{companies: map[string]companycatalog.Company{
ticket19BaiduCompany: {
CompanyID: ticket19BaiduCompany, ISIN: "KYG070341048", Name: "Baidu, Inc.",
YahooSymbol: "9888.HK", FIGI: "BBG00ZMFX1S5", Exchange: "Hong Kong Stock Exchange", Country: "China",
},
ticket19NVDACompany: {
CompanyID: ticket19NVDACompany, Name: "NVIDIA Corporation",
YahooSymbol: "NVDA", FIGI: "BBG000BBJQV0", Exchange: "Nasdaq", Country: "United States",
},
}}
const secret = "ticket-19-company-follow-test-secret"
tokenA, err := auth.GenerateToken(ticket19OwnerA, "owner-a@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
tokenB, err := auth.GenerateToken(ticket19OwnerB, "owner-b@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
h := New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
h.SetCompanyCatalog(catalog)
router := gin.New()
authed := router.Group("/api")
authed.Use(auth.Middleware(secret))
authed.POST("/me/assets", h.AddMyAsset)
post := func(token, companyID, symbol, name, figi string) *httptest.ResponseRecorder {
t.Helper()
requestBody := map[string]string{"company_id": companyID}
// The client may send old or hostile values; the injected catalog wins.
if symbol != "" {
requestBody["symbol"] = symbol
}
if name != "" {
requestBody["name"] = name
}
if figi != "" {
requestBody["figi"] = figi
}
payload, err := json.Marshal(requestBody)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/me/assets", bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
return response
}
first := post(tokenA, ticket19BaiduCompany, "CLIENT-SPOOF-A", "Client supplied name A", ticket19SpoofFIGI)
if first.Code != http.StatusCreated {
t.Fatalf("follow company status=%d body=%s, want 201", first.Code, first.Body.String())
}
duplicate := post(tokenA, ticket19BaiduCompany, "", "", "")
if duplicate.Code != http.StatusCreated {
t.Fatalf("repeat follow by company identity status=%d body=%s, want idempotent success", duplicate.Code, duplicate.Body.String())
}
otherOwner := post(tokenB, ticket19BaiduCompany, "CLIENT-SPOOF-C", "Client supplied name C", "BBG-CLIENT-SPOOF-3")
if otherOwner.Code != http.StatusCreated {
t.Fatalf("other owner's same-company follow status=%d body=%s", otherOwner.Code, otherOwner.Body.String())
}
fallback := post(tokenB, ticket19NVDACompany, "", "", "")
if fallback.Code != http.StatusCreated {
t.Fatalf("FIGI-fallback company follow status=%d body=%s", fallback.Code, fallback.Body.String())
}
for _, tc := range []struct{ owner, companyID string }{
{ticket19OwnerA, ticket19BaiduCompany},
{ticket19OwnerB, ticket19BaiduCompany},
{ticket19OwnerB, ticket19NVDACompany},
} {
var count int
if err := db.QueryRow(`SELECT COUNT(*) FROM user_assets WHERE user_id=$1 AND company_id=$2`, tc.owner, tc.companyID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Errorf("owner %s company %s rows=%d; want one", tc.owner, tc.companyID, count)
}
}
var userID, companyID, symbol, name string
var figi sql.NullString
err = db.QueryRow(`SELECT user_id::text,company_id,symbol,name,figi FROM user_assets WHERE company_id=$1 AND user_id=$2`, ticket19BaiduCompany, ticket19OwnerA).Scan(&userID, &companyID, &symbol, &name, &figi)
if err != nil {
t.Fatalf("read resolved Baidu asset: %v", err)
}
if userID != ticket19OwnerA || companyID != ticket19BaiduCompany || symbol != "9888.HK" || name != "Baidu, Inc." || !figi.Valid || figi.String != "BBG00ZMFX1S5" {
t.Errorf("persisted identity did not come from CompanyCatalog: owner=%s id=%q symbol=%q name=%q figi=%v", userID, companyID, symbol, name, figi)
}
if bytes.Contains(first.Body.Bytes(), []byte("Client supplied")) || bytes.Contains(first.Body.Bytes(), []byte("CLIENT-SPOOF")) || bytes.Contains(first.Body.Bytes(), []byte(ticket19SpoofFIGI)) {
t.Errorf("POST response leaked client-controlled identity: %s", first.Body.String())
}
}
func containsFold(value, query string) bool {
return len(query) == 0 || strings.Contains(strings.ToLower(value), strings.ToLower(query))
}

View File

@ -0,0 +1,98 @@
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
"net/http/httptest"
"os"
"strings"
"testing"
)
func TestCompanyRepositoryPreservesLegacyAndReturnsHintsPostgres(t *testing.T) {
db := ticket4AssetDB(t)
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(migration)); err != nil {
t.Fatal(err)
}
repo := models.NewRepository(db)
figi := "BBG00ZMFX1S5"
legacy, err := repo.UpsertUserAsset(ticket4OwnerA, "LEGACY INDEX", "legacy retained", &figi)
if err != nil {
t.Fatal(err)
}
company := companycatalog.Company{CompanyID: "isin:KYG070341048", Name: "Baidu, Inc.", YahooSymbol: "9888.HK", FIGI: figi, Country: "China", Exchange: "HKG"}
first, err := repo.UpsertCompanyAsset(ticket4OwnerA, company)
if err != nil {
t.Fatalf("company upsert: %v", err)
}
again, err := repo.UpsertCompanyAsset(ticket4OwnerA, company)
if err != nil || again.ID != first.ID {
t.Fatalf("non-idempotent: %v", err)
}
other, err := repo.UpsertCompanyAsset(ticket4OwnerB, company)
if err != nil {
t.Fatal(err)
}
assets, err := repo.GetUserAssets(ticket4OwnerA)
if err != nil || len(assets) != 2 {
t.Fatalf("assets=%+v err=%v", assets, err)
}
for _, a := range assets {
if a.ID == legacy.ID && (a.Name != "legacy retained" || a.Symbol != "LEGACY INDEX" || a.CompanyID != nil || a.YahooSymbol != nil) {
t.Fatal("legacy row changed")
}
if a.ID == first.ID && (a.YahooSymbol == nil || *a.YahooSymbol != "9888.HK" || a.CompanyID == nil || *a.CompanyID != company.CompanyID) {
t.Fatal("lost company hints")
}
}
if err := repo.RemoveUserAssetByID(ticket4OwnerA, other.ID); err != nil {
t.Fatal(err)
}
theirs, err := repo.GetUserAssets(ticket4OwnerB)
if err != nil || len(theirs) != 1 {
t.Fatal("foreign delete changed data")
}
}
func TestCompanyFollowIgnoresEvenMalformedSpoofFieldsPostgres(t *testing.T) {
db := ticket4AssetDB(t)
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(migration)); err != nil {
t.Fatal(err)
}
repo := models.NewRepository(db)
h := New(repo, &config.Config{}, nil, nil, nil, nil)
company := companycatalog.Company{CompanyID: "isin:KYG070341048", Name: "Baidu, Inc.", YahooSymbol: "9888.HK"}
h.SetCompanyCatalog(ticket19CompanyCatalogFake{companies: map[string]companycatalog.Company{company.CompanyID: company}})
router := gin.New()
router.Use(func(c *gin.Context) { c.Set("userID", ticket4OwnerA) })
router.POST("/assets", h.AddMyAsset)
for _, tc := range []struct {
body string
status int
}{
{`{"company_id":"isin:KYG070341048","name":{"private":"spoof"},"symbol":["SSAAPL INDEX"],"figi":123,"user_id":"foreign"}`, 201},
{`{"company_id":"isin:unknown","symbol":"CLIENT-SPOOF"}`, 400},
} {
req := httptest.NewRequest("POST", "/assets", strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
if response.Code != tc.status {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
}
assets, err := repo.GetUserAssets(ticket4OwnerA)
if err != nil || len(assets) != 1 || assets[0].Name != company.Name {
t.Fatalf("assets=%+v err=%v", assets, err)
}
}

View File

@ -4,6 +4,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/generation"
@ -14,6 +15,7 @@ import (
)
type Handler struct {
companyCatalog CompanyCatalog
indexSearcher indices.IndexSearcher
generationUseCase generation.UseCase
repo *models.Repository
@ -33,14 +35,19 @@ func New(
pipeline *ai.Pipeline,
sched *scheduler.Scheduler,
) *Handler {
var catalog CompanyCatalog
if embedded, err := companycatalog.Default(); err == nil {
catalog = embedded
}
return &Handler{
repo: repo,
cfg: cfg,
enc: enc,
registry: registry,
pipeline: pipeline,
scheduler: sched,
reportManager: ai.NewReportManager(),
companyCatalog: catalog,
repo: repo,
cfg: cfg,
enc: enc,
registry: registry,
pipeline: pipeline,
scheduler: sched,
reportManager: ai.NewReportManager(),
}
}

View File

@ -3,6 +3,7 @@ package handlers
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/tradarr/backend/internal/httputil"
"github.com/tradarr/backend/internal/models"
"net/http"
@ -33,14 +34,39 @@ func (h *Handler) GetMyAssets(c *gin.Context) {
type addAssetRequest struct {
FIGI *string `json:"figi"`
Symbol string `json:"symbol" binding:"required"`
Symbol string `json:"symbol"`
Name string `json:"name"`
}
func (h *Handler) AddMyAsset(c *gin.Context) {
userID := c.GetString("userID")
var identity struct {
CompanyID *string `json:"company_id"`
}
if err := c.ShouldBindBodyWith(&identity, binding.JSON); err != nil {
httputil.BadRequest(c, err)
return
}
if identity.CompanyID != nil {
if h.companyCatalog == nil {
c.JSON(503, gin.H{"error": "company catalog unavailable"})
return
}
company, err := h.companyCatalog.ResolveCompany(strings.TrimSpace(*identity.CompanyID))
if err != nil {
c.JSON(400, gin.H{"error": "unknown company_id"})
return
}
asset, err := h.repo.UpsertCompanyAsset(userID, company)
if err != nil {
c.JSON(500, gin.H{"error": "asset operation failed"})
return
}
httputil.Created(c, asset)
return
}
var req addAssetRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
httputil.BadRequest(c, err)
return
}

View File

@ -34,6 +34,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
authed.Use(auth.Middleware(jwtSecret))
authed.GET("/indices/search", h.SearchIndices)
authed.GET("/companies/search", h.SearchCompanies)
authed.GET("/me", h.GetMe)
authed.GET("/me/preferences", h.GetMyPreferences)
authed.GET("/me/summary-models", h.ListMySummaryModels)

View File

@ -0,0 +1,30 @@
# Catalogue local FinanceDatabase
Source officielle : <https://github.com/JerBouma/FinanceDatabase/tree/93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1>, version 2.5.2, commit du 17 novembre 2026. Copyright (c) 2023 Jeroen Bouma ; licence MIT reproduite intégralement dans `data/FINANCEDATABASE_LICENSE`.
`data/equities_primary.csv` embarque les **47 735 lignes** produites par `Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True)` au commit épinglé. Les scores et indicateurs proviennent de `get_listing_ranks()` sur le jeu complet, sans heuristique maison pour promouvoir un listing secondaire. Aucune partition ETF, fonds, indices, futures ou options n'est chargée par l'exporteur : la classification est celle du partitionnement Equities amont, sans prétendre auditer individuellement chaque instrument. Aucun prix, article ou résultat d'API n'est inclus. Le serveur n'effectue aucun téléchargement, y compris au démarrage.
Le fichier est complet, mais ne représente pas 47 735 sociétés identifiables distinctes : 2 423 lignes n'ont ni ISIN ni FIGI et 2 184 identités ont plusieurs lignes déjà classées primaires par l'amont. Le port expose **43 126 identités** (`isin:` en priorité, sinon `figi:`). Pour une identité répétée, il retient le meilleur `listing_score` amont ; une égalité entre primaires est départagée par symbole dans un ordre stable, uniquement pour choisir un représentant déterministe. Les lignes sans identité restent dans le snapshot mais sont exclues de la recherche et de la résolution. Aucune identité artificielle n'est inventée. Les valeurs exactes NVDA, AAPL, 9888.HK, 002594.SZ et 0285.HK sont vérifiées, avec BYD Company et BYD Electronic distincts.
Le manifeste précise provenance, champs, décompte, SHA-256 du parquet amont et du CSV, empreintes des sources Python utilisées et politique de résolution. Le chargement embarqué vérifie son empreinte avant utilisation. La recherche locale porte sur le nom (casse et espaces normalisés), avec ordre nom/identité stable et limite après déduplication ; aucun appel fournisseur n'est nécessaire. Le DTO de recherche ne projette que `company_id`, `name`, `exchange`, `country`, `mic`.
## Reproduire ou mettre à jour explicitement
Les dépendances Python sont réservées à la maintenance ; elles ne sont requises ni dans l'image backend ni pour les tests Go. Python 3.11+ avec prise en charge `tarfile` du filtre `data` est nécessaire. Installer les versions du lockfile dans un environnement virtuel sous un temporaire accessible :
```sh
python3 -E -m venv "$TMPDIR/company-catalog-venv"
"$TMPDIR/company-catalog-venv/bin/python" -E -m pip install -r backend/scripts/company-catalog-requirements.txt
"$TMPDIR/company-catalog-venv/bin/python" -E backend/scripts/update-company-catalog.py --download
```
`--download` contacte uniquement l'archive source GitHub officielle au commit épinglé. Il ne contacte aucun site financier/API et ne lance aucune récupération d'articles. Pour une reproduction complètement hors réseau, fournir une archive préalablement extraite :
```sh
"$TMPDIR/company-catalog-venv/bin/python" -E backend/scripts/update-company-catalog.py \
--source-dir /chemin/FinanceDatabase-93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1 \
--output "$TMPDIR/company-catalog-reproduction"
cmp backend/internal/companycatalog/data/equities_primary.csv "$TMPDIR/company-catalog-reproduction/equities_primary.csv"
```
Le sélectionneur utilise uniquement les fichiers locaux et refuse les connexions Python pendant la sélection. Les sources et le parquet sont vérifiés avant export. Pour changer de commit, revoir explicitement les empreintes attendues (`company-catalog-upstream.json`), les versions Python, constantes, effectifs, identités cibles et tests ; puis régénérer et faire valider par QA. Il n'existe aucun rafraîchissement automatique. Ne pas lancer cet outil pendant les tests ou au démarrage de l'application.

View File

@ -0,0 +1,168 @@
// Package companycatalog provides a local, immutable catalogue of primary equities.
package companycatalog
import (
"bytes"
"crypto/sha256"
_ "embed"
"encoding/csv"
"encoding/hex"
"encoding/json"
"errors"
"io"
"os"
"sort"
"strconv"
"strings"
"sync"
)
type Company struct {
CompanyID, Name, YahooSymbol, ISIN, FIGI, Exchange, MIC, Country string
}
type CompanyCatalog interface {
SearchCompanies(string, int) ([]Company, error)
ResolveCompany(string) (Company, error)
}
var ErrUnknownCompany = errors.New("unknown company")
type Catalog struct {
companies []Company
byID map[string]Company
}
//go:embed data/equities_primary.csv
var embeddedSnapshot []byte
//go:embed data/manifest.json
var embeddedManifest []byte
//go:embed data/FINANCEDATABASE_LICENSE
var embeddedLicense []byte
var defaultOnce sync.Once
var defaultCatalog *Catalog
var defaultError error
func Default() (*Catalog, error) {
defaultOnce.Do(func() {
var manifest struct {
SHA256 string `json:"sha256"`
Records int `json:"records"`
LicenseSHA256 string `json:"license_sha256"`
}
sum := sha256.Sum256(embeddedSnapshot)
licenseSum := sha256.Sum256(embeddedLicense)
if json.Unmarshal(embeddedManifest, &manifest) != nil || manifest.Records != 47735 || hex.EncodeToString(sum[:]) != manifest.SHA256 || hex.EncodeToString(licenseSum[:]) != manifest.LicenseSHA256 {
defaultError = errors.New("invalid embedded company snapshot checksum")
return
}
defaultCatalog, defaultError = readCatalog(bytes.NewReader(embeddedSnapshot))
})
return defaultCatalog, defaultError
}
func NewFinanceDatabaseCatalogFromSnapshot(path string) (*Catalog, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return readCatalog(f)
}
func readCatalog(input io.Reader) (*Catalog, error) {
r := csv.NewReader(input)
header, err := r.Read()
if err != nil {
return nil, err
}
columns := map[string]int{}
for i, h := range header {
columns[h] = i
}
for _, key := range []string{"symbol", "name", "isin", "figi", "exchange", "country", "mic", "delisted", "primary_listing"} {
if _, ok := columns[key]; !ok {
return nil, errors.New("invalid company snapshot columns")
}
}
c := &Catalog{byID: map[string]Company{}}
scores := map[string]float64{}
for {
row, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, errors.New("invalid company snapshot row")
}
value := func(key string) string { return strings.TrimSpace(row[columns[key]]) }
if !strings.EqualFold(value("delisted"), "false") || !strings.EqualFold(value("primary_listing"), "true") {
continue
}
company := Company{Name: value("name"), YahooSymbol: value("symbol"), ISIN: value("isin"), FIGI: value("figi"), Exchange: value("exchange"), MIC: value("mic"), Country: value("country")}
if company.ISIN != "" {
company.CompanyID = "isin:" + company.ISIN
} else if company.FIGI != "" {
company.CompanyID = "figi:" + company.FIGI
} else {
continue
}
if company.Name == "" || company.YahooSymbol == "" || strings.ContainsAny(company.YahooSymbol, " \r\n\t") {
return nil, errors.New("invalid company snapshot identity")
}
score := 0.0
if column, ok := columns["listing_score"]; ok {
score, err = strconv.ParseFloat(row[column], 64)
if err != nil {
return nil, errors.New("invalid listing score")
}
}
if old, exists := c.byID[company.CompanyID]; exists {
// The upstream primary selector can keep multiple equally primary venues
// for one ISIN. Prefer its score, then a stable representative among those
// already-primary rows. Never promote a non-primary listing.
if score < scores[company.CompanyID] || (score == scores[company.CompanyID] && company.YahooSymbol >= old.YahooSymbol) {
continue
}
}
c.byID[company.CompanyID] = company
scores[company.CompanyID] = score
}
for _, company := range c.byID {
c.companies = append(c.companies, company)
}
sort.Slice(c.companies, func(i, j int) bool {
a, b := c.companies[i], c.companies[j]
if strings.ToLower(a.Name) == strings.ToLower(b.Name) {
return a.CompanyID < b.CompanyID
}
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
})
return c, nil
}
// Name search folds case/spacing only: punctuation from a derivative ticker
// (for example ES=F) must not become unrelated fragments of company names.
func normalizeName(s string) string { return strings.Join(strings.Fields(strings.ToLower(s)), " ") }
func (c *Catalog) SearchCompanies(query string, limit int) ([]Company, error) {
query = normalizeName(query)
if query == "" || limit < 1 || limit > 20 {
return nil, errors.New("invalid company search")
}
out := make([]Company, 0, limit)
for _, company := range c.companies {
if strings.Contains(normalizeName(company.Name), query) {
out = append(out, company)
if len(out) == limit {
break
}
}
}
return out, nil
}
func (c *Catalog) ResolveCompany(id string) (Company, error) {
if company, ok := c.byID[id]; ok {
return company, nil
}
return Company{}, ErrUnknownCompany
}

View File

@ -0,0 +1,72 @@
package companycatalog
import (
"os"
"path/filepath"
"strings"
"testing"
)
// This checks the internal catalog result only; it intentionally does not fix
// an HTTP/public DTO shape. The snapshot is local and pinned, with no network.
func TestSearchReturnsOneCompanyNameAndPrimaryYahooSymbol(t *testing.T) {
catalog, err := NewFinanceDatabaseCatalogFromSnapshot(filepath.Join("testdata", "finance_database_equities_primary_2026-11-22.csv"))
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct{ query, name, companyID, yahoo string }{
{"NVIDIA", "NVIDIA Corporation", "isin:US67066G1040", "NVDA"},
{"Apple", "Apple Inc.", "isin:US0378331005", "AAPL"},
{"Baidu", "Baidu, Inc.", "isin:KYG070341048", "9888.HK"},
{"BYD Company", "BYD Company Limited", "isin:CNE100001526", "002594.SZ"},
{"BYD Electronic", "BYD Electronic (International) Company Limited", "isin:HK0285041858", "0285.HK"},
} {
t.Run(tc.query, func(t *testing.T) {
got, err := catalog.SearchCompanies(tc.query, 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("results=%+v; want one company for %q", got, tc.query)
}
if got[0].Name != tc.name || got[0].CompanyID != tc.companyID || got[0].YahooSymbol != tc.yahoo {
t.Fatalf("company=%+v; want name=%q company_id=%q yahoo=%q", got[0], tc.name, tc.companyID, tc.yahoo)
}
if strings.Contains(got[0].YahooSymbol, " ") || strings.Contains(got[0].YahooSymbol, "INDEX") {
t.Fatalf("non-Yahoo security label leaked as Yahoo symbol %q", got[0].YahooSymbol)
}
})
}
}
func TestCompanyCatalogUsesFIGIFallbackWhenISINIsMissing(t *testing.T) {
path := filepath.Join(t.TempDir(), "local-figi-fallback.csv")
fixture := "symbol,name,exchange,mic,country,isin,figi,composite_figi,delisted,listing_score,primary_listing,main_venue,listings,usual_currency,home_known\n" +
"FALLBACK,Example Company,NMS,XNAS,United States,,BBG000FALLBK,BBG000FALLBK,false,1,true,true,1,true,true\n"
if err := os.WriteFile(path, []byte(fixture), 0o600); err != nil {
t.Fatal(err)
}
catalog, err := NewFinanceDatabaseCatalogFromSnapshot(path)
if err != nil {
t.Fatal(err)
}
got, err := catalog.SearchCompanies("Example Company", 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].CompanyID != "figi:BBG000FALLBK" {
t.Fatalf("company fallback identity=%+v; want figi:BBG000FALLBK", got)
}
}
func TestSearchExcludesNonEquityAssetClasses(t *testing.T) {
catalog, err := NewFinanceDatabaseCatalogFromSnapshot(filepath.Join("testdata", "finance_database_equities_primary_2026-11-22.csv"))
if err != nil {
t.Fatal(err)
}
for _, symbol := range []string{"QQQ", "ES=F", "AAPL260117C00200000"} {
if got, err := catalog.SearchCompanies(symbol, 10); err != nil || len(got) != 0 {
t.Errorf("non-equity %q returned %+v, err=%v", symbol, got, err)
}
}
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Jeroen Bouma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,76 @@
{
"fields": [
"symbol",
"name",
"exchange",
"mic",
"country",
"isin",
"figi",
"composite_figi",
"delisted",
"listing_score",
"primary_listing",
"main_venue",
"listings",
"usual_currency",
"home_known"
],
"identities_with_multiple_primary_rows": 2184,
"license": "MIT",
"license_sha256": "dea317ce7193c52174ebb0def6df1a2f762f75b60e5bc026176fea6cf3ede4ff",
"package_version": "2.5.2",
"primary_listing_evidence": "Unmodified commit-pinned upstream listings_model over the complete local Equities data; no ticker heuristic or provider API.",
"records": 47735,
"rows_without_stable_identity": 2423,
"runtime_identity_policy": "ISIN else FIGI; group identical identity; highest upstream listing_score; equal-score primary rows use symbol lexical tie-break for a deterministic representative; unidentified rows remain embedded but are not searchable/followable.",
"runtime_resolvable_identities": 43126,
"selection": "Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True, as_pandas=False); join get_listing_ranks(); sort symbol",
"sha256": "2b340b0834cef9ac8a3c4baea3eb4428466581211c3fdaa0bdf36481749b70ba",
"snapshot": "equities_primary.csv",
"upstream_commit": "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1",
"upstream_commit_date_utc": "2026-11-17T13:27:37Z",
"upstream_equities_data_file": "compression/equities.parquet",
"upstream_equities_data_sha256": "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f",
"upstream_repository": "https://github.com/JerBouma/FinanceDatabase",
"upstream_source_sha256": {
"financedatabase/__init__.py": "607e4c1f0f772d2f51f6004b06fe4a905441d29142fa1f06988f549ce5c8e794",
"financedatabase/cache_model.py": "1372be4459874b7494c82a9ca8b869803bb843ef6ee5132df67f9f0a710a1e88",
"financedatabase/categories_model.py": "f4f47fd5d90edc476f7ce2cf524977a0dc4115dfacfe2f914c6b3566900648f4",
"financedatabase/cryptos/__init__.py": "896a0c2f55ea897a3f6c136c0e0e33118de0ff9274edccd9ae0bb29b26770d74",
"financedatabase/cryptos/cryptos_controller.py": "953ff91ef8a8043987e2cf1d552332e6cb511f69aa85483186301fee0bb79fc2",
"financedatabase/currencies/__init__.py": "c1884f7dbcc322ea64d210696fec6ed6508e05e63614f35523d8ea44fdc23adc",
"financedatabase/currencies/currencies_controller.py": "a427110863e835e99ecd153d9b5d960520d6052e22aacff7ef0ad994c09b311d",
"financedatabase/database_controller.py": "56b9db9cd3363a8993f13a19bb1530d3d77fef9c945acb75df4ca4c853d6e1d7",
"financedatabase/equities/__init__.py": "55b8e55b48cf515b1ec3e3d1266550e3cf00f21fba584e4394cd2264dc4a84df",
"financedatabase/equities/equities_controller.py": "0fd7d859fa2f43f7c3d43484a21a8d5ccfcdcb2276e2a4a1d1c94eb838b88bc5",
"financedatabase/etfs/__init__.py": "5cb9a938a8130ed8a3af1c19095a5d896f809ca24c50f66586a67b31937304b9",
"financedatabase/etfs/etfs_controller.py": "2944bb089470bafc149b94e6f1719081849be1aec62e702df59fe482a5fc51f0",
"financedatabase/frame_model.py": "1e36264d193952a8ddd51ccd5ccc3b6ad1dea55b3c5041ad68112f2c29210386",
"financedatabase/funds/__init__.py": "e67772c33f8130fa8867723f7b41efe7e9b776ea4107db81e399eaec136e369e",
"financedatabase/funds/funds_controller.py": "9a282674b0ac1c5d925fd65955ac7d66899cd788c1dfc74379aacd2c12bf72a6",
"financedatabase/helpers.py": "87946e2257254b6d6700716c27f6edc964bdb4aeba847cf958f0ec70a9f9bb49",
"financedatabase/indices/__init__.py": "5f5915ef8e0d5e5ef4efe04139db3397ec2a59fc2b8c08e370685959aff51733",
"financedatabase/indices/indices_controller.py": "d67f8b26b3d72de503fc62ae987021a6a9bed78a99bd30a6be203d742a7a514c",
"financedatabase/listings_model.py": "44f9b99fda44019e09c37be241d2fd1cdcf52afd1a6b1d33eb7ac54b7132b48d",
"financedatabase/mcp_server/__init__.py": "9df6de1448fd4d659e8463d6548c90b40b6c47f5492dffc5ceb2b585d3993c18",
"financedatabase/mcp_server/__main__.py": "51796c03ba817474a84161ccbb3900838651acee63a47dec7e95a59d4815363a",
"financedatabase/mcp_server/analytics_model.py": "426775e4d6c8d140b4cc009139ad5ce5e24b31bf32f8cb3dc1620676b8d418f5",
"financedatabase/mcp_server/coercion_model.py": "c309112cd0e76c70e777613a9b9d0bd0c09f0f8522d24a72c1d2dcb0a4e9cdc7",
"financedatabase/mcp_server/formatting_model.py": "2c3d32ec961352782894993b336c4ee58d47bf0ee25b762f5f5bd22688fde546",
"financedatabase/mcp_server/mcp_controller.py": "fe1ebab3086b54855aeecffd4f43bd60257f5ae24fe0dbfdc0e3ea0242431dd7",
"financedatabase/mcp_server/provider_model.py": "22bb45c6f192abbb29cf6aea8ee6b901a204d5960765ae7c10e575f002e9af55",
"financedatabase/mcp_server/ranking_model.py": "f03e03de04fc719a0a4ec6beeeaadb261b403a1ad5b3abf057977af6cc924faa",
"financedatabase/mcp_server/registry_model.py": "a4d4844268ef84fbcae1c82aa16e1ba4be34b0a295936661df13220dd3b4dd46",
"financedatabase/mcp_server/setup_model.py": "69508873479ceacfbdb92a8bacfd988968c773b9adb67193dbcfee2d7acc92be",
"financedatabase/mcp_server/site_model.py": "0cf95f37479086d6753653e382029ec8f2806e654e6d35e6dc611f75cb0e6a2f",
"financedatabase/mcp_server/stats_page_model.py": "c53f4ee51851feb4050b8fb9724ea973c0b95305a205ee78456eb818dff6a9ca",
"financedatabase/mcp_server/tools_model.py": "81cadc7360a3512503d0e126437fde168c7043e4578d7d7214bbba5c38d2cfd1",
"financedatabase/moneymarkets/__init__.py": "d6e552766b18c4c577f730e23e622847f327d71cc0c8009140bdcd6384829cc8",
"financedatabase/moneymarkets/moneymarkets_controller.py": "516f6db36f3cd5195cdbab70bda810575e0b875ce7b43e66087b5be6d336971f",
"financedatabase/query_model.py": "a24ff8c88ffb4f5c4dcf7607e057e8b549b3d5f403539a821ca62935fd54e54b",
"financedatabase/utilities/__init__.py": "8ae00bf057b5f6315fac4999e7a813d4b21696017b76246e44a08e20dc9dc282",
"financedatabase/utilities/dataframe_model.py": "814cab4fca135b5c7b6f50818052c0a318f6bd8466338a8bead0c66270066aee",
"financedatabase/utilities/logger_model.py": "9dcf03c9dca815a1d6a2d0b694f5937f98b4ede2a5e03abf36a19575b4387d92"
}
}

View File

@ -0,0 +1,53 @@
package companycatalog
import (
"bytes"
"crypto/sha256"
"encoding/csv"
"encoding/hex"
"encoding/json"
"os"
"testing"
)
func TestEmbeddedSnapshotIsCompletePinnedAndResolvable(t *testing.T) {
data, err := os.ReadFile("data/manifest.json")
if err != nil {
t.Fatal(err)
}
var manifest struct {
Records int `json:"records"`
SHA256 string `json:"sha256"`
Commit string `json:"upstream_commit"`
}
if err = json.Unmarshal(data, &manifest); err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(embeddedSnapshot)
rows, err := csv.NewReader(bytes.NewReader(embeddedSnapshot)).ReadAll()
if err != nil {
t.Fatal(err)
}
if manifest.Records != 47735 || len(rows)-1 != manifest.Records || hex.EncodeToString(sum[:]) != manifest.SHA256 || manifest.Commit != "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1" {
t.Fatal("incomplete or unpinned embedded snapshot")
}
catalog, err := Default()
if err != nil {
t.Fatal(err)
}
if len(catalog.companies) != 43126 {
t.Fatalf("resolved identities=%d", len(catalog.companies))
}
for id, want := range map[string]string{"isin:US67066G1040": "NVDA", "isin:US0378331005": "AAPL", "isin:KYG070341048": "9888.HK", "isin:CNE100001526": "002594.SZ", "isin:HK0285041858": "0285.HK"} {
company, err := catalog.ResolveCompany(id)
if err != nil || company.YahooSymbol != want {
t.Fatalf("%s resolved to %+v, %v", id, company, err)
}
}
for _, query := range []string{"QQQ", "ES=F", "AAPL260117C00200000"} {
result, err := catalog.SearchCompanies(query, 20)
if err != nil || len(result) != 0 {
t.Fatalf("unexpected non-company search result %q: %+v", query, result)
}
}
}

View File

@ -0,0 +1,191 @@
package companycatalog
import (
"crypto/sha256"
"encoding/csv"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
const testdataDir = "testdata"
type financeDatabaseManifest struct {
UpstreamRepository string `json:"upstream_repository"`
UpstreamCommit string `json:"upstream_commit"`
CommitDate string `json:"upstream_commit_date_utc"`
PackageVersion string `json:"package_version"`
License string `json:"license"`
UpstreamDataFile string `json:"upstream_equities_data_file"`
UpstreamDataSHA256 string `json:"upstream_equities_data_sha256"`
SnapshotDate string `json:"snapshot_date"`
Selection string `json:"selection"`
Evidence string `json:"primary_listing_evidence"`
Fixtures map[string]struct {
SHA256 string `json:"sha256"`
Records int `json:"records"`
} `json:"fixtures"`
}
type financeDatabaseRow struct {
Symbol string
Name string
Exchange string
MIC string
Country string
ISIN string
FIGI string
CompositeFIGI string
Delisted string
ListingScore string
PrimaryListing string
MainVenue string
Listings string
UsualCurrency string
HomeKnown string
}
func readFinanceDatabaseRows(t *testing.T, filename string) []financeDatabaseRow {
t.Helper()
file, err := os.Open(filepath.Join(testdataDir, filename))
if err != nil {
t.Fatal(err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = -1
rows, err := reader.ReadAll()
if err != nil {
t.Fatal(err)
}
if len(rows) < 2 {
t.Fatalf("%s has only %d records", filename, len(rows)-1)
}
columns := make(map[string]int, len(rows[0]))
for i, name := range rows[0] {
columns[name] = i
}
for _, column := range []string{"symbol", "name", "exchange", "mic", "country", "isin", "figi", "composite_figi", "delisted", "listing_score", "primary_listing", "main_venue", "listings", "usual_currency", "home_known"} {
if _, ok := columns[column]; !ok {
t.Fatalf("%s lacks %q column", filename, column)
}
}
out := make([]financeDatabaseRow, 0, len(rows)-1)
for _, values := range rows[1:] {
if len(values) != len(rows[0]) {
t.Fatalf("malformed row in %s: %v", filename, values)
}
value := func(column string) string { return values[columns[column]] }
out = append(out, financeDatabaseRow{
Symbol: value("symbol"), Name: value("name"), Exchange: value("exchange"), MIC: value("mic"),
Country: value("country"), ISIN: value("isin"), FIGI: value("figi"), CompositeFIGI: value("composite_figi"),
Delisted: value("delisted"), ListingScore: value("listing_score"), PrimaryListing: value("primary_listing"),
MainVenue: value("main_venue"), Listings: value("listings"), UsualCurrency: value("usual_currency"), HomeKnown: value("home_known"),
})
}
return out
}
func TestFinanceDatabaseSnapshotHasPinnedRuntimeProvenanceAndChecksums(t *testing.T) {
manifestBytes, err := os.ReadFile(filepath.Join(testdataDir, "finance_database_manifest_2026-11-22.json"))
if err != nil {
t.Fatal(err)
}
var manifest financeDatabaseManifest
if err := json.Unmarshal(manifestBytes, &manifest); err != nil {
t.Fatal(err)
}
if manifest.UpstreamRepository != "https://github.com/JerBouma/FinanceDatabase" || manifest.UpstreamCommit != "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1" || manifest.CommitDate != "2026-11-17T13:27:37Z" {
t.Fatalf("unexpected upstream provenance: %+v", manifest)
}
if manifest.PackageVersion != "2.5.2" || manifest.License != "MIT" || manifest.SnapshotDate != "2026-11-22" {
t.Fatalf("unexpected version/license/date: %+v", manifest)
}
if manifest.UpstreamDataFile != "compression/equities.parquet" || len(manifest.UpstreamDataSHA256) != 64 {
t.Fatalf("manifest lacks the pinned upstream dataset digest: %+v", manifest)
}
if !strings.Contains(manifest.Selection, "Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True)") || manifest.Evidence == "" {
t.Fatal("manifest must state the actual primary-listing selection and its evidence")
}
for name, want := range manifest.Fixtures {
content, err := os.ReadFile(filepath.Join(testdataDir, name))
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(content)
if got := hex.EncodeToString(sum[:]); got != want.SHA256 {
t.Errorf("%s sha256=%s, manifest says %s", name, got, want.SHA256)
}
rows := readFinanceDatabaseRows(t, name)
if len(rows) != want.Records {
t.Errorf("%s records=%d, manifest says %d", name, len(rows), want.Records)
}
}
}
func TestFinanceDatabaseRawMultiListingsAndPrimaryRuntimeSnapshot(t *testing.T) {
raw := readFinanceDatabaseRows(t, "finance_database_raw_multilistings_2026-11-22.csv")
primary := readFinanceDatabaseRows(t, "finance_database_equities_primary_2026-11-22.csv")
rawBySymbol := make(map[string]financeDatabaseRow, len(raw))
for _, row := range raw {
if _, exists := rawBySymbol[row.Symbol]; exists {
t.Fatalf("raw fixture repeats symbol %s", row.Symbol)
}
rawBySymbol[row.Symbol] = row
}
// Keep both the requested Baidu ADR (BIDU) and the two Hong Kong listings in
// the raw data. The upstream selector chooses 9888.HK as primary for Baidu.
for _, symbol := range []string{"NVDA", "AAPL", "BIDU", "9888.HK", "89888.HK", "1211.HK", "002594.SZ", "0285.HK", "BYDIF", "BYDIY"} {
if _, ok := rawBySymbol[symbol]; !ok {
t.Errorf("raw multi-listing fixture lacks %s", symbol)
}
}
if !strings.EqualFold(rawBySymbol["BIDU"].PrimaryListing, "false") || !strings.EqualFold(rawBySymbol["9888.HK"].PrimaryListing, "true") {
t.Errorf("FinanceDatabase primary-listing result for Baidu: BIDU=%s 9888.HK=%s", rawBySymbol["BIDU"].PrimaryListing, rawBySymbol["9888.HK"].PrimaryListing)
}
if !strings.EqualFold(rawBySymbol["1211.HK"].PrimaryListing, "false") || !strings.EqualFold(rawBySymbol["002594.SZ"].PrimaryListing, "true") {
t.Errorf("FinanceDatabase primary-listing result for BYD Co: 1211.HK=%s 002594.SZ=%s", rawBySymbol["1211.HK"].PrimaryListing, rawBySymbol["002594.SZ"].PrimaryListing)
}
if !strings.EqualFold(rawBySymbol["0285.HK"].PrimaryListing, "true") || !strings.EqualFold(rawBySymbol["BYDIF"].PrimaryListing, "false") {
t.Errorf("FinanceDatabase primary-listing result for BYD Electronic: 0285.HK=%s BYDIF=%s", rawBySymbol["0285.HK"].PrimaryListing, rawBySymbol["BYDIF"].PrimaryListing)
}
want := map[string]string{
"NVDA": "NVIDIA Corporation",
"AAPL": "Apple Inc.",
"9888.HK": "Baidu, Inc.",
"002594.SZ": "BYD Company Limited",
"0285.HK": "BYD Electronic (International) Company Limited",
}
got := make(map[string]financeDatabaseRow, len(primary))
nameCounts := make(map[string]int)
for _, row := range primary {
if !strings.EqualFold(row.Delisted, "false") || !strings.EqualFold(row.PrimaryListing, "true") {
t.Errorf("runtime snapshot contains non-primary or delisted row: %+v", row)
}
got[row.Symbol] = row
nameCounts[row.Name]++
}
if len(got) != len(want) {
t.Fatalf("runtime selector snapshot has %d target rows; want %d: %+v", len(got), len(want), got)
}
for symbol, name := range want {
row, ok := got[symbol]
if !ok || row.Name != name {
t.Errorf("runtime primary row %s=%+v; want company %q", symbol, row, name)
}
if nameCounts[name] != 1 {
t.Errorf("runtime snapshot has %d rows for %q; want one", nameCounts[name], name)
}
}
if got["002594.SZ"].Name == got["0285.HK"].Name || got["002594.SZ"].ISIN == got["0285.HK"].ISIN {
t.Fatal("FinanceDatabase runtime snapshot collapsed BYD Co and BYD Electronic")
}
if got["002594.SZ"].ListingScore == "" || got["0285.HK"].ListingScore == "" {
t.Fatal("runtime snapshot lacks selector ranking evidence")
}
}

View File

@ -0,0 +1,6 @@
symbol,name,exchange,mic,country,isin,figi,composite_figi,delisted,listing_score,primary_listing,main_venue,listings,usual_currency,home_known
002594.SZ,BYD Company Limited,SHZ,XSHE,China,CNE100001526,BBG001QVK2K1,BBG000G44NQ0,False,3.999605988967691,True,True,11,True,True
0285.HK,BYD Electronic (International) Company Limited,HKG,XHKG,China,HK0285041858,BBG000JPLTR7,BBG000JPKS36,False,2.4508226691042045,True,True,2,True,True
9888.HK,"Baidu, Inc.",HKG,XHKG,China,KYG070341048,BBG00ZMFX1S5,BBG000Q1VPS8,False,2.4508226691042045,True,True,15,True,True
AAPL,Apple Inc.,NMS,XNAS,United States,US0378331005,BBG000B9Y5X2,BBG000B9XRY4,False,3.7479016786570742,True,True,18,True,True
NVDA,NVIDIA Corporation,NMS,XNAS,United States,US67066G1040,BBG000BBJQV0,BBG000BBJQV0,False,3.7479016786570742,True,True,18,True,True
1 symbol name exchange mic country isin figi composite_figi delisted listing_score primary_listing main_venue listings usual_currency home_known
2 002594.SZ BYD Company Limited SHZ XSHE China CNE100001526 BBG001QVK2K1 BBG000G44NQ0 False 3.999605988967691 True True 11 True True
3 0285.HK BYD Electronic (International) Company Limited HKG XHKG China HK0285041858 BBG000JPLTR7 BBG000JPKS36 False 2.4508226691042045 True True 2 True True
4 9888.HK Baidu, Inc. HKG XHKG China KYG070341048 BBG00ZMFX1S5 BBG000Q1VPS8 False 2.4508226691042045 True True 15 True True
5 AAPL Apple Inc. NMS XNAS United States US0378331005 BBG000B9Y5X2 BBG000B9XRY4 False 3.7479016786570742 True True 18 True True
6 NVDA NVIDIA Corporation NMS XNAS United States US67066G1040 BBG000BBJQV0 BBG000BBJQV0 False 3.7479016786570742 True True 18 True True

View File

@ -0,0 +1,40 @@
{
"source": "FinanceDatabase Equities",
"upstream_repository": "https://github.com/JerBouma/FinanceDatabase",
"upstream_commit": "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1",
"upstream_commit_date_utc": "2026-11-17T13:27:37Z",
"package_version": "2.5.2",
"license": "MIT",
"upstream_equities_data_file": "compression/equities.parquet",
"upstream_equities_data_sha256": "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f",
"snapshot_date": "2026-11-22",
"selection": "Ran pinned source with its commit-pinned local compression data: Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True). The raw fixture contains symbols NVDA, AAPL, BIDU, 9888.HK, 89888.HK, 1211.HK, 002594.SZ, 0285.HK, BYDIF, BYDIY, BYDDF and BYDDY before primary filtering. The runtime fixture contains rows produced by the selector; it was sorted by symbol only after selection for deterministic file ordering.",
"primary_listing_evidence": "Runtime primary_listing flags and listing_score are from upstream listings_model.get_listing_ranks() over the full pinned Equities dataset. Ranking considers exchanges, country/home-market shares, main venues, currency, number of listings, and linked names; not random choice or ticker sorting.",
"fields": [
"symbol",
"name",
"exchange",
"mic",
"country",
"isin",
"figi",
"composite_figi",
"delisted",
"listing_score",
"primary_listing",
"main_venue",
"listings",
"usual_currency",
"home_known"
],
"fixtures": {
"finance_database_raw_multilistings_2026-11-22.csv": {
"sha256": "2ae92b90ba9ec2797d7c27c46b46cff423d6968b36e91576ae488b53fdba19cd",
"records": 12
},
"finance_database_equities_primary_2026-11-22.csv": {
"sha256": "977d473bd05658406631b9fac829ac628ab057ff240868b9fd38314fd7848732",
"records": 5
}
}
}

View File

@ -0,0 +1,13 @@
symbol,name,exchange,mic,country,isin,figi,composite_figi,delisted,listing_score,primary_listing,main_venue,listings,usual_currency,home_known
002594.SZ,BYD Company Limited,SHZ,XSHE,China,CNE100001526,BBG001QVK2K1,BBG000G44NQ0,False,3.999605988967691,True,True,11,True,True
0285.HK,BYD Electronic (International) Company Limited,HKG,XHKG,China,HK0285041858,BBG000JPLTR7,BBG000JPKS36,False,2.4508226691042045,True,True,2,True,True
1211.HK,"BYD Co., Ltd.",HKG,XHKG,China,CNE100000296,BBG000G6RLL9,BBG000G6RL93,False,2.4508226691042045,False,True,11,True,True
89888.HK,"Baidu, Inc.",HKG,XHKG,China,KYG070341048,BBG01GXJWMV7,BBG01GXJWMT0,False,2.4508226691042045,False,True,15,False,True
9888.HK,"Baidu, Inc.",HKG,XHKG,China,KYG070341048,BBG00ZMFX1S5,BBG000Q1VPS8,False,2.4508226691042045,True,True,15,True,True
AAPL,Apple Inc.,NMS,XNAS,United States,US0378331005,BBG000B9Y5X2,BBG000B9XRY4,False,3.7479016786570742,True,True,18,True,True
BIDU,"Baidu, Inc.",NMS,XNAS,China,KYG070341048,BBG000QXWHD1,BBG000QXWHD1,False,1.0584459696877415,False,True,15,True,True
BYDDF,"BYD Co., Ltd.",PNK,OTCM,China,CNE100000296,BBG000NZG2R5,BBG000NZG2R5,False,0.0,False,False,11,True,True
BYDDY,"BYD Co., Ltd.",PNK,OTCM,China,US05606L1008,BBG000SFXPB1,BBG000SFXPB1,False,0.0,False,False,11,True,True
BYDIF,BYD Electronic (International) Company Limited,PNK,OTCM,China,HK0285041858,BBG000VKK8W5,BBG000VKK8W5,False,0.0,False,False,2,True,True
BYDIY,BYD Electronic (International) Company Limited,PNK,OTCM,China,US1243121092,BBG004WFYQV3,BBG004WFYQV3,False,0.0,False,False,2,True,True
NVDA,NVIDIA Corporation,NMS,XNAS,United States,US67066G1040,BBG000BBJQV0,BBG000BBJQV0,False,3.7479016786570742,True,True,18,True,True
1 symbol name exchange mic country isin figi composite_figi delisted listing_score primary_listing main_venue listings usual_currency home_known
2 002594.SZ BYD Company Limited SHZ XSHE China CNE100001526 BBG001QVK2K1 BBG000G44NQ0 False 3.999605988967691 True True 11 True True
3 0285.HK BYD Electronic (International) Company Limited HKG XHKG China HK0285041858 BBG000JPLTR7 BBG000JPKS36 False 2.4508226691042045 True True 2 True True
4 1211.HK BYD Co., Ltd. HKG XHKG China CNE100000296 BBG000G6RLL9 BBG000G6RL93 False 2.4508226691042045 False True 11 True True
5 89888.HK Baidu, Inc. HKG XHKG China KYG070341048 BBG01GXJWMV7 BBG01GXJWMT0 False 2.4508226691042045 False True 15 False True
6 9888.HK Baidu, Inc. HKG XHKG China KYG070341048 BBG00ZMFX1S5 BBG000Q1VPS8 False 2.4508226691042045 True True 15 True True
7 AAPL Apple Inc. NMS XNAS United States US0378331005 BBG000B9Y5X2 BBG000B9XRY4 False 3.7479016786570742 True True 18 True True
8 BIDU Baidu, Inc. NMS XNAS China KYG070341048 BBG000QXWHD1 BBG000QXWHD1 False 1.0584459696877415 False True 15 True True
9 BYDDF BYD Co., Ltd. PNK OTCM China CNE100000296 BBG000NZG2R5 BBG000NZG2R5 False 0.0 False False 11 True True
10 BYDDY BYD Co., Ltd. PNK OTCM China US05606L1008 BBG000SFXPB1 BBG000SFXPB1 False 0.0 False False 11 True True
11 BYDIF BYD Electronic (International) Company Limited PNK OTCM China HK0285041858 BBG000VKK8W5 BBG000VKK8W5 False 0.0 False False 2 True True
12 BYDIY BYD Electronic (International) Company Limited PNK OTCM China US1243121092 BBG004WFYQV3 BBG004WFYQV3 False 0.0 False False 2 True True
13 NVDA NVIDIA Corporation NMS XNAS United States US67066G1040 BBG000BBJQV0 BBG000BBJQV0 False 3.7479016786570742 True True 18 True True

View File

@ -0,0 +1,3 @@
-- No destructive downgrade: removing company identity would collapse independent
-- catalogue and legacy follows. Restore a backup or explicitly reconcile first.
DO $$ BEGIN RAISE EXCEPTION '000017 cannot be reverted without explicit company/legacy reconciliation'; END $$;

View File

@ -0,0 +1,13 @@
BEGIN;
ALTER TABLE user_assets ADD COLUMN company_id TEXT NULL,
ADD COLUMN yahoo_symbol TEXT NULL,
ADD COLUMN company_exchange TEXT NULL,
ADD COLUMN company_country TEXT NULL,
ADD COLUMN company_mic TEXT NULL;
CREATE UNIQUE INDEX user_assets_company_unique ON user_assets(user_id,company_id) WHERE company_id IS NOT NULL;
-- Legacy identities remain independent of catalogue follows, even for the same FIGI.
DROP INDEX IF EXISTS user_assets_legacy_symbol_unique;
DROP INDEX IF EXISTS user_assets_figi_unique;
CREATE UNIQUE INDEX user_assets_legacy_symbol_unique ON user_assets(user_id,symbol) WHERE figi IS NULL AND company_id IS NULL;
CREATE UNIQUE INDEX user_assets_figi_unique ON user_assets(user_id,figi) WHERE figi IS NOT NULL AND company_id IS NULL;
COMMIT;

View File

@ -0,0 +1,126 @@
package migrations
import (
"database/sql"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/lib/pq"
)
func TestTicket19CompanyCatalogMigrationIsAdditiveAndKeepsLegacyIndexAssetsPostgres(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
if os.Getenv("TEST_DATABASE_REQUIRED") == "1" {
t.Fatal("TEST_DATABASE_REQUIRED=1 but TEST_DATABASE_URL is empty")
}
t.Skip("TEST_DATABASE_URL absent: isolated PostgreSQL required")
}
db, err := sql.Open("postgres", dsn)
if err != nil {
t.Fatal(err)
}
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("ticket19_company_migration_%d", time.Now().UnixNano())
if _, err := db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
db.Close()
t.Fatal(err)
}
if _, err := db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
db.Close()
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
_ = db.Close()
})
const owner = "00000000-0000-0000-0000-000000000191"
for _, statement := range []string{
`CREATE TABLE users (id UUID PRIMARY KEY)`,
`CREATE TABLE user_assets (id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, symbol VARCHAR(20) NOT NULL, name TEXT NOT NULL DEFAULT '', figi TEXT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE UNIQUE INDEX user_assets_legacy_symbol_unique ON user_assets(user_id,symbol) WHERE figi IS NULL`,
`CREATE UNIQUE INDEX user_assets_figi_unique ON user_assets(user_id,figi) WHERE figi IS NOT NULL`,
`INSERT INTO users(id) VALUES ('` + owner + `')`,
`INSERT INTO users(id) VALUES ('00000000-0000-0000-0000-000000000193')`,
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000191','` + owner + `','LEGACY','Historic company asset',NULL)`,
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000192','` + owner + `','SPX','Historic index asset','BBG000SPX001')`,
} {
if _, err := db.Exec(statement); err != nil {
t.Fatal(err)
}
}
up, err := os.ReadFile("000017_company_catalog.up.sql")
if err != nil {
t.Fatalf("read additive company-catalog migration 000017: %v", err)
}
upSQL := strings.ToLower(string(up))
if !strings.Contains(upSQL, "company_id") {
t.Fatalf("migration must add string company_id for new catalog-backed follow rows: %s", upSQL)
}
for _, destructive := range []string{"delete from user_assets", "truncate user_assets", "drop table user_assets", "create table companies"} {
if strings.Contains(upSQL, destructive) {
t.Errorf("company-catalog migration must preserve assets and avoid a dynamic companies table; found %q", destructive)
}
}
if _, err := db.Exec(string(up)); err != nil {
t.Fatalf("apply company-catalog migration to legacy schema: %v", err)
}
var companyIDType string
if err := db.QueryRow(`SELECT data_type FROM information_schema.columns WHERE table_schema=$1 AND table_name='user_assets' AND column_name='company_id'`, schema).Scan(&companyIDType); err != nil {
t.Fatalf("read company_id column type: %v", err)
}
if companyIDType != "text" && companyIDType != "character varying" {
t.Fatalf("company_id data type=%q; want an opaque string, not UUID", companyIDType)
}
rows, err := db.Query(`SELECT id::text,user_id::text,symbol,name,figi,company_id FROM user_assets ORDER BY id`)
if err != nil {
t.Fatal(err)
}
type assetRow struct {
id, userID, symbol, name string
figi, companyID sql.NullString
}
var got []assetRow
for rows.Next() {
var row assetRow
if err := rows.Scan(&row.id, &row.userID, &row.symbol, &row.name, &row.figi, &row.companyID); err != nil {
rows.Close()
t.Fatal(err)
}
got = append(got, row)
}
if err := rows.Err(); err != nil {
rows.Close()
t.Fatal(err)
}
rows.Close()
if len(got) != 2 {
t.Fatalf("legacy/index asset rows=%d, want both rows preserved: %+v", len(got), got)
}
if got[0].id != "00000000-0000-0000-0000-000000000191" || got[0].userID != owner || got[0].symbol != "LEGACY" || got[0].name != "Historic company asset" || got[0].figi.Valid || got[0].companyID.Valid {
t.Errorf("legacy asset was changed by migration: %+v", got[0])
}
if got[1].id != "00000000-0000-0000-0000-000000000192" || got[1].userID != owner || got[1].symbol != "SPX" || got[1].name != "Historic index asset" || !got[1].figi.Valid || got[1].figi.String != "BBG000SPX001" || got[1].companyID.Valid {
t.Errorf("historical index asset was changed or converted by migration: %+v", got[1])
}
for i, identity := range []string{"isin:KYG070341048", "figi:BBG000BBJQV0"} {
id := fmt.Sprintf("00000000-0000-0000-0000-00000000019%d", 3+i)
symbol := fmt.Sprintf("catalog-%d", i)
if _, err := db.Exec(`INSERT INTO user_assets(id,user_id,symbol,name,figi,company_id) VALUES ($1,$2,$3,'catalog asset',NULL,$4)`, id, owner, symbol, identity); err != nil {
t.Fatalf("insert opaque company identity %q: %v", identity, err)
}
}
if _, err := db.Exec(`INSERT INTO user_assets(id,user_id,symbol,name,figi,company_id) VALUES ('00000000-0000-0000-0000-000000000195',$1,'duplicate','duplicate catalog identity',NULL,'isin:KYG070341048')`, owner); err == nil {
t.Fatal("duplicate owner/company_id must be rejected for idempotent application upserts")
}
if _, err := db.Exec(`INSERT INTO user_assets(id,user_id,symbol,name,figi,company_id) VALUES ('00000000-0000-0000-0000-000000000196','00000000-0000-0000-0000-000000000193','other-owner','same company other owner',NULL,'isin:KYG070341048')`); err != nil {
t.Fatalf("same company identity should be allowed for another owner: %v", err)
}
}

View File

@ -11,6 +11,7 @@ import (
"sync"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
@ -18,10 +19,11 @@ import (
type Fixtures struct {
SummaryModelID string `json:"summaryModelID"`
IndexQuery string `json:"indexQuery"`
IndexName string `json:"indexName"`
IndexSymbol string `json:"indexSymbol"`
IndexFIGI string `json:"indexFIGI"`
CompanyQuery string `json:"companyQuery"`
CompanyID string `json:"companyID"`
CompanyName string `json:"companyName"`
CompanySymbol string `json:"companySymbol"`
CompanyFIGI string `json:"companyFIGI"`
SummarySentinel string `json:"summarySentinel"`
ArticleTitle string `json:"articleTitle"`
ArticleURL string `json:"articleURL"`
@ -30,15 +32,44 @@ type Fixtures struct {
}
func DefaultFixtures() Fixtures {
return Fixtures{"00000000-0000-0000-0000-000000001203", "E2E index", "E2E Financial Index", "E2EIDX", "BBG000E2E001", "E2E synthesized financial summary", "E2E private article title", "https://fixture.invalid/private-article", "E2E private article body", "pending-candidate-id"}
return Fixtures{"00000000-0000-0000-0000-000000001203", "E2E Company", "isin:US0000000001", "E2E Company Inc.", "E2ECO", "BBG000E2E001", "E2E synthesized financial summary", "E2E private article title", "https://fixture.invalid/private-article", "E2E private article body", "pending-candidate-id"}
}
type Event struct {
Model string `json:"model,omitempty"`
Kind string `json:"kind"`
Query string `json:"query,omitempty"`
CompanyID string `json:"company_id,omitempty"`
Symbols []string `json:"symbols,omitempty"`
CandidateID string `json:"candidate_id,omitempty"`
}
// FakeCompanyCatalog keeps the browser journey deterministic and entirely
// local. It exercises the production catalog port without OpenFIGI traffic.
type FakeCompanyCatalog struct{ Fakes *Fakes }
func (c FakeCompanyCatalog) SearchCompanies(query string, limit int) ([]companycatalog.Company, error) {
company := c.Fakes.company()
c.Fakes.record(Event{Kind: "companySearches", Query: query})
if limit < 1 || !strings.Contains(strings.ToLower(company.Name), strings.ToLower(strings.TrimSpace(query))) {
return []companycatalog.Company{}, nil
}
return []companycatalog.Company{company}, nil
}
func (c FakeCompanyCatalog) ResolveCompany(companyID string) (companycatalog.Company, error) {
company := c.Fakes.company()
c.Fakes.record(Event{Kind: "companyResolutions", CompanyID: companyID})
if companyID != company.CompanyID {
return companycatalog.Company{}, companycatalog.ErrUnknownCompany
}
return company, nil
}
func (f *Fakes) company() companycatalog.Company {
return companycatalog.Company{CompanyID: f.Fixture.CompanyID, Name: f.Fixture.CompanyName, YahooSymbol: f.Fixture.CompanySymbol, FIGI: f.Fixture.CompanyFIGI, Exchange: "E2E Exchange", MIC: "XEEE", Country: "E2E Country"}
}
type Fakes struct {
mu sync.Mutex
Fixture Fixtures
@ -60,7 +91,7 @@ func (f *Fakes) Handler() http.Handler {
mux.HandleFunc("/audit", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]any{"openfigiSearches": f.counts["openfigiSearches"], "scraperCalls": f.counts["scraperCalls"], "layaRankingCalls": f.counts["layaRankingCalls"], "layaSummaryCalls": f.counts["layaSummaryCalls"], "events": f.Events})
_ = json.NewEncoder(w).Encode(map[string]any{"openfigiSearches": f.counts["openfigiSearches"], "companySearches": f.counts["companySearches"], "companyResolutions": f.counts["companyResolutions"], "scraperCalls": f.counts["scraperCalls"], "layaRankingCalls": f.counts["layaRankingCalls"], "layaSummaryCalls": f.counts["layaSummaryCalls"], "events": f.Events})
})
mux.HandleFunc("/v3/search", func(w http.ResponseWriter, r *http.Request) {
var req struct {
@ -72,7 +103,7 @@ func (f *Fakes) Handler() http.Handler {
return
}
f.record(Event{Kind: "openfigiSearches"})
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]string{{"name": f.Fixture.IndexName, "ticker": f.Fixture.IndexSymbol, "figi": f.Fixture.IndexFIGI, "marketSector": "Index"}}})
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]string{{"name": f.Fixture.CompanyName, "ticker": f.Fixture.CompanySymbol, "figi": f.Fixture.CompanyFIGI, "marketSector": "Index"}}})
})
mux.HandleFunc("/scrape", func(w http.ResponseWriter, r *http.Request) {
var symbols []string

View File

@ -0,0 +1,32 @@
package generation
import (
"github.com/tradarr/backend/internal/models"
"regexp"
"strings"
)
var yahooTicker = regexp.MustCompile(`^[A-Za-z0-9^][A-Za-z0-9.^=\-]{0,31}$`)
var figiIdentity = regexp.MustCompile(`^BBG[A-Z0-9]{9}$`)
// Only the Yahoo source gets the catalogue's Yahoo listing hint. Other feeds
// retain the exact historical Symbol input. No guesses or Bloomberg conversion.
func yahooSymbols(assets []models.UserAsset) []string {
out := []string{}
seen := map[string]bool{}
for _, a := range assets {
symbol := a.Symbol
if a.CompanyID != nil {
if a.YahooSymbol == nil {
continue
}
symbol = *a.YahooSymbol
}
if !yahooTicker.MatchString(symbol) || figiIdentity.MatchString(strings.ToUpper(symbol)) || seen[symbol] {
continue
}
seen[symbol] = true
out = append(out, symbol)
}
return out
}

View File

@ -0,0 +1,46 @@
package generation
import (
"context"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"reflect"
"testing"
)
func pointer(s string) *string { return &s }
func TestYahooSymbolsUseResolvedPrimaryWithoutBloombergOrFIGI(t *testing.T) {
assets := []models.UserAsset{
{CompanyID: pointer("isin:KYG070341048"), Name: "Baidu, Inc.", Symbol: "OLD_BLOOMBERG", YahooSymbol: pointer("9888.HK")},
{Symbol: "SSAAPL INDEX"}, {Symbol: "BBG000BBJQV0"}, {Symbol: "NVDA"}, {Symbol: "NVDA"},
{CompanyID: pointer("isin:unknown"), Symbol: "CLIENT-SPOOF"},
}
if got := yahooSymbols(assets); !reflect.DeepEqual(got, []string{"9888.HK", "NVDA"}) {
t.Fatalf("Yahoo input=%v", got)
}
}
type symbolFeed struct{ symbols []string }
func (f *symbolFeed) Name() string { return "fake" }
func (f *symbolFeed) Scrape(_ context.Context, s []string) ([]scraper.Article, error) {
f.symbols = s
return nil, nil
}
func TestPerSourceCompanyHintsDoNotChangeOtherFeeds(t *testing.T) {
yahoo, bloomberg, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{}
input := UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 20, Assets: []models.UserAsset{{CompanyID: pointer("isin:company"), Name: "Company", Symbol: "HISTORIC INDEX", YahooSymbol: pointer("9888.HK")}}}
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceWatcherGuru} {
key := key
input.Sources = append(input.Sources, models.Source{ID: key, SourceKey: &key, Enabled: true, ArticleLimit: 20})
}
repo := &contractRepository{inputs: map[string]UserInput{"owner": input}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceWatcherGuru: watcher}})
if _, err := uc.Generate(context.Background(), "owner"); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(watcher.symbols, bloomberg.symbols) {
t.Fatalf("Yahoo=%v Bloomberg=%v Watcher=%v", yahoo.symbols, bloomberg.symbols, watcher.symbols)
}
}

View File

@ -168,7 +168,11 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
if feed == nil {
err = fmt.Errorf("unavailable")
} else {
articles, err = feed.Scrape(ctx, append([]string(nil), symbols...))
sourceSymbols := symbols
if *source.SourceKey == models.SourceYahooFinance {
sourceSymbols = yahooSymbols(input.Assets)
}
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
}
if err != nil {
stat.Status = "failed"

View File

@ -0,0 +1,33 @@
package models
import (
"github.com/tradarr/backend/internal/companycatalog"
)
// UpsertCompanyAsset never converts legacy rows. Each owner/company identity
// has an independent follow, resolved from the trusted local catalogue.
func (r *Repository) UpsertCompanyAsset(owner string, company companycatalog.Company) (*UserAsset, error) {
tx, err := r.db.Begin()
if err != nil {
return nil, err
}
defer tx.Rollback()
if _, err = tx.Exec(`SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, owner); err != nil {
return nil, err
}
a := &UserAsset{}
err = tx.QueryRow(`INSERT INTO user_assets(user_id,symbol,name,figi,company_id,yahoo_symbol,company_exchange,company_country,company_mic)
VALUES($1,$2::text,$3,NULLIF($4,''),$5,$2::text,$6,$7,$8)
ON CONFLICT(user_id,company_id) WHERE company_id IS NOT NULL DO UPDATE SET
symbol=EXCLUDED.symbol,name=EXCLUDED.name,figi=EXCLUDED.figi,yahoo_symbol=EXCLUDED.yahoo_symbol,
company_exchange=EXCLUDED.company_exchange,company_country=EXCLUDED.company_country,company_mic=EXCLUDED.company_mic
RETURNING id,user_id,symbol,name,figi,created_at,company_id,yahoo_symbol,company_exchange,company_country,company_mic`,
owner, company.YahooSymbol, company.Name, company.FIGI, company.CompanyID, company.Exchange, company.Country, company.MIC).Scan(&a.ID, &a.UserID, &a.Symbol, &a.Name, &a.FIGI, &a.CreatedAt, &a.CompanyID, &a.YahooSymbol, &a.CompanyExchange, &a.CompanyCountry, &a.CompanyMIC)
if err != nil {
return nil, err
}
if err = tx.Commit(); err != nil {
return nil, err
}
return a, nil
}

View File

@ -22,12 +22,17 @@ type User struct {
}
type UserAsset struct {
FIGI *string `json:"figi"`
ID string `json:"id"`
UserID string `json:"user_id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
CompanyID *string `json:"company_id"`
YahooSymbol *string `json:"-"`
CompanyExchange *string `json:"exchange,omitempty"`
CompanyCountry *string `json:"country,omitempty"`
CompanyMIC *string `json:"mic,omitempty"`
FIGI *string `json:"figi"`
ID string `json:"id"`
UserID string `json:"user_id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
}
type Source struct {

View File

@ -17,14 +17,18 @@ func scanAsset(row assetScanner) (*UserAsset, error) {
}
func (r *Repository) GetUserAssets(userID string) ([]UserAsset, error) {
rows, err := r.db.Query(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 ORDER BY symbol,created_at,id`, userID)
rows, err := r.db.Query(`SELECT id,user_id,symbol,name,figi,created_at,
to_jsonb(user_assets)->>'company_id',to_jsonb(user_assets)->>'yahoo_symbol',
to_jsonb(user_assets)->>'company_exchange',to_jsonb(user_assets)->>'company_country',to_jsonb(user_assets)->>'company_mic'
FROM user_assets WHERE user_id=$1 ORDER BY symbol,created_at,id`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
assets := []UserAsset{}
for rows.Next() {
a, err := scanAsset(rows)
a := &UserAsset{}
err := rows.Scan(&a.ID, &a.UserID, &a.Symbol, &a.Name, &a.FIGI, &a.CreatedAt, &a.CompanyID, &a.YahooSymbol, &a.CompanyExchange, &a.CompanyCountry, &a.CompanyMIC)
if err != nil {
return nil, err
}
@ -62,19 +66,24 @@ func (r *Repository) UpsertUserAsset(userID, symbol, name string, figi *string)
return a, tx.Commit()
}
if figi == nil {
return finish(scanAsset(tx.QueryRow(`INSERT INTO user_assets(user_id,symbol,name,figi) VALUES($1,$2,$3,NULL)
ON CONFLICT(user_id,symbol) WHERE figi IS NULL DO UPDATE SET name=EXCLUDED.name
RETURNING id,user_id,symbol,name,figi,created_at`, userID, symbol, name)))
existing, lookupErr := scanAsset(tx.QueryRow(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND symbol=$2 AND figi IS NULL AND to_jsonb(user_assets)->>'company_id' IS NULL`, userID, symbol))
if lookupErr == nil {
return finish(scanAsset(tx.QueryRow(`UPDATE user_assets SET name=$1 WHERE id=$2 AND user_id=$3 RETURNING id,user_id,symbol,name,figi,created_at`, name, existing.ID, userID)))
}
if lookupErr != sql.ErrNoRows {
return nil, lookupErr
}
return finish(scanAsset(tx.QueryRow(`INSERT INTO user_assets(user_id,symbol,name,figi) VALUES($1,$2,$3,NULL) RETURNING id,user_id,symbol,name,figi,created_at`, userID, symbol, name)))
}
// A known FIGI remains canonical even when other rows share its symbol.
a, err := scanAsset(tx.QueryRow(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND figi=$2`, userID, *figi))
a, err := scanAsset(tx.QueryRow(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND figi=$2 AND to_jsonb(user_assets)->>'company_id' IS NULL`, userID, *figi))
if err == nil {
return finish(scanAsset(tx.QueryRow(`UPDATE user_assets SET symbol=$1,name=$2 WHERE id=$3 AND user_id=$4 RETURNING id,user_id,symbol,name,figi,created_at`, symbol, name, a.ID, userID)))
}
if err != sql.ErrNoRows {
return nil, err
}
rows, err := tx.Query(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND UPPER(BTRIM(symbol))=$2 FOR UPDATE`, userID, symbol)
rows, err := tx.Query(`SELECT id,user_id,symbol,name,figi,created_at FROM user_assets WHERE user_id=$1 AND UPPER(BTRIM(symbol))=$2 AND to_jsonb(user_assets)->>'company_id' IS NULL FOR UPDATE`, userID, symbol)
if err != nil {
return nil, err
}
@ -107,7 +116,7 @@ func (r *Repository) UpsertUserAsset(userID, symbol, name string, figi *string)
}
func (r *Repository) RemoveUserAsset(userID, symbol string) error {
_, err := r.db.Exec(`DELETE FROM user_assets WHERE user_id=$1 AND symbol=$2 AND figi IS NULL`, userID, strings.ToUpper(strings.TrimSpace(symbol)))
_, err := r.db.Exec(`DELETE FROM user_assets WHERE user_id=$1 AND symbol=$2 AND figi IS NULL AND to_jsonb(user_assets)->>'company_id' IS NULL`, userID, strings.ToUpper(strings.TrimSpace(symbol)))
return err
}
func (r *Repository) RemoveUserAssetByID(userID, id string) error {

View File

@ -7,6 +7,7 @@ import (
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/generation"
@ -18,6 +19,7 @@ import (
)
type Dependencies struct {
CompanyCatalog companycatalog.CompanyCatalog
LayaRanker generation.LayaRanker
Feeds map[string]scraper.Scraper
IndexSearcher indices.IndexSearcher
@ -47,6 +49,9 @@ func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
h.SetGenerationUseCase(uc)
h.SetIndexSearcher(deps.IndexSearcher)
if deps.CompanyCatalog != nil {
h.SetCompanyCatalog(deps.CompanyCatalog)
}
return &App{Router: api.SetupRouter(h, cfg.JWTSecret), scheduler: sched}
}
func (a *App) Close() { a.scheduler.Stop() }

View File

@ -0,0 +1,11 @@
certifi==2026.11.20
charset-normalizer==3.5.2
idna==3.20
numpy==2.4.6
pandas==3.0.3
polars==2.1.0
polars-runtime-32==2.1.0
python-dateutil==4.0.0
requests==2.34.2
tzdata==2026.6
urllib3==2.8.0

View File

@ -0,0 +1,45 @@
{
"license_sha256": "dea317ce7193c52174ebb0def6df1a2f762f75b60e5bc026176fea6cf3ede4ff",
"upstream_commit": "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1",
"upstream_equities_data_sha256": "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f",
"upstream_source_sha256": {
"financedatabase/__init__.py": "607e4c1f0f772d2f51f6004b06fe4a905441d29142fa1f06988f549ce5c8e794",
"financedatabase/cache_model.py": "1372be4459874b7494c82a9ca8b869803bb843ef6ee5132df67f9f0a710a1e88",
"financedatabase/categories_model.py": "f4f47fd5d90edc476f7ce2cf524977a0dc4115dfacfe2f914c6b3566900648f4",
"financedatabase/cryptos/__init__.py": "896a0c2f55ea897a3f6c136c0e0e33118de0ff9274edccd9ae0bb29b26770d74",
"financedatabase/cryptos/cryptos_controller.py": "953ff91ef8a8043987e2cf1d552332e6cb511f69aa85483186301fee0bb79fc2",
"financedatabase/currencies/__init__.py": "c1884f7dbcc322ea64d210696fec6ed6508e05e63614f35523d8ea44fdc23adc",
"financedatabase/currencies/currencies_controller.py": "a427110863e835e99ecd153d9b5d960520d6052e22aacff7ef0ad994c09b311d",
"financedatabase/database_controller.py": "56b9db9cd3363a8993f13a19bb1530d3d77fef9c945acb75df4ca4c853d6e1d7",
"financedatabase/equities/__init__.py": "55b8e55b48cf515b1ec3e3d1266550e3cf00f21fba584e4394cd2264dc4a84df",
"financedatabase/equities/equities_controller.py": "0fd7d859fa2f43f7c3d43484a21a8d5ccfcdcb2276e2a4a1d1c94eb838b88bc5",
"financedatabase/etfs/__init__.py": "5cb9a938a8130ed8a3af1c19095a5d896f809ca24c50f66586a67b31937304b9",
"financedatabase/etfs/etfs_controller.py": "2944bb089470bafc149b94e6f1719081849be1aec62e702df59fe482a5fc51f0",
"financedatabase/frame_model.py": "1e36264d193952a8ddd51ccd5ccc3b6ad1dea55b3c5041ad68112f2c29210386",
"financedatabase/funds/__init__.py": "e67772c33f8130fa8867723f7b41efe7e9b776ea4107db81e399eaec136e369e",
"financedatabase/funds/funds_controller.py": "9a282674b0ac1c5d925fd65955ac7d66899cd788c1dfc74379aacd2c12bf72a6",
"financedatabase/helpers.py": "87946e2257254b6d6700716c27f6edc964bdb4aeba847cf958f0ec70a9f9bb49",
"financedatabase/indices/__init__.py": "5f5915ef8e0d5e5ef4efe04139db3397ec2a59fc2b8c08e370685959aff51733",
"financedatabase/indices/indices_controller.py": "d67f8b26b3d72de503fc62ae987021a6a9bed78a99bd30a6be203d742a7a514c",
"financedatabase/listings_model.py": "44f9b99fda44019e09c37be241d2fd1cdcf52afd1a6b1d33eb7ac54b7132b48d",
"financedatabase/mcp_server/__init__.py": "9df6de1448fd4d659e8463d6548c90b40b6c47f5492dffc5ceb2b585d3993c18",
"financedatabase/mcp_server/__main__.py": "51796c03ba817474a84161ccbb3900838651acee63a47dec7e95a59d4815363a",
"financedatabase/mcp_server/analytics_model.py": "426775e4d6c8d140b4cc009139ad5ce5e24b31bf32f8cb3dc1620676b8d418f5",
"financedatabase/mcp_server/coercion_model.py": "c309112cd0e76c70e777613a9b9d0bd0c09f0f8522d24a72c1d2dcb0a4e9cdc7",
"financedatabase/mcp_server/formatting_model.py": "2c3d32ec961352782894993b336c4ee58d47bf0ee25b762f5f5bd22688fde546",
"financedatabase/mcp_server/mcp_controller.py": "fe1ebab3086b54855aeecffd4f43bd60257f5ae24fe0dbfdc0e3ea0242431dd7",
"financedatabase/mcp_server/provider_model.py": "22bb45c6f192abbb29cf6aea8ee6b901a204d5960765ae7c10e575f002e9af55",
"financedatabase/mcp_server/ranking_model.py": "f03e03de04fc719a0a4ec6beeeaadb261b403a1ad5b3abf057977af6cc924faa",
"financedatabase/mcp_server/registry_model.py": "a4d4844268ef84fbcae1c82aa16e1ba4be34b0a295936661df13220dd3b4dd46",
"financedatabase/mcp_server/setup_model.py": "69508873479ceacfbdb92a8bacfd988968c773b9adb67193dbcfee2d7acc92be",
"financedatabase/mcp_server/site_model.py": "0cf95f37479086d6753653e382029ec8f2806e654e6d35e6dc611f75cb0e6a2f",
"financedatabase/mcp_server/stats_page_model.py": "c53f4ee51851feb4050b8fb9724ea973c0b95305a205ee78456eb818dff6a9ca",
"financedatabase/mcp_server/tools_model.py": "81cadc7360a3512503d0e126437fde168c7043e4578d7d7214bbba5c38d2cfd1",
"financedatabase/moneymarkets/__init__.py": "d6e552766b18c4c577f730e23e622847f327d71cc0c8009140bdcd6384829cc8",
"financedatabase/moneymarkets/moneymarkets_controller.py": "516f6db36f3cd5195cdbab70bda810575e0b875ce7b43e66087b5be6d336971f",
"financedatabase/query_model.py": "a24ff8c88ffb4f5c4dcf7607e057e8b549b3d5f403539a821ca62935fd54e54b",
"financedatabase/utilities/__init__.py": "8ae00bf057b5f6315fac4999e7a813d4b21696017b76246e44a08e20dc9dc282",
"financedatabase/utilities/dataframe_model.py": "814cab4fca135b5c7b6f50818052c0a318f6bd8466338a8bead0c66270066aee",
"financedatabase/utilities/logger_model.py": "9dcf03c9dca815a1d6a2d0b694f5937f98b4ede2a5e03abf36a19575b4387d92"
}
}

View File

@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Explicit maintenance only. Never imported/called by the application.
Run with pinned dependencies in company-catalog-requirements.txt and -E.
--source-dir uses an already downloaded upstream checkout completely offline.
--download explicitly downloads only the pinned official source archive.
"""
import argparse
import hashlib
import io
import json
import os
from pathlib import Path
import shutil
import socket
import sys
import tarfile
import tempfile
import urllib.request
COMMIT = "93b872f0e4b4e05e8d35b7f0a39efe9245bcc2c1"
DATA_HASH = "decfcf03f1294dabe09a591a5015775dc49a5a54a3536e35b4869659a5123f7f"
FIELDS = "symbol name exchange mic country isin figi composite_figi delisted listing_score primary_listing main_venue listings usual_currency home_known".split()
ROOT = Path(__file__).resolve().parents[1]
def digest(content):
return hashlib.sha256(content).hexdigest()
def generate(source, destination):
parquet = source / "compression/equities.parquet"
if digest(parquet.read_bytes()) != DATA_HASH:
raise SystemExit("Pinned equities parquet hash mismatch")
lock = json.loads((ROOT / "scripts/company-catalog-upstream.json").read_text())
if lock["upstream_commit"] != COMMIT or lock["upstream_equities_data_sha256"] != DATA_HASH:
raise SystemExit("Upstream lock and generator constants disagree")
for name, expected in lock["upstream_source_sha256"].items():
if digest((source / name).read_bytes()) != expected:
raise SystemExit("Pinned upstream source hash mismatch")
if digest((source / "LICENSE").read_bytes()) != lock["license_sha256"]:
raise SystemExit("Pinned upstream license hash mismatch")
# The upstream selector is run over local data; refuse Python network access.
def deny(*args, **kwargs):
raise RuntimeError("Network forbidden while selecting the local snapshot")
socket.socket.connect = deny
socket.create_connection = deny
os.environ.setdefault("POLARS_MAX_THREADS", "4")
sys.path.insert(0, str(source))
import financedatabase as fd
import polars as pl
equities = fd.Equities(use_local_location=True)
selected = equities.select(only_primary_listing=True, exclude_delisted=True, as_pandas=False)
rows = selected.join(equities.get_listing_ranks(), on="symbol", how="left").select(FIELDS).sort("symbol")
if rows.height != 47735:
raise SystemExit(f"Unexpected primary equity count {rows.height}, expected 47735")
targets = {"NVDA": "NVIDIA Corporation", "AAPL": "Apple Inc.", "9888.HK": "Baidu, Inc.", "002594.SZ": "BYD Company Limited", "0285.HK": "BYD Electronic (International) Company Limited"}
for symbol, name in targets.items():
match = rows.filter(pl.col("symbol") == symbol)
if match.height != 1 or match["name"][0] != name:
raise SystemExit("Pinned primary target mismatch")
content = rows.write_csv().encode("utf-8")
identities = {}
unidentified = 0
for row in rows.iter_rows(named=True):
identity = "isin:" + row["isin"] if row["isin"] else ("figi:" + row["figi"] if row["figi"] else None)
if identity:
identities[identity] = identities.get(identity, 0) + 1
else:
unidentified += 1
manifest = {
"runtime_resolvable_identities": len(identities),
"rows_without_stable_identity": unidentified,
"identities_with_multiple_primary_rows": sum(count > 1 for count in identities.values()),
"runtime_identity_policy": "ISIN else FIGI; group identical identity; highest upstream listing_score; equal-score primary rows use symbol lexical tie-break for a deterministic representative; unidentified rows remain embedded but are not searchable/followable.",
"upstream_repository": "https://github.com/JerBouma/FinanceDatabase",
"upstream_commit": COMMIT,
"upstream_commit_date_utc": "2026-11-17T13:27:37Z",
"package_version": "2.5.2", "license": "MIT",
"upstream_equities_data_file": "compression/equities.parquet",
"upstream_equities_data_sha256": DATA_HASH,
"selection": "Equities(use_local_location=True).select(only_primary_listing=True, exclude_delisted=True, as_pandas=False); join get_listing_ranks(); sort symbol",
"primary_listing_evidence": "Unmodified commit-pinned upstream listings_model over the complete local Equities data; no ticker heuristic or provider API.",
"records": rows.height, "snapshot": "equities_primary.csv", "sha256": digest(content),
"fields": FIELDS,
"upstream_source_sha256": {str(p.relative_to(source)): digest(p.read_bytes()) for p in sorted((source / "financedatabase").rglob("*.py"))},
"license_sha256": digest((source / "LICENSE").read_bytes()),
}
destination.mkdir(parents=True, exist_ok=True)
# Generate everything before replacing existing artifacts; no cache purge.
with tempfile.TemporaryDirectory(dir=destination) as staging:
stage = Path(staging)
(stage / "equities_primary.csv").write_bytes(content)
(stage / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
shutil.copyfile(source / "LICENSE", stage / "FINANCEDATABASE_LICENSE")
for name in ("equities_primary.csv", "manifest.json", "FINANCEDATABASE_LICENSE"):
os.replace(stage / name, destination / name)
print(f"Equity primary snapshot: {rows.height} records; sha256={digest(content)}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--source-dir", type=Path)
group.add_argument("--download", action="store_true")
parser.add_argument("--output", type=Path, default=ROOT / "internal/companycatalog/data")
args = parser.parse_args()
if args.source_dir:
generate(args.source_dir.resolve(), args.output)
else:
with tempfile.TemporaryDirectory(prefix="company-catalog-", dir=os.environ.get("IDEA_MANAGED_TMP") or os.environ.get("TMPDIR")) as work:
archive = urllib.request.urlopen(f"https://codeload.github.com/JerBouma/FinanceDatabase/tar.gz/{COMMIT}", timeout=120).read()
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
tar.extractall(work, filter="data")
generate(Path(work) / f"FinanceDatabase-{COMMIT}", args.output)
if __name__ == "__main__":
main()