Coverage for scripts/compare_training_variants.py: 100%
114 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"""Compare retrain variants and pick the winner on VALIDATION IC, never on the backtest split.
3Reads `ml/versions/<id>/multitask_training_metrics.json` (or sequence_...) for each version id and prints one table:
4validation and backtest non-overlapping rank IC (mean, t) for the book heads, the backtest ranking-quality verdicts, the
5net Sharpe of the head the book trades, and whether the variant beats the reference by more than the reference's own
6seed-to-seed spread. The backtest columns are for the record; selecting on them would overfit the 2019-21 window that
7Lean also tests.
9 python scripts/compare_training_variants.py --reference v0_s1 --noise v0_s1 v0_s2 --variants v1 v2 v3
10"""
12from __future__ import annotations
14import argparse
15import json
16import math
17import sys
18from pathlib import Path
20sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
22from evaluation.rank_ic_core import newey_west_t_stat
24DEFAULT_HEADS = ("rank_5d", "rank_20d")
25HORIZON_DAYS = {"rank_5d": 5, "rank_20d": 20}
28def _ic(metrics: dict, split: str, head: str) -> dict:
29 """Non-overlapping IC (honest t, few dates) plus the FULL daily IC series' mean and Newey-West t: the daily mean
30 has the same expectation with far less noise (261 dates against 14 on validation) and the HAC t corrects the
31 autocorrelation the plain daily t ignores."""
32 block = (metrics.get(split) or {}).get(f"{head}_ic_non_overlapping") or {}
33 daily = (metrics.get(split) or {}).get(f"{head}_ic") or {}
34 values = daily.get("ic_values") or []
35 return {
36 "mean_ic": block.get("mean_ic"), "t_stat": block.get("t_stat"), "num_dates": block.get("num_dates"),
37 "daily_mean_ic": daily.get("mean_ic"), "daily_num_dates": daily.get("num_dates"),
38 "hac_t_stat": newey_west_t_stat(values, HORIZON_DAYS.get(head, 20) - 1) if values else None,
39 }
42def summarize_variant(metrics: dict, heads: tuple[str, ...] = DEFAULT_HEADS, score_basis: str = "daily") -> dict:
43 """Validation/backtest IC per head, the mean validation IC across `heads` (the selection score: the full-daily mean
44 by default, `score_basis="non_overlapping"` reproduces the V5.6.0 14-date score) and the backtest verdicts. Heads
45 without a finite validation IC are ignored; no usable head -> score None."""
46 row: dict = {"heads": {}}
47 scores = []
48 for head in heads:
49 validation = _ic(metrics, "validation", head)
50 backtest = _ic(metrics, "backtest", head)
51 quality = ((metrics.get("backtest") or {}).get(f"{head}_ranking_quality") or {}).get("quality_status")
52 net = (((metrics.get("backtest") or {}).get(f"{head}_net_performance") or {}).get("observed") or {}).get("net_sharpe")
53 row["heads"][head] = {"validation": validation, "backtest": backtest, "quality_status": quality, "net_sharpe": net}
54 value = validation["daily_mean_ic"] if score_basis == "daily" and validation["daily_mean_ic"] is not None else validation["mean_ic"]
55 if isinstance(value, (int, float)) and math.isfinite(value):
56 scores.append(float(value))
57 row["validation_score"] = sum(scores) / len(scores) if scores else None
58 row["seed"] = metrics.get("seed")
59 return row
62def seed_spread(scores: list[float]) -> float:
63 """Max-min of the reference's validation scores across seeds (0.0 with fewer than two): the noise a
64 variant has to clear before it counts as an improvement."""
65 return (max(scores) - min(scores)) if len(scores) >= 2 else 0.0
68def choose_winner(rows: dict[str, dict], reference: str, noise_ids: list[str]) -> dict:
69 reference_row = rows.get(reference)
70 reference_score = reference_row["validation_score"] if reference_row else None
71 noise_scores = [rows[i]["validation_score"] for i in noise_ids if i in rows and rows[i]["validation_score"] is not None]
72 spread = seed_spread(noise_scores)
73 best_id, best_score = reference, reference_score
74 for version_id, row in rows.items():
75 score = row["validation_score"]
76 if version_id == reference or score is None or reference_score is None:
77 continue
78 if score > reference_score + spread and (best_score is None or score > best_score):
79 best_id, best_score = version_id, score
80 return {
81 "winner": best_id,
82 "reference": reference,
83 "reference_score": reference_score,
84 "seed_spread": spread,
85 "winner_score": best_score,
86 "beats_reference": best_id != reference,
87 }
90def group_rows(rows: dict[str, dict], groups: dict[str, list[str]]) -> dict[str, dict]:
91 """One row per group (a variant trained with several seeds): `validation_score` is the mean over the members that
92 have a score, `member_scores` keeps each seed's own. Groups with no scored member get score None."""
93 grouped = {}
94 for name, ids in groups.items():
95 members = {i: rows[i]["validation_score"] for i in ids if i in rows and rows[i]["validation_score"] is not None}
96 grouped[name] = {
97 "validation_score": sum(members.values()) / len(members) if members else None,
98 "member_scores": members,
99 "heads": rows[next(iter(members))]["heads"] if members else {},
100 }
101 return grouped
104def choose_group_winner(grouped: dict[str, dict], reference: str) -> dict:
105 """R-MODEL (selection half): a variant group wins only if its MEAN validation score beats the control group's mean by
106 more than the control's own single-seed spread (max-min over its seeds) - noise the variant has to clear."""
107 reference_row = grouped.get(reference) or {}
108 spread = seed_spread(list((reference_row.get("member_scores") or {}).values()))
109 reference_score = reference_row.get("validation_score")
110 best_name, best_score = reference, reference_score
111 for name, row in grouped.items():
112 score = row["validation_score"]
113 if name == reference or score is None or reference_score is None:
114 continue
115 if score > reference_score + spread and (best_score is None or score > best_score):
116 best_name, best_score = name, score
117 return {
118 "winner": best_name, "reference": reference, "reference_score": reference_score, "seed_spread": spread,
119 "winner_score": best_score, "beats_reference": best_name != reference,
120 }
123def load_rows(ids: list[str], versions_dir: Path, metrics_filename: str) -> dict[str, dict]:
124 rows = {}
125 for version_id in ids:
126 path = versions_dir / version_id / metrics_filename
127 if not path.exists():
128 continue
129 rows[version_id] = summarize_variant(json.loads(path.read_text(encoding="utf-8")))
130 return rows
133def main() -> int:
134 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
135 parser.add_argument("--versions-dir", default="ml/versions")
136 parser.add_argument("--metrics-file", default="multitask_training_metrics.json")
137 parser.add_argument("--reference", required=True, help="version id of the control (current config)")
138 parser.add_argument("--noise", nargs="*", default=[], help="control re-runs with other seeds: they define the seed spread")
139 parser.add_argument("--variants", nargs="*", default=[])
140 parser.add_argument(
141 "--groups", nargs="*", default=[],
142 help="V5.7.0 multi-seed mode: NAME=id1,id2,... per arm (the control arm is the one named by --reference). Each arm is "
143 "scored by its mean validation IC (full daily series); a variant wins only above the control mean + the control's seed spread.",
144 )
145 parser.add_argument("--output", default="ml/evaluation/training_variant_comparison.json")
146 args = parser.parse_args()
148 if args.groups:
149 groups = {name: ids.split(",") for name, ids in (item.split("=", 1) for item in args.groups)}
150 all_ids = list(dict.fromkeys(i for ids in groups.values() for i in ids))
151 rows = load_rows(all_ids, Path(args.versions_dir), args.metrics_file)
152 grouped = group_rows(rows, groups)
153 verdict = choose_group_winner(grouped, args.reference)
154 for name, row in grouped.items():
155 score = "n/a" if row["validation_score"] is None else f"{row['validation_score']:+.4f}"
156 print(f"{name:24s} mean validation IC {score} seeds {row['member_scores']}")
157 print(json.dumps(verdict, indent=2))
158 Path(args.output).parent.mkdir(parents=True, exist_ok=True)
159 Path(args.output).write_text(json.dumps({"rows": rows, "groups": grouped, "verdict": verdict}, indent=2), encoding="utf-8")
160 return 0
162 ids = list(dict.fromkeys([args.reference, *args.noise, *args.variants]))
163 rows = load_rows(ids, Path(args.versions_dir), args.metrics_file)
164 verdict = choose_winner(rows, args.reference, args.noise or [args.reference])
165 print(f"{'version':32s} {'val score':>9s} " + " ".join(f"{h}: val daily IC (HAC t) | bt IC (t) | status" for h in DEFAULT_HEADS))
166 for version_id, row in rows.items():
167 cells = []
168 for head in DEFAULT_HEADS:
169 info = row["heads"][head]
170 v, b = info["validation"], info["backtest"]
171 fmt = lambda block: "n/a" if block["mean_ic"] is None else f"{block['mean_ic']:+.3f} ({block['t_stat']:.1f})" # noqa: E731
172 fmt_daily = lambda block: "n/a" if block["daily_mean_ic"] is None or block["hac_t_stat"] is None else f"{block['daily_mean_ic']:+.3f} ({block['hac_t_stat']:.1f})" # noqa: E731
173 cells.append(f"{head}: {fmt_daily(v)} | {fmt(b)} | {info['quality_status']}")
174 score = "n/a" if row["validation_score"] is None else f"{row['validation_score']:+.4f}"
175 print(f"{version_id:32s} {score:>9s} " + " ".join(cells))
176 print(json.dumps(verdict, indent=2))
177 Path(args.output).parent.mkdir(parents=True, exist_ok=True)
178 Path(args.output).write_text(json.dumps({"rows": rows, "verdict": verdict}, indent=2), encoding="utf-8")
179 return 0
182if __name__ == "__main__":
183 raise SystemExit(main())