Coverage for evaluation/gate_audit.py: 100%
54 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"""Rolling-IC gate audit (V5.8.0, todo lead 1).
3On the 2021-25 holdout the idealized book earned +0.55 Sharpe while the as-live book lost -0.21: the rolling-IC gate
4vetoed 513 of 630 rebalances although the pooled rank IC was +0.055 (HAC t 3.95). A gate that sees a positive signal and
5still vetoes four rebalances in five is either measuring something else or measuring it late. This module puts the gate's
6own reading next to what it is supposed to estimate, date by date:
8 * `state_mean_ic` - what `compute_rolling_ic_state` (the live function, via the incremental offline state) reports,
9 * `resolved_trailing_ic` - the mean of the FULLY resolved daily IC (dataset rank target, every name) over the same
10 number of trailing origin dates whose horizon has elapsed by that date - the quantity the gate estimates,
11 * `forward_ic` - the daily IC of the decision date itself (known only later), i.e. whether a veto was right.
13Summary: veto share, false-veto share (vetoed although the forward IC was positive), the correlation between the gate's
14reading and the resolved trailing IC, and the mean gap between them. Pure pandas/numpy, no I/O.
15"""
17from __future__ import annotations
19import numpy as np
20import pandas as pd
23def daily_rank_ic(
24 frame: pd.DataFrame,
25 *,
26 score_column: str,
27 target_column: str,
28 date_column: str = "date",
29 min_names_per_date: int = 10,
30) -> dict[str, float]:
31 """{date: Spearman IC of the score against the (already per-date ranked) target}, dates under the name floor or with
32 no variance skipped."""
33 out: dict[str, float] = {}
34 data = frame[[date_column, score_column, target_column]].dropna()
35 for date, day in data.groupby(date_column, sort=True):
36 if len(day) < min_names_per_date:
37 continue
38 score_rank = day[score_column].rank().to_numpy()
39 target_rank = day[target_column].rank().to_numpy()
40 if np.ptp(score_rank) == 0.0 or np.ptp(target_rank) == 0.0:
41 continue
42 value = float(np.corrcoef(score_rank, target_rank)[0, 1])
43 if np.isfinite(value):
44 out[str(date)[:10]] = value
45 return out
48def resolved_trailing_ic(
49 daily_ic: dict[str, float], trading_dates: list[str], *, horizon: int, window: int
50) -> dict[str, float | None]:
51 """For each date D in `trading_dates` (the equity-session calendar), the mean daily IC over the `window` most recent
52 origin dates whose `horizon`-session forward window ended strictly before D - what a perfect, fully resolved trailing
53 gate would read on D."""
54 positions = {date: index for index, date in enumerate(trading_dates)}
55 ic_dates = sorted(date for date in daily_ic if date in positions)
56 ic_positions = np.array([positions[date] for date in ic_dates], dtype=int)
57 ic_values = np.array([daily_ic[date] for date in ic_dates], dtype=float)
58 out: dict[str, float | None] = {}
59 for date in trading_dates:
60 cutoff = positions[date] - horizon # origin + horizon < D <=> origin <= D - horizon - 1
61 eligible = np.nonzero(ic_positions < cutoff)[0]
62 if len(eligible) == 0:
63 out[date] = None
64 continue
65 tail = eligible[-window:]
66 out[date] = float(ic_values[tail].mean())
67 return out
70def audit_rolling_ic_gate(
71 *,
72 decision_dates: list[str],
73 gate_fn,
74 state_fn,
75 daily_ic: dict[str, float],
76 trading_dates: list[str],
77 horizon: int,
78 window: int,
79) -> dict:
80 """`gate_fn(date) -> evaluate_rolling_ic_gate() dict`, `state_fn(date) -> compute_rolling_ic_state() dict` (the same
81 objects the as-live simulator uses). `decision_dates` are the rebalance dates to audit."""
82 trailing = resolved_trailing_ic(daily_ic, trading_dates, horizon=horizon, window=window)
83 rows = []
84 for date in decision_dates:
85 key = str(date)[:10]
86 state = state_fn(key) or {}
87 verdict = gate_fn(key) or {}
88 rows.append(
89 {
90 "date": key,
91 "engaged": bool(verdict.get("engaged", True)),
92 "reason": verdict.get("reason"),
93 "state_mean_ic": state.get("rolling_mean_ic"),
94 "state_resolved_dates": state.get("num_resolved_dates"),
95 "state_resolved_observations": state.get("num_resolved_observations"),
96 "resolved_trailing_ic": trailing.get(key),
97 "forward_ic": daily_ic.get(key),
98 }
99 )
100 vetoed = [row for row in rows if not row["engaged"]]
101 false_vetoes = [row for row in vetoed if row["forward_ic"] is not None and row["forward_ic"] > 0]
102 true_vetoes = [row for row in vetoed if row["forward_ic"] is not None and row["forward_ic"] <= 0]
103 paired = [
104 (row["state_mean_ic"], row["resolved_trailing_ic"])
105 for row in rows
106 if row["state_mean_ic"] is not None and row["resolved_trailing_ic"] is not None
107 ]
108 correlation = None
109 mean_gap = None
110 if len(paired) >= 3:
111 state_values, resolved_values = map(np.asarray, zip(*paired, strict=False))
112 if np.std(state_values) > 0 and np.std(resolved_values) > 0:
113 correlation = float(np.corrcoef(state_values, resolved_values)[0, 1])
114 mean_gap = float(np.mean(state_values - resolved_values))
115 resolved_would_veto = [
116 row for row in rows if row["resolved_trailing_ic"] is not None and row["resolved_trailing_ic"] < 0.0
117 ]
118 forward = [row["forward_ic"] for row in rows if row["forward_ic"] is not None]
119 return {
120 "num_decisions": len(rows),
121 "num_vetoed": len(vetoed),
122 "veto_share": (len(vetoed) / len(rows)) if rows else None,
123 "num_false_vetoes": len(false_vetoes),
124 "false_veto_share_of_vetoes": (len(false_vetoes) / len(vetoed)) if vetoed else None,
125 "num_true_vetoes": len(true_vetoes),
126 "mean_forward_ic_all": float(np.mean(forward)) if forward else None,
127 "mean_forward_ic_vetoed": float(np.mean([r["forward_ic"] for r in vetoed if r["forward_ic"] is not None]))
128 if any(r["forward_ic"] is not None for r in vetoed)
129 else None,
130 "state_vs_resolved_correlation": correlation,
131 "state_minus_resolved_mean_gap": mean_gap,
132 "resolved_gate_veto_share": (len(resolved_would_veto) / len(rows)) if rows else None,
133 "rows": rows,
134 }