Coverage for scripts/build_wide_root.py: 100%
115 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 wide equity root of V6.6.0: a separate Lean data root with every S&P 500 member since 2003, Yahoo daily bars.
3Never a change to `data/`, which stays one fixed vintage (AGENTS.md rule 12). Only names with bars are here; Yahoo has no delisted
4ones, and `ml/evaluation/v660/wide_coverage.json` measures that gap. A rerun resumes: a ticker already in the manifest is skipped.
6The script records only row counts, spans and hashes. Nothing here computes a return.
8 python scripts/build_wide_root.py --start 2003-06-01 --end 2026-11-03 --out data_wide
9"""
11from __future__ import annotations
13import argparse
14import copy
15import hashlib
16import json
17import shutil
18import sys
19import time as _time
20from collections.abc import Callable
21from pathlib import Path
23ROOT = Path(__file__).resolve().parents[1]
24sys.path.insert(0, str(ROOT))
26from data_pipeline.sp500_membership import ( # noqa: E402
27 fetch_membership,
28 load_membership,
29 suspect_interval,
30 tickers_touching,
31 write_coverage,
32 yahoo_symbol_for_member,
33)
34from data_pipeline.yfinance_backfill import sanitize_ohlc, scale_for_lean, write_lean_zip # noqa: E402
36MANIFEST = "wide_manifest.json"
37RAW_DIR = "reference/raw_closes"
38COPIED_DIRS = ("market-hours", "symbol-properties", "reference", Path("alternative") / "interest-rate", Path("crypto") / "coinbase" / "daily")
39EMPTY_DIRS = (Path("equity") / "usa" / "map_files", Path("equity") / "usa" / "factor_files")
40SECTOR_ETFS = ("XLB", "XLE", "XLF", "XLI", "XLK", "XLP", "XLU", "XLV", "XLY", "XLC", "XLRE")
41BENCHMARKS = ("SPY", "AGG", "BIL")
44def fetch_adjusted_and_raw(symbol: str, start: str, end: str) -> tuple[list[dict], dict[str, float]]:
45 """(rows as `fetch_yahoo_ohlcv` gives them, split-adjusted closes without dividends). Yahoo's `Adj Close` / `Close` ratio is what
46 `auto_adjust=True` applies, so one download serves both. Market cap needs the second: an adjusted close embeds later dividends."""
47 import pandas as pd
48 import yfinance as yf
50 frame = yf.download(symbol, start=start, end=end, auto_adjust=False, progress=False, threads=False)
51 if frame is None or frame.empty:
52 return [], {}
53 if isinstance(frame.columns, pd.MultiIndex):
54 frame.columns = frame.columns.get_level_values(0)
55 rows, raw = [], {}
56 for stamp, row in frame.iterrows():
57 close, adjusted = float(row["Close"]), float(row["Adj Close"])
58 if not (close > 0.0 and adjusted > 0.0):
59 continue
60 ratio = adjusted / close
61 day = stamp.date()
62 rows.append({
63 "date": day, "open": float(row["Open"]) * ratio, "high": float(row["High"]) * ratio, "low": float(row["Low"]) * ratio,
64 "close": adjusted, "volume": float(row["Volume"]) if row["Volume"] == row["Volume"] else 0.0,
65 })
66 raw[day.isoformat()] = close
67 return rows, raw
70def build_root(
71 out: Path, *, start: str, end: str, config: dict, source: Path = ROOT / "data",
72 fetch_fn: Callable[[str, str, str], tuple[list[dict], dict[str, float]]] = fetch_adjusted_and_raw, pause_seconds: float = 0.2,
73 get_membership: Callable[[str], str] | None = None, coverage_path: Path | None = None, retries: int = 2,
74) -> dict:
75 """Writes the root and returns its manifest. A failed name is left out and reported, never guessed."""
76 out = Path(out)
77 for relative in COPIED_DIRS:
78 if (source / relative).exists():
79 (out / relative).parent.mkdir(parents=True, exist_ok=True)
80 shutil.copytree(source / relative, out / relative, dirs_exist_ok=True)
81 for relative in EMPTY_DIRS:
82 (out / relative).mkdir(parents=True, exist_ok=True)
83 (out / RAW_DIR).mkdir(parents=True, exist_ok=True)
85 manifest_path = out / MANIFEST
86 manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {"start": start, "end": end, "tickers": {}, "left_out": {}}
87 manifest["membership"] = fetch_membership(out / "reference", get=get_membership)
88 table = load_membership(out / "reference" / "sp500_ticker_start_end.csv")
89 members = set(tickers_touching(table, start, end))
90 project = {str(asset["ticker"]) for asset in config["phase1"]["universe"]["assets"] if asset["security_type"] == "equity"}
91 wanted = sorted(members | project | set(SECTOR_ETFS) | set(BENCHMARKS))
93 for count, ticker in enumerate(wanted, start=1):
94 if ticker in manifest["tickers"] or manifest["left_out"].get(ticker, "").startswith("suspect"):
95 continue
96 rows, raw = [], {}
97 for attempt in range(retries + 1):
98 try:
99 rows, raw = fetch_fn(yahoo_symbol_for_member(ticker), start, end)
100 except Exception as error: # one bad ticker must not lose the others
101 manifest["left_out"][ticker] = f"fetch failed: {type(error).__name__}"
102 rows = []
103 if rows:
104 break
105 if pause_seconds and attempt < retries:
106 _time.sleep(pause_seconds * 5)
107 rows, _ = sanitize_ohlc(rows)
108 rows = [row for row in rows if row["date"].isoformat() < end]
109 if not rows:
110 manifest["left_out"].setdefault(ticker, "no bars")
111 continue
112 first = rows[0]["date"].isoformat()
113 if ticker in table and suspect_interval(table[ticker], first, window_start=start):
114 manifest["left_out"][ticker] = f"suspect: bars begin {first}, after its membership began"
115 continue
116 path = out / "equity" / "usa" / "daily" / f"{ticker.lower()}.zip"
117 path.parent.mkdir(parents=True, exist_ok=True)
118 write_lean_zip(path, ticker, scale_for_lean(rows, "equity"), merge_with_existing=False)
119 (out / RAW_DIR / f"{ticker.lower()}.json").write_text(json.dumps(raw, separators=(",", ":")), encoding="utf-8", newline="\n")
120 manifest["left_out"].pop(ticker, None)
121 manifest["tickers"][ticker] = {
122 "rows": len(rows), "first": first, "last": rows[-1]["date"].isoformat(), "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
123 "member": ticker in table,
124 }
125 if count % 25 == 0:
126 manifest_path.write_text(json.dumps(manifest, indent=1), encoding="utf-8", newline="\n")
127 print(f"{count} of {len(wanted)}: {len(manifest['tickers'])} written, {len(manifest['left_out'])} left out", flush=True)
128 if pause_seconds:
129 _time.sleep(pause_seconds)
130 manifest_path.write_text(json.dumps(manifest, indent=1), encoding="utf-8", newline="\n")
131 if coverage_path is not None:
132 write_coverage(coverage_path, table, set(manifest["tickers"]), manifest["left_out"])
133 return manifest
136def wide_config(base: dict, manifest: dict, *, keep_project_crypto: bool = True, tickers: set[str] | None = None) -> dict:
137 """A run config on this root: every name with bars (or `tickers`), plus the benchmarks and the project's crypto. An asset's
138 `data_path` keeps the `data/` prefix: `asset_zip_paths` and a Codespace run's `.dataroot` swap the root under it."""
139 config = copy.deepcopy(base)
140 assets = []
141 for ticker, entry in sorted(manifest["tickers"].items()):
142 if ticker == "BIL" or (tickers is not None and ticker not in tickers and ticker not in BENCHMARKS):
143 continue # BIL is the sweep, outside the universe
144 assets.append({
145 "ticker": ticker, "security_type": "equity", "market": "usa", "data_path": f"data/equity/usa/daily/{ticker.lower()}.zip",
146 "available_from": entry["first"], "available_to": entry["last"],
147 })
148 if keep_project_crypto:
149 assets += [asset for asset in base["phase1"]["universe"]["assets"] if asset["security_type"] == "crypto"]
150 config["phase1"]["universe"]["assets"] = assets
151 return config
154def main() -> int:
155 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
156 parser.add_argument("--start", default="2003-06-01")
157 parser.add_argument("--end", default="2026-11-03")
158 parser.add_argument("--out", default="data_wide")
159 args = parser.parse_args()
160 config = json.loads((ROOT / "config.json").read_text(encoding="utf-8"))
161 manifest = build_root(ROOT / args.out, start=args.start, end=args.end, config=config, coverage_path=ROOT / "ml" / "evaluation" / "v660" / "wide_coverage.json")
162 print(f"{len(manifest['tickers'])} tickers written, {len(manifest['left_out'])} left out")
163 return 0
166if __name__ == "__main__":
167 raise SystemExit(main())