Coverage for scripts/holdout_report.py: 100%
67 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 ONE-LOOK out-of-window report (V5.7.0): how a model set performs on the holdout dataset it never saw.
3Run exactly once per candidate decision, AFTER the model has been chosen on validation (R-MODEL): the holdout is evidence,
4not a selection set. Reads the holdout rows of `ml/datasets/full_dataset.csv` (`build_holdout_dataset.py --full-splits`
5labels them `holdout`; an older standalone holdout file labels them `backtest`), scores every model head
6on the holdout window, and reports per head and per asset class: daily rank IC (mean, HAC t, non-overlapping t) against the
7dataset's own rank targets, plus the as-live book (blended head, every live mechanism) when `--book` is given.
9 python scripts/holdout_report.py [--models multitask sequence] [--book] [--output ml/evaluation/holdout_report.json]
10"""
12from __future__ import annotations
14import argparse
15import json
16import sys
17from pathlib import Path
19import pandas as pd
21ROOT_DIR = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT_DIR))
23sys.path.insert(0, str(Path(__file__).resolve().parent))
25from evaluation.model_predictions import predict_heads # noqa: E402
26from evaluation.rank_ic_core import newey_west_t_stat, rank_ic_from_arrays # noqa: E402
28ML_DIR = ROOT_DIR / "ml"
29MODEL_FILES = {"multitask": ("multitask_model.json", "multitask_feature_schema.json"), "sequence": ("sequence_model.json", "sequence_feature_schema.json")}
30HEAD_TARGETS = {"rank_5d": ("target_rank_5d", 5), "rank_20d": ("target_rank_20d", 20)}
33def select_holdout_rows(dataset: pd.DataFrame, holdout_window: dict) -> tuple[pd.DataFrame, str]:
34 """Training-eligible rows of the holdout window and the split label they carry.
36 A four-split dataset labels them `holdout`; the V5.7.0 standalone holdout file labelled the whole file `backtest`.
37 Rows outside `phase1.windows.holdout` are never returned, so a four-split file can not be scored as its backtest."""
38 start, end = str(holdout_window["start"]), str(holdout_window["end"])
39 dates = dataset["date"].astype(str).str[:10]
40 in_window = (dates >= start) & (dates <= end) & dataset["training_eligible"].astype(bool)
41 split = "holdout" if (dataset["split"] == "holdout").any() else "backtest"
42 selected = dataset[in_window & (dataset["split"] == split)].reset_index(drop=True)
43 if selected.empty:
44 raise ValueError(f"no training-eligible holdout rows between {start} and {end}")
45 return selected, split
48def ic_summary(frame: pd.DataFrame, prediction: str, target: str, horizon: int) -> dict:
49 """Daily rank IC of `prediction` against `target` over `frame` (one row per ticker-date)."""
50 result = rank_ic_from_arrays(
51 frame[prediction].to_numpy(), frame[target].to_numpy(), frame["date"].to_numpy(), min_names_per_date=10
52 )
53 non_overlapping = rank_ic_from_arrays(
54 frame[prediction].to_numpy(), frame[target].to_numpy(), frame["date"].to_numpy(),
55 non_overlapping_stride=horizon, min_names_per_date=10,
56 )
57 return {
58 "daily_mean_ic": result["mean_ic"], "hac_t": newey_west_t_stat(result["ic_values"], horizon - 1),
59 "num_dates": result["num_dates"], "non_overlapping_mean_ic": non_overlapping["mean_ic"],
60 "non_overlapping_t": non_overlapping["t_stat"], "non_overlapping_dates": non_overlapping["num_dates"],
61 }
64def main() -> int:
65 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
66 parser.add_argument("--models", nargs="*", default=["multitask", "sequence"])
67 parser.add_argument("--dataset", default=str(ML_DIR / "datasets" / "full_dataset.csv"))
68 parser.add_argument("--book", action="store_true", help="also run the as-live book on the holdout window")
69 parser.add_argument("--output", default=str(ML_DIR / "evaluation" / "holdout_report.json"))
70 args = parser.parse_args()
72 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
73 holdout_window = config["phase1"]["windows"]["holdout"]
74 parts = [chunk[chunk["date"].astype(str).str[:10] >= str(holdout_window["start"])] for chunk in pd.read_csv(args.dataset, chunksize=40_000)]
75 dataset, holdout_split = select_holdout_rows(pd.concat(parts, ignore_index=True), holdout_window)
76 asset_class = {a["ticker"]: a.get("asset_class") or a.get("security_type") for a in config["phase1"]["universe"]["assets"]}
77 dataset["asset_class"] = dataset["ticker"].map(asset_class)
78 window = int(config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30))
79 report: dict = {
80 "dataset": args.dataset, "split_label": holdout_split, "rows": int(len(dataset)), "tickers": int(dataset["ticker"].nunique()),
81 "first_date": str(dataset["date"].min()), "last_date": str(dataset["date"].max()), "models": {},
82 }
83 for model_kind in args.models:
84 model_file, schema_file = MODEL_FILES[model_kind]
85 model_export = json.loads((ML_DIR / model_file).read_text(encoding="utf-8"))
86 schema = json.loads((ML_DIR / schema_file).read_text(encoding="utf-8"))
87 predictions = predict_heads(
88 dataset, model_export, schema["model_input_names"], list(HEAD_TARGETS),
89 model_kind=model_kind, sequence_feature_schema=schema if model_kind == "sequence" else None,
90 configured_window_size=window, batched=True,
91 )
92 per_head = {}
93 for head, (target, horizon) in HEAD_TARGETS.items():
94 scored = dataset.assign(prediction=predictions[head]).dropna(subset=["prediction", target])
95 per_head[head] = {
96 "all": ic_summary(scored, "prediction", target, horizon),
97 "by_asset_class": {
98 kind: ic_summary(group, "prediction", target, horizon)
99 for kind, group in scored.groupby("asset_class")
100 if group["ticker"].nunique() >= 10 or kind == "forex"
101 },
102 }
103 print(f"{model_kind}/{head}: " + json.dumps(per_head[head]["all"]))
104 report["models"][model_kind] = per_head
105 if args.book:
106 from as_live_levers import AsLiveHarness, summarize
108 harness = AsLiveHarness(holdout_split, dataset_path=args.dataset, use_cache=False)
109 report["as_live_book"] = summarize(harness.as_live())
110 report["idealized_book"] = summarize(harness.idealized())
111 print("as-live book:", json.dumps(report["as_live_book"]))
112 Path(args.output).write_text(json.dumps(report, indent=2, default=float), encoding="utf-8")
113 if Path(args.output).resolve() == (ROOT_DIR / "ml" / "evaluation" / "holdout_report.json").resolve():
114 from evaluation.readme_research import refresh_readme_best_effort
116 refresh_readme_best_effort()
117 print(f"written {args.output}")
118 return 0
121if __name__ == "__main__":
122 raise SystemExit(main())