#!/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()