Coverage for scripts/build_holdout_data.py: 100%

75 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Fetch Yahoo-adjusted bars for every universe asset into a staging root (V5.7.0 holdout fetcher, V5.8.0 data refresh). 

2 

3Every trained model and every lever was tuned on 2014-12..2021-03; only the 2018 validation year is independent, and it 

4is thin. This fetches Yahoo (already split/dividend-adjusted) daily bars for every universe asset from `--start` to 

5`--end` (default 2014-06-01..2025-06-30), writes them as Lean-format zips at the same relative paths under 

6`--root`, and re-fetches every FRED series the features read (bond, alt-data, FX rates) through the same end date 

7into `<root>/reference/fred_series/`. Nothing under `data/` is touched, so the trained models, the dataset and 

8Lean backtests stay exactly as they were; the holdout is evaluation-only (`scripts/build_holdout_dataset.py`). 

9 

10Assets Yahoo cannot serve (delisted, renamed) are skipped and listed - the holdout universe is whatever survives. 

11 

12 python scripts/build_holdout_data.py [--start 2014-06-01] [--end 2025-06-30] [--root data_v6_staging] [--apply] 

13 

14V6.0.0: `data_holdout/` was deleted (the holdout lives inside `data/` since V5.8.0); the default root is a staging folder 

15that `aq evaluate --audit-data --data-root` checks before anything is copied over `data/`. 

16 

17Dry run by default (fetches and reports, writes nothing). 

18""" 

19 

20from __future__ import annotations 

21 

22import argparse 

23import json 

24import sys 

25from pathlib import Path 

26 

27ROOT_DIR = Path(__file__).resolve().parents[1] 

28sys.path.insert(0, str(ROOT_DIR)) 

29 

30from data_pipeline.fetch import ASSET_CLASS_CONFIG # noqa: E402 

31from data_pipeline.fred_backfill import fetch_fred_series, reference_series, write_fred_series_cache # noqa: E402 

32from data_pipeline.yfinance_backfill import ( # noqa: E402 

33 apply_price_overrides, 

34 fetch_yahoo_ohlcv, 

35 sanitize_ohlc, 

36 scale_for_lean, 

37 write_lean_crypto_quote_zip, 

38 write_lean_zip, 

39) 

40 

41 

42def holdout_zip_path(root: Path, asset: dict) -> Path: 

43 relative = Path(asset["data_path"]) 

44 return root / Path(*relative.parts[1:]) 

45 

46 

47# data_pipeline.fetch names its asset classes differently from Lean security types 

48CLASS_KEY_BY_SECURITY_TYPE = {"equity": "stock", "crypto": "crypto", "forex": "forex"} 

49 

50 

51# Lean symbols whose Yahoo ticker changed after the model's window (FB -> META in 2022; a bare "FB" on Yahoo is another stock) 

52YAHOO_RENAMES = {"FB": "META"} 

53 

54 

55def yahoo_symbol(asset: dict) -> str: 

56 explicit = (asset.get("backfill") or {}).get("symbol") 

57 if explicit: 

58 return str(explicit) 

59 if asset["ticker"] in YAHOO_RENAMES: 

60 return YAHOO_RENAMES[asset["ticker"]] 

61 return ASSET_CLASS_CONFIG[CLASS_KEY_BY_SECURITY_TYPE[asset["security_type"]]]["yahoo_symbol_fn"](asset["ticker"]) 

62 

63 

64def main() -> int: 

65 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

66 parser.add_argument("--start", default="2014-06-01") 

67 parser.add_argument("--end", default="2025-06-30") 

68 parser.add_argument("--root", default="data_v6_staging") 

69 parser.add_argument("--apply", action="store_true", help="write the zips and FRED cache (default: dry run)") 

70 parser.add_argument("--tickers", nargs="*", default=None) 

71 parser.add_argument( 

72 "--report-name", default="holdout_report.json", 

73 help="V5.8.0: report file written under --root (the V5.8.0 window extension writes refresh_report.json)", 

74 ) 

75 parser.add_argument("--skip-fred", action="store_true", help="V5.8.0: zips only (FRED handled by `aq backfill fred`)") 

76 args = parser.parse_args() 

77 

78 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

79 root = ROOT_DIR / args.root 

80 overrides_path = ROOT_DIR / "data_pipeline" / "price_overrides.json" 

81 price_overrides = json.loads(overrides_path.read_text(encoding="utf-8")) if overrides_path.exists() else {} 

82 report: dict[str, dict] = {} 

83 for asset in config["phase1"]["universe"]["assets"]: 

84 ticker, security_type = asset["ticker"], asset["security_type"] 

85 if args.tickers and ticker not in args.tickers: 

86 continue 

87 if security_type not in CLASS_KEY_BY_SECURITY_TYPE: 

88 report[ticker] = {"status": "skipped_security_type", "security_type": security_type} 

89 continue 

90 symbol = yahoo_symbol(asset) 

91 rows, overridden = apply_price_overrides(fetch_yahoo_ohlcv(symbol, args.start, args.end), price_overrides.get(ticker)) 

92 rows, ohlc_fixed = sanitize_ohlc(rows) 

93 if not rows: 

94 report[ticker] = {"status": "no_data", "yahoo_symbol": symbol} 

95 print(f"{ticker:10s} {symbol:10s} NO DATA") 

96 continue 

97 report[ticker] = { 

98 "status": "ok", "yahoo_symbol": symbol, "rows": len(rows), "ohlc_rows_widened": ohlc_fixed, 

99 "price_overrides_applied": overridden, 

100 "first": rows[0]["date"].isoformat(), "last": rows[-1]["date"].isoformat(), 

101 } 

102 print(f"{ticker:10s} {symbol:10s} {len(rows):5d} rows {report[ticker]['first']}..{report[ticker]['last']}") 

103 if args.apply: 

104 write_fn = ASSET_CLASS_CONFIG[CLASS_KEY_BY_SECURITY_TYPE[security_type]].get("write_fn", write_lean_zip) 

105 target = holdout_zip_path(root, asset) 

106 target.parent.mkdir(parents=True, exist_ok=True) 

107 write_fn(target, ticker, scale_for_lean(rows, security_type), merge_with_existing=False) 

108 if security_type == "crypto" and target.name.endswith("_trade.zip"): 

109 # V5.8.0: Lean requests a crypto quote feed too; derive it from the fresh trade zip (zero-spread rows) 

110 write_lean_crypto_quote_zip( 

111 target, target.with_name(target.name.replace("_trade.zip", "_quote.zip")), ticker, 

112 merge_with_existing=False, 

113 ) 

114 

115 fred_report: dict[str, int] = {} 

116 for key, series_id in ({} if args.skip_fred else reference_series(config, "all")).items(): 

117 rows = fetch_fred_series(series_id, "1990-01-01", args.end) 

118 fred_report[key] = len(rows) 

119 if args.apply and rows: 

120 write_fred_series_cache(root / "reference" / "fred_series", key, rows) 

121 print("FRED rows:", fred_report) 

122 

123 failures = sorted(ticker for ticker, entry in report.items() if entry["status"] != "ok") 

124 print(f"{len(report) - len(failures)} assets ok, {len(failures)} without holdout data: {failures}") 

125 if args.apply: 

126 root.mkdir(parents=True, exist_ok=True) 

127 (root / args.report_name).write_text(json.dumps({"assets": report, "fred_rows": fred_report}, indent=2), encoding="utf-8") 

128 return 0 

129 

130 

131if __name__ == "__main__": 

132 raise SystemExit(main())