Coverage for portfolio/rolling_ic_gate.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""V5.3.5 (development/Problems.md #102): a rolling TRAILING realized-IC 

2gate for book engagement - the direct sibling of 

3portfolio/book_construction.py::compute_confidence_spread()'s consumer in 

4_select_book_group(), added because dispersion and skill turned out to be 

5different things a real backtest could tell apart even when the existing 

6min_rank_confidence_spread gate couldn't. 

7 

8Background: #102 found that lowering min_rank_confidence_spread (which 

9only measures whether the model's raw scores are DISPERSED today) let the 

10live book trade through real, historically bad stretches where the 

11model's own per-era IC diagnostic (#71) is near-zero or negative - a 

12day's scores can look perfectly "spread out" while carrying zero genuine 

13predictive validity. This module adds an independent, second veto based 

14on TRAILING REALIZED IC (was the model actually right, recently) rather 

15than same-day dispersion. 

16 

17Deliberately its own module, not folded into book_construction.py or 

18risk/kill_switch.py: 

19 - book_construction.py is same-bar cross-sectional selection math with 

20 no temporal/resolution state today (compute_confidence_spread() reads 

21 only this bar's own scores). This gate needs a multi-bar buffer and a 

22 "wait for the future, then resolve" shape - closer in spirit to 

23 evaluation/kill_switch_replay.py's day-by-day state-carry pattern - 

24 and deserves its own independently-testable home, the same 

25 relationship portfolio/book_neutrality.py already has to 

26 book_construction.py (a sibling module, imported by main.py's call 

27 site, not inlined). 

28 - risk/kill_switch.py already has a dormant `min_live_rank_ic` 

29 condition, but it reads `live_rank_ic` from a locally-cached file 

30 only a separate Postgres-connected worker ever writes 

31 (visualization/grafana/retraining_status.json) - which doesn't exist 

32 in a standalone `aq backtest` run, so that condition is a live no-op 

33 during backtests today. It is also a portfolio-wide sticky trade-lock 

34 trip (blast radius: everything), a different kind of decision from 

35 this module's book-construction-level, per-rebalance engagement veto 

36 (blast radius: this one rebalance). Wiring this module's rolling 

37 buffer into that kill-switch condition too would be a real, small, 

38 separately-verifiable follow-up - explicitly not done here, to keep 

39 this round's verification story to one mechanism. 

40 

41Pure, deterministic, cheap - both functions below do only pandas/numpy 

42work over an already-assembled event list (no I/O), respecting main.py's 

43per-bar latency budget the same way every other pure risk/analyzer module 

44in this codebase does (risk/kill_switch.py, analyzer/market_analyzer.py). 

45 

46Design choice: a hard, boolean gate - not a continuous position-sizing 

47multiplier. Every existing book-level check (min_rank_confidence_spread) 

48is a hard veto with a single, audit-log-able reason, and 

49book_construction.py's own docstring already defers continuous 

50rank-weighted sizing as a documented future extension rather than 

51building it alongside a same-round change to the selection logic itself. 

52A scaling multiplier for this signal specifically is the same kind of 

53not built, for the same reason: shipping a new signal and 

54a new sizing curve in the same round makes it impossible to attribute a 

55verification result to either one cleanly. 

56""" 

57 

58from __future__ import annotations 

59 

60import math 

61from typing import Any 

62 

63from evaluation.rank_ic_core import aggregate_rank_ic_observations, resolve_realized_rank_ic_observations 

64 

65# Same "this condition can never fire" sentinel convention as 

66# risk/kill_switch.py::_NEVER_BELOW - enabling this gate must never, by 

67# itself, activate an uncalibrated threshold. The real floor comes from 

68# evaluation/rolling_ic_gate_calibration.py, never guessed. 

69_NEVER_BELOW = -1e12 

70 

71 

72def compute_rolling_ic_state( 

73 event_buffer: list[dict], 

74 *, 

75 horizon_days: int, 

76 rolling_window_days: int, 

77 min_names_per_date: int = 2, 

78) -> dict[str, Any]: 

79 """Resolves `event_buffer` (main.py's own flat, in-memory 

80 {"ticker", "created_at", "resolved_predicted_rank_20d", "close_price"} 

81 deque, or the offline replay/calibration tools' equivalent) via 

82 evaluation.rank_ic_core.resolve_realized_rank_ic_observations(), then 

83 restricts to the trailing `rolling_window_days` UNIQUE resolved 

84 origin dates (not calendar days, and not raw observation count - a 

85 date with more symbols resolved must not count for more "days" of 

86 trailing history than a thin one) before aggregating. 

87 

88 `min_names_per_date` (V5.3.5, development/Problems.md #102) - default 

89 2 preserves this function's original behavior exactly (see 

90 evaluation.rank_ic_core.rank_ic_from_arrays()'s own docstring for why 

91 this exists: a 2-name origin date is mathematically forced to a 

92 +-1 IC reading regardless of real skill, and real historical data 

93 confirmed this dominates the low tail of a walk-forward calibration's 

94 distribution). Callers evaluating a live or replayed rolling-IC 

95 reading - where thin-universe noise masquerading as "the model is 

96 badly wrong" would cause a spurious veto - should pass a value well 

97 above 2 (evaluation/rolling_ic_gate_calibration.py and evaluation/ 

98 rolling_ic_gate_replay.py both default to 10, sourced from 

99 phase_v2.rolling_ic_gate.min_names_per_date). 

100 

101 Returns {"rolling_mean_ic": float | None, "num_resolved_dates": int, 

102 "num_resolved_observations": int}. `rolling_mean_ic` is None (never 

103 0.0) when zero observations have resolved yet - "unknown" must never 

104 be silently treated as "IC is exactly zero" by evaluate_rolling_ic_gate() 

105 below, the same None-vs-neutral-default distinction every other pure 

106 signal function in this codebase already draws (e.g. 

107 risk/kill_switch.py::_rolling_sharpe()).""" 

108 resolved = resolve_realized_rank_ic_observations(event_buffer, horizon_days=horizon_days) 

109 if not resolved: 

110 return {"rolling_mean_ic": None, "num_resolved_dates": 0, "num_resolved_observations": 0} 

111 

112 unique_dates = sorted({observation["origin_date"] for observation in resolved}) 

113 trailing_dates = set(unique_dates[-rolling_window_days:]) if rolling_window_days > 0 else set() 

114 trailing_observations = [observation for observation in resolved if observation["origin_date"] in trailing_dates] 

115 

116 if not trailing_observations: 

117 return {"rolling_mean_ic": None, "num_resolved_dates": 0, "num_resolved_observations": 0} 

118 

119 aggregate = aggregate_rank_ic_observations(trailing_observations, min_names_per_date=min_names_per_date) 

120 return { 

121 "rolling_mean_ic": aggregate["mean_ic"] if aggregate["num_dates"] > 0 else None, 

122 "num_resolved_dates": aggregate["num_dates"], 

123 "num_resolved_observations": len(trailing_observations), 

124 } 

125 

126 

127def evaluate_rolling_ic_gate(rolling_ic_state: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]: 

128 """Pure decision function - the direct sibling of 

129 portfolio.book_construction.compute_confidence_spread()'s consumer at 

130 _select_book_group(). `rolling_ic_state` is compute_rolling_ic_state()'s 

131 own output; `config` is phase_v2.rolling_ic_gate's dict. 

132 

133 GUARDRAIL - fail-open at two levels, matching 

134 risk/kill_switch.py::evaluate_kill_switch()'s own documented contract: 

135 1. config["enabled"] is False -> always engaged, full no-op, 

136 regardless of any other input. 

137 2. num_resolved_dates < min_resolved_dates_required (default: 

138 config's own rolling_window_days, matching evaluate_kill_switch()'s 

139 min_bars_for_sharpe precedent - "the trailing window size" is the 

140 value's own documented intent) -> also engaged. A cold-start 

141 buffer (the first ~40-60 live bars of any run, before enough 

142 predictions have had time to resolve against a realized 20-day 

143 forward return) must never masquerade as "IC is bad" - it must 

144 masquerade as "gate not evaluated yet". 

145 

146 Returns {"engaged": bool, "reason": str, "observed_rolling_mean_ic": 

147 float | None, "min_rolling_mean_ic": float, "num_resolved_dates": int}.""" 

148 min_rolling_mean_ic = float(config.get("min_rolling_mean_ic", _NEVER_BELOW)) 

149 num_resolved_dates = int(rolling_ic_state.get("num_resolved_dates", 0)) 

150 observed_rolling_mean_ic = rolling_ic_state.get("rolling_mean_ic") 

151 

152 if not bool(config.get("enabled", False)): 

153 return { 

154 "engaged": True, 

155 "reason": "rolling_ic_gate_disabled", 

156 "observed_rolling_mean_ic": observed_rolling_mean_ic, 

157 "min_rolling_mean_ic": min_rolling_mean_ic, 

158 "num_resolved_dates": num_resolved_dates, 

159 } 

160 

161 min_resolved_dates_required = int(config.get("min_resolved_dates_required", config.get("rolling_window_days", 40))) 

162 if num_resolved_dates < min_resolved_dates_required or observed_rolling_mean_ic is None: 

163 return { 

164 "engaged": True, 

165 "reason": "rolling_ic_gate_insufficient_history", 

166 "observed_rolling_mean_ic": observed_rolling_mean_ic, 

167 "min_rolling_mean_ic": min_rolling_mean_ic, 

168 "num_resolved_dates": num_resolved_dates, 

169 } 

170 

171 # V6.6.7 (#377): still fail-open, as documented, but named: a NaN compared False and reported "above floor" 

172 if not (math.isfinite(float(observed_rolling_mean_ic)) and math.isfinite(float(min_rolling_mean_ic))): 

173 return { 

174 "engaged": True, 

175 "reason": "rolling_ic_nonfinite", 

176 "observed_rolling_mean_ic": observed_rolling_mean_ic, 

177 "min_rolling_mean_ic": min_rolling_mean_ic, 

178 "num_resolved_dates": num_resolved_dates, 

179 } 

180 if observed_rolling_mean_ic < min_rolling_mean_ic: 

181 return { 

182 "engaged": False, 

183 "reason": "rolling_ic_below_floor", 

184 "observed_rolling_mean_ic": observed_rolling_mean_ic, 

185 "min_rolling_mean_ic": min_rolling_mean_ic, 

186 "num_resolved_dates": num_resolved_dates, 

187 } 

188 

189 return { 

190 "engaged": True, 

191 "reason": "rolling_ic_above_floor", 

192 "observed_rolling_mean_ic": observed_rolling_mean_ic, 

193 "min_rolling_mean_ic": min_rolling_mean_ic, 

194 "num_resolved_dates": num_resolved_dates, 

195 } 

196 

197 

198LATE_BAR_SECURITY_TYPES = frozenset({"forex", "crypto"}) 

199LATE_BAR_EVENT_COUNTS = ("per_tick", "once") 

200 

201 

202def resolve_late_bar_event_count(gate_config: dict[str, Any] | None) -> str: 

203 """`rolling_ic_gate.late_bar_event_count` (V6.2.0): "per_tick" (default, the behaviour up to V6.1.0) records a 

204 crypto / forex symbol's event on its own midnight tick AND again on the next equity tick, where its last bar is 

205 re-scored, so it weighs twice per date in the gate's IC; "once" records it on its own tick only.""" 

206 value = str((gate_config or {}).get("late_bar_event_count", "per_tick")).lower() 

207 return value if value in LATE_BAR_EVENT_COUNTS else "per_tick" 

208 

209 

210def should_record_ic_event(security_type: str, fresh_bar: bool, mode: str) -> bool: 

211 """Whether this tick's rank event for one symbol enters the rolling-IC buffer: always, except a late-bar symbol 

212 re-scored without a fresh bar under "once". Shared by main.py and the offline replica (evaluation.live_parity).""" 

213 return not (mode == "once" and str(security_type).lower() in LATE_BAR_SECURITY_TYPES and not fresh_bar)