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:
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
|
||||
}
|
||||
Reference in New Issue
Block a user