Coverage for evaluation/rolling_ic_gate_replay.py: 100%
28 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"""Day-by-day OFFLINE replay of `portfolio.rolling_ic_gate`'s two decision
2functions against a historical dataset (V5.3.5, development/Problems.md
3#102) - the direct sibling of `evaluation/kill_switch_replay.py`'s
4day-by-day, no-lookahead, walk-forward structure, for this round's new
5rolling-IC gate instead of the kill switch.
7This is the critical pre-`main.py` checkpoint the V5.3.5 plan calls out:
8run this against the historical dataset with `evaluation/
9rolling_ic_gate_calibration.py`'s calibrated floor and confirm
10disengagement concentrates in the three known bad eras (Apr-Sep 2019,
11Dec 2019-Mar 2020, Jun-Sep 2020) rather than spreading uniformly across
12the whole run - entirely offline, before `main.py` is touched at all. A
13uniform reduction would mean this gate is just a redundant second
14dispersion floor, not a genuine skill signal, and is the signal to stop
15and revisit before A6 wires anything into the live path.
17NO-LOOKAHEAD DISCIPLINE - the single most important property this module
18has to get right: at each rebalance date, the event buffer passed to
19`compute_rolling_ic_state()` is built from `evaluation.
20rolling_ic_gate_calibration.build_event_buffer()` and then sliced to only
21events dated on-or-before that date (the same technique, and the same
22reason, that module's own docstring explains) - a decision "as of" date D
23must never see a row dated after D, exactly matching what main.py's own
24live in-memory buffer could possibly contain by that point in a real run.
25"""
27from __future__ import annotations
29from evaluation.rolling_ic_gate_calibration import build_event_buffer
30from evaluation.rolling_ic_series import make_rolling_ic_state_fn
31from portfolio.rolling_ic_gate import evaluate_rolling_ic_gate
33# development/Problems.md #102's own three named bad eras, found from this
34# round's research into rolling IC vs. the model's per-era IC diagnostic
35# (#71) - used only by summarize_rolling_ic_gate_replay()'s per-era
36# breakdown, so the offline report can be read directly against them
37# without a throwaway script re-deriving these boundaries by hand.
38KNOWN_ERAS = {
39 "era_0_good": ("2019-01-01", "2019-04-01"),
40 "era_1_bad_apr_sep_2019": ("2019-04-01", "2019-09-01"),
41 "era_2_bad_dec2019_mar2020": ("2019-12-01", "2020-03-01"),
42 "era_3_bad_jun_sep_2020": ("2020-06-01", "2020-09-01"),
43}
46def replay_rolling_ic_gate_over_dataset(
47 dataset,
48 *,
49 raw_score_column: str,
50 ticker_column: str = "ticker",
51 date_column: str = "date",
52 close_column: str = "close",
53 rebalance_dates: list[str],
54 horizon_days: int,
55 rolling_window_days: int,
56 gate_config: dict,
57 min_names_per_date: int = 10,
58) -> list[dict]:
59 """Builds the full event buffer once (`build_event_buffer()`), then for
60 each date in `rebalance_dates` (must already be sorted - callers own
61 that, same convention as `rank_book_simulator.py`'s unique_dates loop;
62 should be the SAME cadence a real book rebalance uses, not necessarily
63 every calendar date, matching main.py's own gate-is-only-consulted-on-
64 rebalance-bars design) slices the buffer to events dated <= that date
65 and evaluates the gate exactly as `portfolio.book_construction.
66 _select_book_group()` would.
68 `min_names_per_date` (V5.3.5, development/Problems.md #102) - passed
69 through to `compute_rolling_ic_state()`; defaults to 10 for the same
70 reason `evaluation/rolling_ic_gate_calibration.py::
71 calibrate_rolling_ic_floor()` does (see that function's own
72 docstring) - a real replay run at this module's own default of 2
73 showed the calibrated floor barely engaging during two of three known
74 historically-bad eras, traced to thin-universe origin dates forcing
75 spurious +-1.0 IC readings into the rolling mean.
77 Returns one dict per rebalance date: {"date", "engaged", "reason",
78 "observed_rolling_mean_ic", "min_rolling_mean_ic", "num_resolved_dates"}
79 - `evaluate_rolling_ic_gate()`'s own result dict plus "date"."""
80 events = build_event_buffer(
81 dataset, raw_score_column=raw_score_column, ticker_column=ticker_column,
82 date_column=date_column, close_column=close_column,
83 )
84 state_fn = make_rolling_ic_state_fn(
85 events, horizon_days=horizon_days, rolling_window_days=rolling_window_days, min_names_per_date=min_names_per_date
86 )
88 records = []
89 for date in rebalance_dates:
90 result = evaluate_rolling_ic_gate(state_fn(str(date)), gate_config)
91 records.append({"date": str(date), **result})
93 return records
96def _era_for_date(date: str) -> str | None:
97 for era_name, (start, end) in KNOWN_ERAS.items():
98 if start <= date < end:
99 return era_name
100 return None
103def summarize_rolling_ic_gate_replay(records: list[dict]) -> dict:
104 """Aggregate engaged/disengaged fractions overall and per known era
105 (`KNOWN_ERAS` above), mirroring `evaluation/kill_switch_replay.py::
106 summarize_kill_switch_replay()`'s aggregation shape. Dates outside
107 every named era are still counted in `"overall"` but not attributed to
108 any `"by_era"` entry - `KNOWN_ERAS` deliberately doesn't cover the
109 whole historical window, only the four eras this round's research
110 already characterized."""
111 total_dates = len(records)
112 disengaged = [record for record in records if not record["engaged"]]
113 disengaged_by_floor = [record for record in records if record["reason"] == "rolling_ic_below_floor"]
115 by_era: dict[str, dict] = {}
116 for era_name in KNOWN_ERAS:
117 era_records = [record for record in records if _era_for_date(record["date"]) == era_name]
118 era_disengaged = [record for record in era_records if not record["engaged"]]
119 by_era[era_name] = {
120 "total_dates": len(era_records),
121 "disengaged_days": len(era_disengaged),
122 "disengaged_day_fraction": (len(era_disengaged) / len(era_records)) if era_records else None,
123 }
125 return {
126 "overall": {
127 "total_dates": total_dates,
128 "disengaged_days": len(disengaged),
129 "disengaged_day_fraction": (len(disengaged) / total_dates) if total_dates else 0.0,
130 "disengaged_days_below_floor": len(disengaged_by_floor),
131 },
132 "by_era": by_era,
133 }