Coverage for scripts/build_pre2013_root.py: 100%
82 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""The never-read confirmation data of V6.5.0: a separate Lean data root with the universe's history before `data/` begins.
3`data/` starts on 2013-01-02 and no phase has read anything older, so this root is the one window no rule was fitted on. It
4is a separate folder, never a prepend: `data/` is one fixed Yahoo vintage (AGENTS.md rule 12), and adding older rows would
5change what dataset builds read. Crypto did not trade then; tickers with no bars are left out and reported.
7The script records only row counts and date spans. Nothing here looks at a price, and nothing may until verification.
9 python scripts/build_pre2013_root.py --start 2002-01-01 --end 2013-01-02 --out data_pre2013
10"""
12from __future__ import annotations
14import argparse
15import hashlib
16import json
17import shutil
18import sys
19from collections.abc import Callable
20from pathlib import Path
22ROOT = Path(__file__).resolve().parents[1]
23sys.path.insert(0, str(ROOT))
24sys.path.insert(0, str(ROOT / "scripts"))
26from build_holdout_data import CLASS_KEY_BY_SECURITY_TYPE, yahoo_symbol # noqa: E402
28from data_pipeline.fetch import ASSET_CLASS_CONFIG # noqa: E402
29from data_pipeline.yfinance_backfill import ( # noqa: E402
30 apply_price_overrides,
31 fetch_yahoo_ohlcv,
32 sanitize_ohlc,
33 scale_for_lean,
34 write_lean_zip,
35)
37SWEEP = {"ticker": "BIL", "security_type": "equity", "data_path": "data/equity/usa/daily/bil.zip"}
38BENCHMARK_EXTRAS = (SWEEP,)
39COPIED_DIRS = ("market-hours", "symbol-properties", "reference", Path("alternative") / "interest-rate")
40EMPTY_DIRS = (Path("equity") / "usa" / "map_files", Path("equity") / "usa" / "factor_files")
43def _asset_path(out: Path, asset: dict) -> Path:
44 return out / Path(*Path(asset["data_path"]).parts[1:])
47def build_root(
48 config: dict, out: Path, *, start: str, end: str, source: Path = ROOT / "data",
49 fetch_fn: Callable[[str, str, str], list[dict]] = fetch_yahoo_ohlcv, overrides: dict | None = None,
50) -> dict:
51 """Writes the root and returns its manifest: per ticker the row count, first and last date and the file's sha256; tickers
52 left out with why. A failed fetch leaves a ticker out; the verification run simply has fewer names."""
53 out = Path(out)
54 for relative in COPIED_DIRS:
55 target = out / relative
56 if (source / relative).exists():
57 target.parent.mkdir(parents=True, exist_ok=True)
58 shutil.copytree(source / relative, target, dirs_exist_ok=True)
59 for relative in EMPTY_DIRS:
60 (out / relative).mkdir(parents=True, exist_ok=True)
61 manifest: dict = {"start": start, "end": end, "tickers": {}, "left_out": {}}
62 known = {str(asset["ticker"]) for asset in config["phase1"]["universe"]["assets"]}
63 assets = list(config["phase1"]["universe"]["assets"]) + [asset for asset in BENCHMARK_EXTRAS if asset["ticker"] not in known]
64 for asset in assets:
65 ticker, security_type = str(asset["ticker"]), str(asset["security_type"])
66 if security_type == "crypto":
67 manifest["left_out"][ticker] = "crypto"
68 continue
69 if security_type not in CLASS_KEY_BY_SECURITY_TYPE:
70 manifest["left_out"][ticker] = f"security type {security_type}"
71 continue
72 try:
73 rows = fetch_fn(yahoo_symbol(asset), start, end)
74 except Exception as error: # one bad ticker must not lose the others
75 manifest["left_out"][ticker] = f"fetch failed: {type(error).__name__}"
76 continue
77 rows, _ = apply_price_overrides(rows, (overrides or {}).get(ticker))
78 rows, _ = sanitize_ohlc(rows)
79 rows = [row for row in rows if row["date"].isoformat() < end]
80 if not rows:
81 manifest["left_out"][ticker] = "no bars in the window"
82 continue
83 path = _asset_path(out, asset)
84 path.parent.mkdir(parents=True, exist_ok=True)
85 write_fn = ASSET_CLASS_CONFIG[CLASS_KEY_BY_SECURITY_TYPE[security_type]].get("write_fn", write_lean_zip)
86 write_fn(path, ticker, scale_for_lean(rows, security_type), merge_with_existing=False)
87 manifest["tickers"][ticker] = {
88 "rows": len(rows), "first": rows[0]["date"].isoformat(), "last": rows[-1]["date"].isoformat(),
89 "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "security_type": security_type,
90 }
91 (out / "pre2013_manifest.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8", newline="\n")
92 return manifest
95def universe_for_root(config: dict, manifest: dict) -> dict:
96 """The config restricted to the tickers the root holds (no crypto, none listed later)."""
97 import copy
99 out = copy.deepcopy(config)
100 keep = set(manifest["tickers"])
101 out["phase1"]["universe"]["assets"] = [asset for asset in out["phase1"]["universe"]["assets"] if str(asset["ticker"]) in keep]
102 return out
105def main() -> int:
106 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
107 parser.add_argument("--start", default="2002-01-01")
108 parser.add_argument("--end", default="2013-01-02")
109 parser.add_argument("--out", default="data_pre2013")
110 args = parser.parse_args()
111 config = json.loads((ROOT / "config.json").read_text(encoding="utf-8"))
112 overrides_path = ROOT / "data_pipeline" / "price_overrides.json"
113 overrides = json.loads(overrides_path.read_text(encoding="utf-8")) if overrides_path.exists() else {}
114 manifest = build_root(config, ROOT / args.out, start=args.start, end=args.end, overrides=overrides)
115 print(f"{len(manifest['tickers'])} tickers written, {len(manifest['left_out'])} left out")
116 for ticker, why in sorted(manifest["left_out"].items()):
117 print(f" {ticker}: {why}")
118 spans = sorted((entry["first"], ticker) for ticker, entry in manifest["tickers"].items())
119 print("latest starts:", spans[-10:])
120 return 0
123if __name__ == "__main__":
124 raise SystemExit(main())