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:
30
backend/internal/companycatalog/README.md
Normal file
30
backend/internal/companycatalog/README.md
Normal 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.
|
||||
168
backend/internal/companycatalog/catalog.go
Normal file
168
backend/internal/companycatalog/catalog.go
Normal 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
|
||||
}
|
||||
72
backend/internal/companycatalog/catalog_ticket19_test.go
Normal file
72
backend/internal/companycatalog/catalog_ticket19_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
21
backend/internal/companycatalog/data/FINANCEDATABASE_LICENSE
Normal file
21
backend/internal/companycatalog/data/FINANCEDATABASE_LICENSE
Normal 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.
|
||||
47736
backend/internal/companycatalog/data/equities_primary.csv
Normal file
47736
backend/internal/companycatalog/data/equities_primary.csv
Normal file
File diff suppressed because it is too large
Load Diff
76
backend/internal/companycatalog/data/manifest.json
Normal file
76
backend/internal/companycatalog/data/manifest.json
Normal 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"
|
||||
}
|
||||
}
|
||||
53
backend/internal/companycatalog/embedded_test.go
Normal file
53
backend/internal/companycatalog/embedded_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
6
backend/internal/companycatalog/testdata/finance_database_equities_primary_2026-11-22.csv
vendored
Normal file
6
backend/internal/companycatalog/testdata/finance_database_equities_primary_2026-11-22.csv
vendored
Normal 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
|
||||
|
40
backend/internal/companycatalog/testdata/finance_database_manifest_2026-11-22.json
vendored
Normal file
40
backend/internal/companycatalog/testdata/finance_database_manifest_2026-11-22.json
vendored
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
13
backend/internal/companycatalog/testdata/finance_database_raw_multilistings_2026-11-22.csv
vendored
Normal file
13
backend/internal/companycatalog/testdata/finance_database_raw_multilistings_2026-11-22.csv
vendored
Normal 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
|
||||
|
Reference in New Issue
Block a user