Coverage for evaluation/kill_switch_replay.py: 100%

87 statements  

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

1"""V5.2.8 (development/Problems.md #94) - a day-by-day OFFLINE replay of 

2main.py's kill-switch + sticky-trade-lock state machine, against a 

3purely offline return series (e.g. evaluation/rank_book_simulator.py:: 

4simulate_rank_book()'s own per_date_net_return output) - the first 

5offline counterpart to any of live's ~10 risk/execution gates 

6(development/Problems.md #92's own finding was that NONE of them had one 

7before this). Follows the exact three-tier pattern already established by 

8evaluation/rank_signal_calibration.py's reconcile_book_history_date()/ 

9replay_book_history_reconciliation()/summarize_book_history_reconciliation() 

10- a new, additive sibling module, never touching rank_book_simulator.py's 

11own simulate_rank_book() (that function's own docstring explicitly warns 

12against conflating raw ranking quality with live gate engagement - this 

13module answers a different question and lives separately on purpose). 

14 

15APPROXIMATION, NOT GROUND TRUTH (read before trusting this module's 

16numbers - see development/Problems.md #94 for the full caveat and the 

17named follow-up this does NOT attempt): real live state at any given date 

18depends on the ACTUAL trade-lock/liquidation path taken on every PRIOR 

19date (main.py's own session-rollover block, main.py:6140-6345) - this 

20replay mechanically reproduces that same state machine, but only ever 

21sees the offline return series, never the live book's own realized 

22(gate-diverged) history. It models exactly two of evaluate_kill_switch()'s 

237 runtime_metrics inputs (recent_bar_returns via a rolling deque, 

24drawdown_velocity_pct_per_bar via a running peak) plus 

25risk_controls.py::assess_drawdown_lock()'s daily/total drawdown breach - 

26both feed the SAME sticky trade-lock reason space main.py's own 

27session-rollover clearing logic uses. It does NOT model live_rank_ic, 

28consecutive_losses, slippage_divergence_bps, model_age_days, or 

29reconciliation_breach (no offline equivalent exists for any of these) - 

30they stay None throughout, which evaluate_kill_switch()'s own documented 

31None-skip contract degrades cleanly rather than fabricating a value for. 

32No bypass flags (bypass_sticky_trade_lock etc.) are modeled either - this 

33replay always represents the honest, non-bypassed sticky behavior.""" 

34 

35from __future__ import annotations 

36 

37from collections import deque 

38from dataclasses import asdict, dataclass, field 

39 

40from risk.kill_switch import evaluate_kill_switch 

41from risk_controls import assess_drawdown_lock 

42 

43_RETURN_HISTORY_MAXLEN = 252 

44 

45 

46@dataclass(frozen=True) 

47class KillSwitchReplayRecord: 

48 date: str 

49 tripped: bool 

50 severity: str 

51 triggers: list = field(default_factory=list) 

52 sticky_reason_active: bool = False 

53 trade_lock_reason: str | None = None 

54 would_be_locked: bool = False 

55 

56 def to_dict(self) -> dict: 

57 return asdict(self) 

58 

59 

60def _is_sticky_reason(reason: str | None) -> bool: 

61 """Byte-identical predicate to main.py:6178-6180's 

62 trade_lock_reason_is_sticky check - kept as its own function so it 

63 can never silently drift from the live condition it mirrors.""" 

64 return reason == "total_drawdown_limit_breached" or str(reason or "").startswith("kill_switch_") 

65 

66 

67def replay_kill_switch_over_dataset( 

68 dates: list, 

69 daily_portfolio_returns: dict, 

70 kill_switch_config: dict, 

71 *, 

72 max_daily_drawdown_pct: float, 

73 max_total_drawdown_pct: float, 

74 starting_portfolio_value: float = 1.0, 

75) -> list: 

76 """Day-by-day, in `dates` order (must already be sorted - callers own 

77 that, same convention as rank_book_simulator.py's unique_dates loop). 

78 

79 daily_portfolio_returns: {date: net_return} - reuse simulate_rank_book()'s 

80 own per_date_net_return/per_date pair directly (dict(zip(per_date, 

81 per_date_net_return))) rather than inventing a second return series. 

82 A date missing from this dict defaults to 0.0 return (a flat/no-trade 

83 day), never KeyError. 

84 

85 Mirrors main.py:6140-6345's exact per-date sequence: (1) sticky-lock 

86 clear/keep using the reason carried over from the PRIOR date, (2) 

87 portfolio_value/peak_equity/drawdown update from this date's return, 

88 (3) return-history + drawdown-velocity update, (4) 

89 assess_drawdown_lock() check, (5) evaluate_kill_switch() check - in 

90 that exact order, since main.py's own ordering determines which 

91 reason wins when more than one would fire the same date. Returns one 

92 dict (KillSwitchReplayRecord.to_dict()) per date.""" 

93 return_history: deque = deque(maxlen=_RETURN_HISTORY_MAXLEN) 

94 previous_portfolio_value = None 

95 previous_total_drawdown = None 

96 portfolio_value = float(starting_portfolio_value) 

97 peak_equity = portfolio_value 

98 trade_lock_active = False 

99 trade_lock_reason = None 

100 sharpe_tripped_last_bar = False 

101 sharpe_below_run_last_bar = 0 

102 

103 records = [] 

104 

105 for date in dates: 

106 # (1) sticky-lock clear/keep, using the reason carried over from 

107 # the PRIOR date - byte-identical predicate to main.py's own. 

108 if trade_lock_active and not _is_sticky_reason(trade_lock_reason): 

109 trade_lock_active = False 

110 trade_lock_reason = None 

111 

112 # (2) portfolio value / peak / drawdown, from the offline return 

113 # series. No separate session/day-open concept exists offline - 

114 # daily_drawdown collapses to this date's own one-bar return 

115 # (main.py's own daily_drawdown is itself session-open-to-now, 

116 # effectively the same figure at Daily resolution where a new 

117 # session starts every bar in backtest mode). 

118 net_return = float(daily_portfolio_returns.get(date, 0.0)) 

119 portfolio_value *= 1.0 + net_return 

120 peak_equity = max(peak_equity, portfolio_value) 

121 total_drawdown = portfolio_value / max(peak_equity, 1e-9) - 1.0 

122 daily_drawdown = net_return 

123 

124 # (3) return history + drawdown velocity, same deque convention 

125 # as main.py's self._kill_switch_return_history. 

126 if previous_portfolio_value is not None and previous_portfolio_value > 0: 

127 return_history.append(portfolio_value / previous_portfolio_value - 1.0) 

128 drawdown_velocity = ( 

129 abs(total_drawdown) - abs(previous_total_drawdown) if previous_total_drawdown is not None else None 

130 ) 

131 previous_portfolio_value = portfolio_value 

132 previous_total_drawdown = total_drawdown 

133 

134 # (4) drawdown-lock breach (risk_controls.py, byte-identical call 

135 # to main.py's own). 

136 breach_active, breach_reason = assess_drawdown_lock( 

137 daily_drawdown, total_drawdown, max_daily_drawdown_pct, max_total_drawdown_pct 

138 ) 

139 if breach_active: 

140 trade_lock_active = True 

141 trade_lock_reason = breach_reason 

142 

143 # (5) the kill switch itself - only the two dataset-derivable 

144 # runtime_metrics inputs are populated; every other input stays 

145 # None (evaluate_kill_switch()'s own documented None-skip 

146 # contract handles this cleanly, never fabricates a value). 

147 runtime_metrics = { 

148 "recent_bar_returns": list(return_history), 

149 "drawdown_velocity_pct_per_bar": drawdown_velocity, 

150 "live_rank_ic": None, 

151 "consecutive_losses": None, 

152 "slippage_divergence_bps": None, 

153 "model_age_days": None, 

154 "reconciliation_breach": False, 

155 "rolling_sharpe_tripped_last_bar": sharpe_tripped_last_bar, 

156 "rolling_sharpe_below_run_last_bar": sharpe_below_run_last_bar, 

157 } 

158 decision = evaluate_kill_switch(runtime_metrics, kill_switch_config) 

159 sharpe_tripped_last_bar = decision.rolling_sharpe_tripped 

160 sharpe_below_run_last_bar = decision.rolling_sharpe_below_run 

161 if decision.tripped: 

162 trade_lock_active = True 

163 trade_lock_reason = decision.reason 

164 

165 records.append( 

166 KillSwitchReplayRecord( 

167 date=str(date), 

168 tripped=decision.tripped, 

169 severity=decision.severity, 

170 triggers=list(decision.triggers), 

171 sticky_reason_active=_is_sticky_reason(trade_lock_reason), 

172 trade_lock_reason=trade_lock_reason, 

173 would_be_locked=trade_lock_active, 

174 ).to_dict() 

175 ) 

176 

177 return records 

178 

179 

180def summarize_kill_switch_replay(records: list) -> dict: 

181 """Aggregate trip-count / total-locked-days / locked-day fraction, 

182 mirroring evaluation/rank_signal_calibration.py:: 

183 summarize_book_history_reconciliation()'s aggregation shape.""" 

184 total_dates = len(records) 

185 trip_count = sum(1 for record in records if record["tripped"]) 

186 locked_days = sum(1 for record in records if record["would_be_locked"]) 

187 return { 

188 "total_dates": total_dates, 

189 "trip_count": trip_count, 

190 "locked_days": locked_days, 

191 "locked_day_fraction": (locked_days / total_dates) if total_dates else 0.0, 

192 } 

193 

194 

195def forward_window_returns(daily_returns: dict, horizon: int = 20) -> dict: 

196 """{date: compounded return of the next `horizon` dates after it} for every date with a full window (V6.4.0, lead L7). 

197 `daily_returns` = {date: return} of the book as it would have run UNLOCKED.""" 

198 dates = sorted(daily_returns) 

199 out = {} 

200 for index, date in enumerate(dates): 

201 window = dates[index + 1 : index + 1 + horizon] 

202 if len(window) < horizon: 

203 break 

204 growth = 1.0 

205 for day in window: 

206 growth *= 1.0 + float(daily_returns[day]) 

207 out[str(date)] = growth - 1.0 

208 return out 

209 

210 

211def percentile(values, q: float) -> float | None: 

212 """Linear-interpolated `q` quantile (0-1) of `values`; None when empty.""" 

213 ordered = sorted(float(value) for value in values) 

214 if not ordered: 

215 return None 

216 position = q * (len(ordered) - 1) 

217 low, high = int(position // 1), min(int(-(-position // 1)), len(ordered) - 1) 

218 return ordered[low] + (ordered[high] - ordered[low]) * (position - low) 

219 

220 

221def false_lock_share(locked_dates, forward_returns: dict, quantile: float = 2.0 / 3.0) -> float | None: 

222 """Share of locked dates whose UNLOCKED book went on to a next-`horizon` return at or above the `quantile` of all 

223 dates' forward returns: locks that sat out a strong stretch (V6.4.0, lead L7's "false lock"). None when no locked 

224 date has a full forward window.""" 

225 threshold = percentile(forward_returns.values(), quantile) 

226 scored = [forward_returns[str(date)] for date in locked_dates if str(date) in forward_returns] 

227 if threshold is None or not scored: 

228 return None 

229 return sum(1 for value in scored if value >= threshold) / len(scored)