Coverage for evaluation/rolling_ic_gate_calibration.py: 100%
39 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"""Calibrates `phase_v2.rolling_ic_gate.min_rolling_mean_ic` from real data
2(V5.3.5, development/Problems.md #102) - the same "derive the number,
3don't guess it" discipline `aq evaluate --calibrate-book-spread` already
4established for `min_rank_confidence_spread`, applied to this round's new
5gate so its shipped floor is never a hand-guessed constant either.
7Deliberately reuses, never re-derives: `portfolio.rolling_ic_gate.
8compute_rolling_ic_state()` (the exact aggregation the live gate and
9`evaluation/rolling_ic_gate_replay.py` both call) and `evaluation.
10rank_ic_core.resolve_realized_rank_ic_observations()` beneath it. A
11calibrated floor computed here can never silently disagree with what the
12live gate means by "rolling IC," because it is the same code, not a
13parallel approximation.
15WALK-FORWARD, NOT A SINGLE FULL-HISTORY READING: naively calling
16`compute_rolling_ic_state()` once on the dataset's entire event history
17would let observations whose resolution only became known LATE in the
18dataset leak into a rolling-window reading nominally "as of" an EARLIER
19sample date - a real lookahead bug, since `resolve_realized_rank_ic_observations()`
20resolves every observation using the full buffer's own future close
21prices, not bounded to any particular "as of" date. This module avoids
22that by sampling a strided sequence of dates and, at each one, slicing
23the event buffer to only events dated on-or-before that sample date
24before calling `compute_rolling_ic_state()` - exactly what a live buffer
25would contain by that date, never more. `evaluation/rolling_ic_gate_replay.py`
26shares this same buffer-slicing discipline (see that module's own
27docstring) since it needs the identical no-lookahead guarantee for a
28different purpose (a per-date engagement decision instead of a
29calibration distribution).
31`sample_stride_days=5` (not every single date) keeps this an O(num_samples
32x average_buffer_size) offline computation rather than O(num_dates^2) -
33acceptable for a tool run once, by hand, never on any per-bar live path.
34"""
36from __future__ import annotations
38import numpy as np
39import pandas as pd
41from evaluation.rolling_ic_series import make_rolling_ic_state_fn
43_ROLLING_IC_DISTRIBUTION_PERCENTILES = {"p10": 0.10, "p25": 0.25, "median": 0.50, "p75": 0.75}
45# Same sentinel value as portfolio.rolling_ic_gate's own (private,
46# module-local) _NEVER_BELOW - kept as an independent local copy rather
47# than a cross-module import of a private name, matching how
48# risk/kill_switch.py's own _NEVER_BELOW is never imported elsewhere
49# either. Only meaningful as "the gate's own never-trips floor value";
50# never compared against the other module's copy directly.
51_NEVER_BELOW = -1e12
54def build_event_buffer(
55 dataset: pd.DataFrame,
56 *,
57 raw_score_column: str,
58 ticker_column: str = "ticker",
59 date_column: str = "date",
60 close_column: str = "close",
61) -> list[dict]:
62 """Converts `dataset` into the flat, date-sorted event-dict shape
63 `compute_rolling_ic_state()`/`resolve_realized_rank_ic_observations()`
64 expect - the offline equivalent of main.py's Pass 1c buffer append,
65 reused by both this module and `evaluation/rolling_ic_gate_replay.py`
66 so the two tools can never disagree about what an "event" is. Rows
67 missing either the raw score or the close price are skipped (mirrors
68 `resolve_realized_rank_ic_observations()`'s own "model still warming
69 up" skip contract), never fabricated."""
70 ordered = dataset.sort_values(date_column, kind="stable")
71 events: list[dict] = []
72 for ticker, date, score, close in zip(
73 ordered[ticker_column], ordered[date_column], ordered[raw_score_column], ordered[close_column], strict=False
74 ):
75 if score is None or (isinstance(score, float) and np.isnan(score)):
76 continue
77 if close is None or (isinstance(close, float) and np.isnan(close)):
78 continue
79 events.append(
80 {
81 "ticker": str(ticker),
82 "created_at": f"{date}T00:00:00Z",
83 "resolved_predicted_rank_20d": float(score),
84 "close_price": float(close),
85 }
86 )
87 return events
90def calibrate_rolling_ic_floor(
91 dataset: pd.DataFrame,
92 *,
93 raw_score_column: str,
94 ticker_column: str = "ticker",
95 date_column: str = "date",
96 close_column: str = "close",
97 horizon_days: int,
98 rolling_window_days: int,
99 percentile: float = 0.10,
100 sample_stride_days: int = 5,
101 min_names_per_date: int = 10,
102) -> dict:
103 """Walk-forward: at every `sample_stride_days`-th unique date in
104 `dataset`, computes the rolling IC state a live buffer would have had
105 by that date (event buffer sliced to <= that date, via
106 `build_event_buffer()` + `compute_rolling_ic_state()`), collects every
107 non-None `rolling_mean_ic` reading into a distribution, and returns
108 the `percentile`-th quantile as the calibrated floor.
110 Sample dates before enough history has accumulated (compute_rolling_ic_state()
111 returns `rolling_mean_ic=None`) are EXCLUDED from the distribution, not
112 counted as a 0.0 reading - a cold-start gap is missing data, not
113 evidence of zero skill.
115 `min_names_per_date` (V5.3.5, development/Problems.md #102) - passed
116 through to `compute_rolling_ic_state()`. Defaults to 10, well above
117 `compute_rolling_ic_state()`'s own pure-function default of 2: a real
118 run against this project's historical dataset found the p10-percentile
119 floor dominated by spurious +-1.0 readings from origin dates where
120 only 2-3 names had resolved (thin-universe/model-warmup dates,
121 mathematically forced to an extreme correlation regardless of real
122 skill) - excluding them here is what makes the resulting distribution
123 represent genuine cross-sectional skill rather than early-history
124 noise. See evaluation.rank_ic_core.rank_ic_from_arrays()'s own
125 docstring for the full mechanism.
127 Returns:
128 {"calibrated_min_rolling_mean_ic": float,
129 "percentile": float,
130 "num_samples_used": int,
131 "num_samples_skipped_insufficient_history": int,
132 "rolling_ic_distribution": {"min", "p10", "p25", "median", "p75", "max"}}
134 An empty/all-thin dataset returns calibrated_min_rolling_mean_ic=_NEVER_BELOW
135 (portfolio.rolling_ic_gate's own "gate never trips" sentinel) and an
136 all-None distribution, never raises."""
137 events = build_event_buffer(
138 dataset, raw_score_column=raw_score_column, ticker_column=ticker_column,
139 date_column=date_column, close_column=close_column,
140 )
141 if not events:
142 return {
143 "calibrated_min_rolling_mean_ic": _NEVER_BELOW,
144 "percentile": percentile,
145 "num_samples_used": 0,
146 "num_samples_skipped_insufficient_history": 0,
147 "rolling_ic_distribution": {"min": None, "p10": None, "p25": None, "median": None, "p75": None, "max": None},
148 }
150 event_dates = [str(event["created_at"])[:10] for event in events]
151 unique_dates = sorted(set(event_dates))
152 sample_dates = unique_dates[::sample_stride_days] if sample_stride_days > 0 else unique_dates
154 state_fn = make_rolling_ic_state_fn(
155 events, horizon_days=horizon_days, rolling_window_days=rolling_window_days, min_names_per_date=min_names_per_date
156 )
157 readings: list[float] = []
158 num_samples_skipped_insufficient_history = 0
159 for sample_date in sample_dates:
160 state = state_fn(sample_date)
161 if state["rolling_mean_ic"] is None:
162 num_samples_skipped_insufficient_history += 1
163 continue
164 readings.append(state["rolling_mean_ic"])
166 if not readings:
167 return {
168 "calibrated_min_rolling_mean_ic": _NEVER_BELOW,
169 "percentile": percentile,
170 "num_samples_used": 0,
171 "num_samples_skipped_insufficient_history": num_samples_skipped_insufficient_history,
172 "rolling_ic_distribution": {"min": None, "p10": None, "p25": None, "median": None, "p75": None, "max": None},
173 }
175 readings_array = np.array(readings, dtype=np.float64)
176 distribution = {"min": float(np.min(readings_array)), "max": float(np.max(readings_array))}
177 for name, quantile in _ROLLING_IC_DISTRIBUTION_PERCENTILES.items():
178 distribution[name] = float(np.quantile(readings_array, quantile))
180 return {
181 "calibrated_min_rolling_mean_ic": float(np.quantile(readings_array, percentile)),
182 "percentile": percentile,
183 "num_samples_used": len(readings),
184 "num_samples_skipped_insufficient_history": num_samples_skipped_insufficient_history,
185 "rolling_ic_distribution": distribution,
186 }