Coverage for scripts/gate_value_compare.py: 100%
56 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"""Live rolling-IC gate value against the offline gate's value on the same dates (V6.1.0, Problems.md #190, #196).
3R-CAL2 found the gate's reading to be what keeps the simulator from matching Lean's rebalance decisions (the book mechanics
4replay to r 0.74-0.83). Since V6.1.0 the book history records the live gate's reading (`rolling_ic`: rolling mean IC and the
5resolved-date count) on every rebalance attempt. This scores the same dates with the offline gate (the as-live harness: dataset
6scores, the lagged late-bar frame, the rolling-IC state function) and reports how the two agree: correlation of the values,
7mean absolute difference, how often both sit on the same side of the floor, and where they differ most.
9 python scripts/gate_value_compare.py --book-history visualization/book_history/<run>.jsonl [--dataset ml/datasets/full_dataset.csv]
10 [--splits backtest holdout] [--warmup-days 400] [--out ml/evaluation/v610/gate_value_compare_bt1.json]
11"""
13from __future__ import annotations
15import argparse
16import json
17import math
18import sys
19from pathlib import Path
21ROOT_DIR = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT_DIR))
23sys.path.insert(0, str(Path(__file__).resolve().parent))
26def live_gate_values(book_history: list[dict]) -> dict[str, dict]:
27 """{date: {"value": float | None, "resolved": int, "veto_reason": str | None}} for each record carrying `rolling_ic`;
28 a later record of the same date wins (a retry)."""
29 out: dict[str, dict] = {}
30 for record in book_history:
31 entry = record.get("rolling_ic")
32 if not isinstance(entry, dict):
33 continue
34 value = entry.get("rolling_mean_ic")
35 out[str(record.get("date", ""))[:10]] = {
36 "value": float(value) if isinstance(value, (int, float)) and math.isfinite(value) else None,
37 "resolved": int(entry.get("num_resolved_dates") or 0),
38 "veto_reason": record.get("gate_veto_reason"),
39 }
40 return out
43def compare_values(live: dict[str, dict], offline: dict[str, float | None], floor: float, min_resolved: int) -> dict:
44 """Agreement of the two gate readings over the dates where both exist and live had enough resolved dates."""
45 pairs = [
46 (date, entry["value"], offline.get(date))
47 for date, entry in sorted(live.items())
48 if entry["value"] is not None and offline.get(date) is not None and entry["resolved"] >= min_resolved
49 ]
50 if len(pairs) < 3:
51 return {"dates": len(pairs)}
52 live_values = [value for _, value, _ in pairs]
53 offline_values = [value for _, _, value in pairs]
54 mean_live, mean_offline = sum(live_values) / len(pairs), sum(offline_values) / len(pairs)
55 covariance = sum((a - mean_live) * (b - mean_offline) for a, b in zip(live_values, offline_values, strict=False))
56 spread = math.sqrt(sum((a - mean_live) ** 2 for a in live_values) * sum((b - mean_offline) ** 2 for b in offline_values))
57 same_side = sum(1 for a, b in zip(live_values, offline_values, strict=False) if (a >= floor) == (b >= floor))
58 worst = sorted(pairs, key=lambda item: -abs(item[1] - item[2]))[:5]
59 return {
60 "dates": len(pairs),
61 "correlation": covariance / spread if spread > 0 else None,
62 "mean_live": mean_live,
63 "mean_offline": mean_offline,
64 "mean_abs_difference": sum(abs(a - b) for a, b in zip(live_values, offline_values, strict=False)) / len(pairs),
65 "same_side_of_floor_share": same_side / len(pairs),
66 "floor": floor,
67 "largest_differences": [{"date": d, "live": a, "offline": b} for d, a, b in worst],
68 }
71def main() -> int:
72 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
73 parser.add_argument("--book-history", required=True)
74 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
75 parser.add_argument("--splits", nargs="*", default=["backtest", "holdout"])
76 parser.add_argument("--warmup-days", type=int, default=400)
77 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v610" / "gate_value_compare.json"))
78 args = parser.parse_args()
80 from as_live_levers import AsLiveHarness
82 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
83 history = [json.loads(line) for line in Path(args.book_history).read_text(encoding="utf-8").splitlines() if line.strip()]
84 live = live_gate_values(history)
85 harness = AsLiveHarness(tuple(args.splits), dataset_path=args.dataset, config=config, gate_warmup_days=args.warmup_days)
86 frame = harness.lagged_frame
87 harness.gate_for(frame) # builds the rolling-IC state function for this frame
88 gate = config["phase_v2"]["rolling_ic_gate"]
89 state_fn = next(fn for key, fn in harness._states.items() if key[0] == id(frame))
90 offline = {date: (state_fn(date) or {}).get("rolling_mean_ic") for date in live}
91 report = compare_values(live, offline, float(gate.get("min_rolling_mean_ic", 0.0)), int(gate.get("min_resolved_dates_required", 20)))
92 report.update(book_history=str(args.book_history), splits=list(args.splits), warmup_days=args.warmup_days)
93 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
94 Path(args.out).write_text(json.dumps(report, indent=1, default=float), encoding="utf-8")
95 print(json.dumps({k: v for k, v in report.items() if k != "largest_differences"}, indent=1, default=float))
96 return 0
99if __name__ == "__main__":
100 raise SystemExit(main())