Coverage for evaluation/rank_book_simulator.py: 100%

655 statements  

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

1"""Cost-aware offline simulation of the cross-sectional rank book (V5.1 

2Phase 0). Reuses the EXACT selection/neutrality machinery main.py's live 

3decision path uses - portfolio.book_construction.build_rank_based_book() 

4and portfolio.book_neutrality.apply_book_neutrality() - so this module's 

5numbers are the offline mirror of live behavior, not an independently 

6re-derived approximation. Both of those are pure Python/dataclasses (no 

7torch, no pandas), so importing them here does not compromise this 

8package's torch-free contract (see evaluation/__init__.py's docstring). 

9""" 

10 

11from __future__ import annotations 

12 

13import math 

14from dataclasses import asdict, dataclass, field, replace 

15from typing import Any 

16 

17import numpy as np 

18import pandas as pd 

19 

20from portfolio.book_construction import ( 

21 BookAllocation, 

22 apply_class_weight_caps, 

23 build_book_raw_weights, 

24 build_rank_based_book, 

25 partial_adjust_weights, 

26 remember_formed_book, 

27) 

28from portfolio.book_neutrality import apply_book_neutrality 

29from portfolio.rank_signal import MAIN_RANK_GROUP, grouped_cross_sectional_rank_scores 

30from portfolio.sleeve_guard import evaluate_sleeve_guard, resolve_sleeve_guard_config 

31from risk.asset_class_router import asset_listed_on_venue 

32from risk.kill_switch import evaluate_kill_switch 

33from risk_controls import evaluate_non_model_exit, should_scale_position 

34 

35DEFAULT_SECTOR_MAX_NET_WEIGHT = 0.05 

36# main.py's `_kill_switch_return_history` deque length. 

37_KILL_SWITCH_HISTORY_MAXLEN = 252 

38# NAV the per-name impact and minimum-commission terms assume when none is configured (config.json initial cash). 

39DEFAULT_ASSUMED_PORTFOLIO_VALUE_USD = 100_000.0 

40 

41 

42@dataclass(frozen=True) 

43class RankBookSimulationResult: 

44 """One rank-book simulation: gross and net Sharpe and return, drawdown, turnover, cost drag and the daily series.""" 

45 gross_sharpe: float 

46 net_sharpe: float 

47 gross_total_return: float 

48 net_total_return: float 

49 net_max_drawdown: float 

50 annualized_turnover: float 

51 cost_drag_annual_bps: float 

52 num_rebalances: int 

53 num_dates_used: int 

54 mean_names_long: float 

55 mean_names_short: float 

56 per_date_net_return: list = field(default_factory=list) 

57 per_date: list = field(default_factory=list) 

58 # V5.5.0 (as-live mode) - 0 / {} in the idealized default run. 

59 num_vetoed_rebalances: int = 0 

60 veto_reasons: dict = field(default_factory=dict) 

61 # V5.7.0 - kill-switch lock days / frozen member decisions, 0 unless `kill_switch_config` is passed. 

62 num_kill_switch_locked_dates: int = 0 

63 num_kill_switch_frozen_decisions: int = 0 

64 kill_switch_locked_date_list: list = field(default_factory=list) 

65 # V5.8.0 - dates on which the sleeve guard kept the book flat (0 unless `sleeve_guard_config` is enabled). 

66 num_sleeve_guard_suspended_dates: int = 0 

67 # V5.7.0 - mean sum of |weight| and of signed weight over the dates used (NAV fractions), for sizing parity checks. 

68 mean_gross_exposure: float = 0.0 

69 mean_net_exposure: float = 0.0 

70 # V6.0.0: one {"date", "engaged", "reason", "locked"} per rebalance attempt (lean_calibration's decision agreement). 

71 rebalance_log: list = field(default_factory=list) 

72 # V6.0.0, with log_weights=True: the weights held after each date's rebalance, aligned with per_date. 

73 weights_log: list = field(default_factory=list) 

74 # V6.1.0: per-component net returns ({"main_book": {date: r}, "legacy": {date: r}}) when the legacy signal is modelled. 

75 per_date_component_returns: dict = field(default_factory=dict) 

76 

77 def to_dict(self) -> dict[str, Any]: 

78 return asdict(self) 

79 

80 

81def _annualized_sharpe(returns: np.ndarray, trading_days_per_year: int) -> float: 

82 """Same convention as train.py::compute_strategy_metrics() - 

83 (mean/std) * sqrt(trading_days_per_year) - kept identical so this 

84 simulator's Sharpe is directly comparable to every other Sharpe number 

85 already reported by this codebase.""" 

86 if len(returns) < 2: 

87 return 0.0 

88 std = float(returns.std(ddof=1)) 

89 if std <= 0.0: 

90 return 0.0 

91 return float(returns.mean() / std) * math.sqrt(trading_days_per_year) 

92 

93 

94def _empty_result(trading_days_per_year: int) -> RankBookSimulationResult: 

95 return RankBookSimulationResult( 

96 gross_sharpe=0.0, 

97 net_sharpe=0.0, 

98 gross_total_return=0.0, 

99 net_total_return=0.0, 

100 net_max_drawdown=0.0, 

101 annualized_turnover=0.0, 

102 cost_drag_annual_bps=0.0, 

103 num_rebalances=0, 

104 num_dates_used=0, 

105 mean_names_long=0.0, 

106 mean_names_short=0.0, 

107 per_date_net_return=[], 

108 per_date=[], 

109 ) 

110 

111 

112def _cap_new_entries( 

113 new_weights: dict[str, float], held_weights: dict[str, float], ranks: dict[str, float | None], max_positions: int 

114) -> dict[str, float]: 

115 """live's _apply_signal: a NEW entry is skipped once `max_positions` positions are open; held members always stay. 

116 Members are processed in conviction order (|rank - 0.5|, main.py's Pass 2 sort).""" 

117 kept = {symbol: weight for symbol, weight in new_weights.items() if symbol in held_weights} 

118 entries = sorted( 

119 (symbol for symbol in new_weights if symbol not in held_weights), 

120 key=lambda symbol: -abs(float(ranks.get(symbol) if ranks.get(symbol) is not None else 0.5) - 0.5), 

121 ) 

122 room = max(0, max_positions - len(kept)) 

123 for symbol in entries[:room]: 

124 kept[symbol] = new_weights[symbol] 

125 return kept 

126 

127 

128def _new_legacy_state() -> dict[str, Any]: 

129 return {"weights": {}, "history": [], "entry_index": {}, "peak": {}, "last_trade": {}, "band": {}, "previous": {}} 

130 

131 

132def _legacy_mark(state: dict[str, Any], returns_today: dict[str, float]) -> float: 

133 """Return of the held legacy positions on a date that is not traded (a skipped weekend date).""" 

134 weights = state["history"][-1] if state["history"] else {} 

135 return sum(weight * float(returns_today.get(symbol, 0.0)) for symbol, weight in weights.items()) 

136 

137 

138def _legacy_lagged_return(state: dict[str, Any], date_returns: dict[str, Any], entry_lag_bars: int, *, record: bool = False) -> float: 

139 """The legacy positions' return for this date: with an entry lag the weights held `entry_lag_bars` dates ago earn 

140 it (the order filled at the next open), exactly as the book. `record` appends today's weights to the history.""" 

141 history = state["history"] 

142 if entry_lag_bars > 0: 

143 index = len(history) - entry_lag_bars 

144 weights = history[index] if index >= 0 else {} 

145 else: 

146 weights = state["weights"] 

147 value = sum(weight * float(date_returns.get(symbol, 0.0)) for symbol, weight in weights.items()) 

148 if record: 

149 state["previous"] = weights 

150 history.append(dict(state["weights"])) 

151 return value 

152 

153 

154def _legacy_intraday(state: dict[str, Any], eligible: pd.DataFrame, ticker_column: str, column: str) -> float: 

155 """The next session's open-to-close move earned by the legacy weights that changed today (next-open fill).""" 

156 current, previous = state["weights"], state["previous"] 

157 intraday = dict(zip(eligible[ticker_column].astype(str), eligible[column], strict=False)) 

158 total = 0.0 

159 for symbol in set(current) | set(previous): 

160 delta = current.get(symbol, 0.0) - previous.get(symbol, 0.0) 

161 value = intraday.get(symbol) 

162 if delta != 0.0 and value == value and value is not None: 

163 total += delta * float(value) 

164 return total 

165 

166 

167def _legacy_step(state: dict[str, Any], component: dict[str, Any], *, eligible: pd.DataFrame, date: str, date_index: int, is_session: bool, 

168 ticker_column: str, close_column: str, book_members: set[str], book_held: dict[str, float], 

169 book_active: bool, kill_switch_locked: bool, candidate_metadata_by_ticker: dict[str, Any], 

170 cost_bps: float, commission_override, min_commission_usd_by_ticker: dict[str, Any] | None, pv_for_costs: float, 

171 max_active_positions: int | None, cooldown_dates: int, resize_threshold_weight: float) -> tuple[float, float]: 

172 """One date of the legacy probability signal on non-members (main.py Pass 1c `_derive_signal` + Pass 2's non-member 

173 branch). Shared pure pieces: `data_pipeline.bar_synthesis.derive_signal` / `adaptive_sell_threshold` (the signal and 

174 its adaptive sell band, recorded for every symbol every date as Pass 1c does), `portfolio.legacy_sleeve. 

175 apply_legacy_sleeve_policy` (budget, per-name cap, no new entry while the book is vetoed), the member chain 

176 `component["weight_fn"]` (sizing, liquidity, net edge and the analyzer's verdict), `risk_controls. 

177 evaluate_non_model_exit` (age / trailing stop) and the live cooldown / position cap. A legacy "sell" closes a held 

178 position (analyzer Priority 0); the legacy signal never shorts (main.py's `already_flat`). Returns (cost, turnover) 

179 as NAV fractions.""" 

180 from data_pipeline.bar_synthesis import adaptive_sell_threshold, derive_signal 

181 from portfolio.legacy_sleeve import apply_legacy_sleeve_policy 

182 

183 signal = component["signal"] 

184 sleeve_config = component["sleeve_config"] 

185 probability_column = component["probability_column"] 

186 classes = set(component.get("asset_classes", ("equity", "crypto"))) 

187 weight_fn = component.get("weight_fn") 

188 max_holding = component.get("max_holding_dates") 

189 stop_pct = component.get("trailing_stop_pct") 

190 weights = state["weights"] 

191 new_weights = dict(weights) 

192 if probability_column not in eligible.columns: 

193 return 0.0, 0.0 

194 rows = eligible.set_index(eligible[ticker_column].astype(str)).to_dict("index") 

195 for symbol in list(new_weights): # backstop exits first, as Pass 2 checks them before the signal 

196 row = rows.get(symbol) 

197 close = float(row.get(close_column)) if row and row.get(close_column) == row.get(close_column) else None 

198 if close is None or close <= 0.0: 

199 continue 

200 reason = evaluate_non_model_exit( 

201 date_index, True, int(max_holding or 10**9), float(stop_pct) if stop_pct else float("inf"), 

202 state["entry_index"].get(symbol, date_index), state["peak"].get(symbol), "long", close, 

203 ) if (max_holding is not None or stop_pct) else None 

204 if reason in ("max_holding_age_exceeded", "trailing_stop_triggered"): 

205 new_weights.pop(symbol) 

206 elif state["peak"].get(symbol) is None or close > state["peak"][symbol]: 

207 state["peak"][symbol] = close 

208 gross_used = sum(abs(weight) for symbol, weight in new_weights.items() if symbol not in book_members) 

209 for symbol, row in rows.items(): 

210 probability = row.get(probability_column) 

211 if probability is None or probability != probability: 

212 continue 

213 history = state["band"].setdefault(symbol, []) 

214 effective_sell = adaptive_sell_threshold( 

215 sell_threshold=signal["sell_threshold"], history=history, band_enabled=signal["band_enabled"], 

216 min_observations=signal["band_min_observations"], band_percentile=signal["band_percentile"], 

217 ) 

218 name, confidence, target = derive_signal( 

219 float(probability), decision_threshold=signal["decision_threshold"], buy_threshold=signal["buy_threshold"], 

220 effective_sell_threshold=effective_sell, max_position_weight=signal["max_position_weight"], 

221 ) 

222 history.append(float(probability)) 

223 if len(history) > signal["band_window"]: 

224 del history[0] 

225 if not is_session or symbol in book_members or symbol in book_held: 

226 continue 

227 meta = candidate_metadata_by_ticker.get(symbol, {}) 

228 if meta.get("asset_class") not in classes or not bool(meta.get("trading_eligible", True)): 

229 continue 

230 held = new_weights.get(symbol, 0.0) 

231 if name == "sell": 

232 if held: 

233 new_weights.pop(symbol) 

234 continue 

235 if name != "buy" or kill_switch_locked: 

236 continue # analyzer Priority 1 blocks entries and resizes under the lock 

237 sized = float(weight_fn(symbol=symbol, date=date, base_weight=target, held_weight=held, confidence=confidence, 

238 row=row)) if weight_fn else target 

239 if sized == held: 

240 continue 

241 policy = apply_legacy_sleeve_policy("buy", sized, False, held != 0.0, book_active, gross_used, sleeve_config) 

242 if policy["signal"] != "buy": 

243 continue 

244 wanted = float(policy["target_weight"]) 

245 last = state["last_trade"].get(symbol) 

246 if held == 0.0: 

247 if cooldown_dates > 0 and last is not None and date_index - last < cooldown_dates: 

248 continue 

249 if max_active_positions is not None and len(new_weights) + len(book_held) >= int(max_active_positions): 

250 continue 

251 new_weights[symbol] = wanted 

252 gross_used = float(policy["sleeve_gross_used"]) 

253 elif resize_threshold_weight <= 0.0 or should_scale_position(held, wanted, resize_threshold_weight): 

254 new_weights[symbol] = wanted 

255 cost, turnover = 0.0, 0.0 

256 for symbol in set(new_weights) | set(weights): 

257 delta = new_weights.get(symbol, 0.0) - weights.get(symbol, 0.0) 

258 if delta == 0.0: 

259 continue 

260 turnover += abs(delta) 

261 cost += abs(delta) * (cost_bps + commission_override(symbol)) / 1e4 

262 floor_usd = float((min_commission_usd_by_ticker or {}).get(symbol, 0.0)) 

263 if floor_usd > 0.0: 

264 cost += max(0.0, floor_usd - abs(delta) * pv_for_costs * cost_bps / 1e4) / pv_for_costs 

265 state["last_trade"][symbol] = date_index 

266 if symbol not in new_weights: 

267 state["entry_index"].pop(symbol, None) 

268 state["peak"].pop(symbol, None) 

269 elif symbol not in weights: 

270 state["entry_index"][symbol] = date_index 

271 state["weights"] = new_weights 

272 return cost, turnover 

273 

274 

275def _simulate_rank_book_core( 

276 frame: pd.DataFrame, 

277 *, 

278 prediction_column: str, 

279 forward_return_column: str = "target_return_1d", 

280 ticker_column: str = "ticker", 

281 date_column: str = "date", 

282 top_n: int, 

283 bottom_n: int, 

284 rebalance_every_bars: int, 

285 cost_bps_per_side: float, 

286 commission_bps: float, 

287 gross_exposure: float, 

288 dollar_neutral: bool, 

289 sector_neutral: bool, 

290 sector_by_ticker: dict[str, str] | None = None, 

291 hysteresis_rank_margin: float = 0.0, 

292 max_weight_per_name: float, 

293 min_universe_size: int = 20, 

294 sector_max_net_weight: float = DEFAULT_SECTOR_MAX_NET_WEIGHT, 

295 reapply_sector_cap_after_dollar_neutral: bool = False, 

296 trading_days_per_year: int = 252, 

297 entry_lag_bars: int = 0, 

298 min_commission_usd: float = 0.0, 

299 assumed_portfolio_value_usd: float = 0.0, 

300 impact_model_config: dict[str, Any] | None = None, 

301 candidate_metadata_by_ticker: dict[str, dict] | None = None, 

302 normalize_to_percentile: bool = False, 

303 min_rank_confidence_spread: float = 0.0, 

304 rolling_ic_gate_fn=None, 

305 live_weighting: bool = False, 

306 max_position_weight: float = 0.25, 

307 hold_positions_on_veto: bool = False, 

308 retry_rebalance_after_veto: bool = False, 

309 max_holding_dates: int | None = None, 

310 commission_bps_by_ticker: dict[str, float] | None = None, 

311 entry_veto_column: str | None = None, 

312 hysteresis_anchor_on_formed_book: bool | None = None, 

313 kill_switch_config: dict[str, Any] | None = None, 

314 kill_switch_sticky: bool = False, 

315 member_weight_fn=None, 

316 raw_weights_fn=None, 

317 impact_inputs_fn=None, 

318 min_commission_usd_by_ticker: dict[str, float] | None = None, 

319 rank_group_by_ticker: dict[str, str] | None = None, 

320 sector_relative_rank: bool = False, 

321 partial_adjust_fraction: float = 1.0, 

322 rank_overlay_fn=None, 

323 sector_relative_min_size: int = 3, 

324 sleeve_guard_config: dict[str, Any] | None = None, 

325 venue_listing_dates: dict[str, dict] | None = None, 

326 class_weight_caps: dict[str, dict] | None = None, 

327 per_asset_class_slots: dict[str, tuple[int, int]] | None = None, 

328 rebalance_counter_start: int = 0, 

329 intraday_next_return_column: str | None = None, 

330 decision_overrides: dict[str, str] | None = None, 

331 log_weights: bool = False, 

332 rebalance_session_dates: set[str] | None = None, 

333 resize_threshold_weight: float = 0.0, 

334 trade_cooldown_dates: int = 0, 

335 trailing_stop_pct: float | None = None, 

336 close_column: str = "close", 

337 mid_cycle_member_updates: bool = False, 

338 member_pass_resizes: bool = True, 

339 accrue_skipped_dates: bool = False, 

340 kill_switch_extra_returns: dict[str, float] | None = None, 

341 legacy_component: dict[str, Any] | None = None, 

342 max_active_positions: int | None = None, 

343 cash_sweep: dict[str, Any] | None = None, 

344) -> tuple[RankBookSimulationResult, dict[str, int]]: 

345 """The real implementation, shared by simulate_rank_book() (public, 

346 returns just the result) and capacity_curve() (needs held_days_by_ticker 

347 too, to estimate which held name is the liquidity bottleneck). See 

348 simulate_rank_book()'s docstring for the full parameter/behavior 

349 contract - this function is not itself part of the public API. 

350 

351 Per date, in sorted order: dates with fewer than min_universe_size 

352 eligible (non-NaN prediction AND forward-return) rows are SKIPPED 

353 entirely (no selection, no return accrual) - same convention as 

354 train.py::build_cross_sectional_rank_targets()'s min_universe_size 

355 gate; the book silently carries over across a skipped date, as if it 

356 did not exist for accounting purposes. On a rebalance date (every 

357 rebalance_every_bars-th non-skipped date, first date always rebalances), 

358 predictions are handed to build_rank_based_book() (with hysteresis 

359 against the previous allocation) for top/bottom-N selection, each leg 

360 is equal-weighted to gross_exposure/2, then apply_book_neutrality() 

361 applies the sector/dollar/gross constraints. Cost 

362 (cost_bps_per_side + commission_bps, in bps) is charged on the turnover 

363 of that single rebalance event only - held-and-unchanged positions 

364 between rebalances accrue zero cost, matching main.py's own 

365 hold-until-next-rebalance contract (portfolio/book_construction.py:: 

366 should_rebalance_this_bar()). 

367 

368 entry_lag_bars (V5.2.1, development/Problems.md - default 0, today's 

369 exact behavior): a Daily-resolution market order decided off bar N's 

370 close fills at bar N+1's open, not bar N's close (main.py's own 

371 documented behavior) - this function previously credited a newly- 

372 selected position with that SAME date's forward return, an implicit 

373 zero-lag fill assumption no live system can achieve. When > 0, return 

374 accrual for a given date reads the book state as it stood 

375 entry_lag_bars dates EARLIER (a rolling snapshot history), not the 

376 state as of the current date's own rebalance - so a position selected 

377 today does not start earning return until entry_lag_bars dates from 

378 now, mirroring the live fill delay. Affects ONLY which return a held 

379 weight earns; turnover/cost accounting stays keyed to the unlagged 

380 rebalance transition (cost is incurred at order-submission time, not 

381 fill time). A position held unchanged across the lag window has an 

382 identical snapshot at both indices, so nothing is falsely penalized - 

383 only genuinely CHANGED positions are affected. 

384 

385 min_commission_usd / assumed_portfolio_value_usd (default 0.0 - a 

386 no-op, today's exact bps-of-turnover-only cost model): an 

387 honestly-approximate per-order minimum-commission floor, layered on 

388 top of the existing cost_bps_per_side/commission_bps bps-of-turnover 

389 term. Real broker commissions are often floor-dominated for small 

390 orders (see execution/cost_model.py's own min_commission_usd), which a 

391 pure bps-of-notional model never captures. Requires an assumed NAV to 

392 convert a per-order dollar floor into a return-fraction - a deliberate 

393 approximation (uniform order size, fixed NAV across the whole run), 

394 not a precision claim, same "honestly-approximate" convention 

395 capacity_curve()'s own docstring uses. Only applied on rebalance 

396 dates, charged once per name whose weight actually changed. 

397 

398 AS-LIVE MODE (V5.5.0, Problems.md #128) - the nine trailing keyword 

399 arguments above all default to the idealized behavior this function 

400 always had; `evaluation.live_parity.build_as_live_kwargs()` sets them to 

401 mirror main.py's live path (parity rule, AGENTS.md): 

402 - `normalize_to_percentile`: candidates are ranked by per-date 

403 cross-sectional percentile (what live hands the book), so the 

404 hysteresis margin means percentile points as live; the spread gate 

405 keeps seeing RAW scores (portfolio/book_construction.py contract). 

406 - `min_rank_confidence_spread` / `rolling_ic_gate_fn`: the two live 

407 vetoes (the gate fn maps a date string to evaluate_rolling_ic_gate()'s 

408 result dict, or None for "no opinion"). 

409 - `candidate_metadata_by_ticker`: real `trading_eligible`/`asset_class` 

410 instead of forcing True/None. 

411 - `live_weighting`: build_book_raw_weights() confidence weights instead 

412 of equal weights (both feed apply_book_neutrality()). 

413 - `hold_positions_on_veto`: a vetoed rebalance HOLDS the existing book 

414 (live never liquidates on a veto - should_exit_non_selected_book_symbol) 

415 instead of flattening it; `retry_rebalance_after_veto` re-attempts on 

416 the next date as live does (its has_previous_allocation reads False). 

417 - `max_holding_dates`: live's `exits.max_holding_bars` age exit. 

418 - hysteresis anchors on the last NON-EMPTY book (remember_formed_book()), 

419 which a veto never erases. 

420 

421 V5.7.0 live mechanisms, all off by default (`evaluation.live_parity` builds them from the live config): 

422 - `hysteresis_anchor_on_formed_book` (default: follows `hold_positions_on_veto`) separates the anchor choice from 

423 the hold choice, which the lever attribution had confounded. 

424 - `kill_switch_config` (`phase_v2.risk.kill_switch`): `risk.kill_switch.evaluate_kill_switch` runs every date on the 

425 simulated net returns. A locked rebalance freezes member positions (analyzer Priority 1: entries and resizes become 

426 `reduce_risk`, exits still pass). `kill_switch_sticky=False` mirrors the backtest bypass that clears the lock each 

427 session, so the lock is re-derived every date; True latches the first trip for the rest of the run. 

428 - `member_weight_fn(symbol=, date=, base_weight=, held_weight=, predicted_rank=, row=)` returns the final target 

429 weight of one book member (live sizing chain, liquidity, net-edge gate; hold = return `held_weight`). 

430 - `raw_weights_fn(allocations, date)` replaces `build_book_raw_weights` (HRP). 

431 - `impact_inputs_fn(symbol, date) -> (daily_volatility, adv_usd) | None` charges the Almgren impact per name on its 

432 own traded notional; `min_commission_usd_by_ticker` tops up each traded name to the broker's dollar floor. 

433 

434 V5.8.0, both off by default: 

435 - `rank_group_by_ticker` ({ticker: group}): percentiles are taken within each rank group and the spread gate reads 

436 only the main group's raw scores (main.py with `rank_signal.grouped_normalization`). 

437 - `sleeve_guard_config` (`phase_v2.sleeve_guards.<sleeve>`): `portfolio.sleeve_guard.evaluate_sleeve_guard` on this 

438 book's own simulated net returns (NAV fractions, nav=1.0); while suspended the book is flat and does not rebalance. 

439 - `class_weight_caps` (`portfolio.book_construction.resolve_class_weight_caps`): per-name / class-gross caps applied to the 

440 neutrality-adjusted weights before the member sizing chain, as main.py does (`phase_v2.class_weight_caps`). 

441 - `venue_listing_dates` (`risk.asset_class_router.load_venue_listing_dates`): a pair is not a candidate before its 

442 exchange listing date or inside a suspension (main.py with `venue_listing_guard.enabled`). 

443 

444 V6.0.0, all off by default (todo lead 2, the Lean calibration): 

445 - `per_asset_class_slots` ({class: (top_n, bottom_n)}): the class-neutral book main.py already builds 

446 (`phase_v2.portfolio_book.per_asset_class_slots`), passed to the same `build_rank_based_book`. 

447 - `rebalance_counter_start`: the cadence counter's starting value. main.py counts equity sessions from the start of 

448 its warm-up, so a live run rebalances on a phase the split's first date does not share. 

449 - `intraday_next_return_column` (with `entry_lag_bars=1`): a market order decided on date D fills at the NEXT open, 

450 so the next session's open-to-close move is earned by the NEW weights, not the old ones; the column holds each 

451 row's next-session close/open - 1 (`evaluation.live_parity.add_next_intraday_return`). 

452 - `decision_overrides` ({date: "engaged" | "vetoed" | "locked"}): replays live's gate decisions instead of 

453 computing them (diagnostic: separates the gates' reading from execution). 

454 - `log_weights`: keep the post-rebalance weights of every date (`weights_log`) for a position-level comparison. 

455 - `rebalance_session_dates`: only these dates count toward the cadence and may rebalance or retry (main.py's 

456 `bar_index` advances on equity sessions only; an equity holiday with enough crypto/forex rows was a cadence step 

457 offline and none live). Returns still accrue on every date. 

458 - `resize_threshold_weight`: a held member keeps its weight unless the new target moves it by at least this much 

459 (`risk_controls.should_scale_position`, main.py's `position_scaling.rebalance_threshold_weight`). 

460 - `trade_cooldown_dates`: no new entry or direction flip within this many session dates of the symbol's last trade 

461 (a same-side resize is gated by the threshold alone); exits (the book's rotation, the age exit, the trailing stop) 

462 are exempt, as live's `is_cooldown_exempt` (`trade_cooldown_bars`). 

463 - `trailing_stop_pct`: live's trailing stop on daily closes (`risk_controls.evaluate_non_model_exit`), from the best 

464 close since entry, direction-aware. 

465 

466 V6.1.0, all off by default (rule R-CAL2: each one replicates a main.py mechanism): 

467 - `member_pass_resizes` (V6.4.4, R-CAL5 candidate; default True = V6.1.0 behaviour): False keeps a held member's weight 

468 on the between-rebalance member pass (only entries and exits trade there); BT5's engine made 3 resizes in 3.3 

469 years against the simulator's 32 (ml/evaluation/v644/gate_replica_audit.json). 

470 - `mid_cycle_member_updates`: between rebalances live re-runs every member of the last ENGAGED book through the 

471 member chain on every session (`book_allocations = self._last_book_allocations`), so a member blocked on the 

472 rebalance day (kill-switch lock, net edge, cooldown) or closed by the age exit / trailing stop is entered as soon as 

473 it passes, and a held member is resized when its target moves past the threshold. After a veto there is no book 

474 (live's `_last_book_allocations` is empty) and nothing happens until the next engaged rebalance. 

475 - `accrue_skipped_dates`: a date with too few rows to rank (weekends: crypto only) still earns the held positions' 

476 return, folded into the previous date's return (live marks crypto every calendar day). 

477 - `kill_switch_extra_returns` ({date: NAV return}): P&L outside this simulation (sleeves, crypto outside the book) 

478 that live's kill switch reads, because it watches the whole portfolio value. 

479 - `legacy_component`: the legacy probability signal on non-members (main.py Pass 2 non-member branch), see 

480 `_legacy_step`; its P&L joins the returns and the kill switch and is reported per component. 

481 - `max_active_positions`: live's position count limit (`phase9.portfolio.max_active_positions`): a new entry is not 

482 taken while that many positions (book + legacy) are open; members are filled in conviction order. 

483 Exit costs (age exit, trailing stop, sleeve guard) are now part of the date's cost on a rebalance date too. 

484 

485 V6.2.0, off by default: `cash_sweep` ({"returns_by_date": {date: T-bill ETF return}, "config": 

486 `portfolio.cash_sweep.resolve_cash_sweep_config`, "security_type_by_ticker", "book_gross_cap", "max_short_exposure", 

487 "other_budget", "neutral_budget", "min_commission_usd"}) holds idle NAV in the T-bill ETF as main.py does: sized at the end of each date 

488 from the book and legacy weights just decided and the next date's possible orders (`portfolio.cash_sweep`), filled a 

489 date later, earning the ETF's return as a third component (`per_date_component_returns["cash_sweep"]`). The kill 

490 switch reads the returns without it when `config["exclude_from_risk_controls"]` (live's strategy value ex-sweep). 

491 """ 

492 sector_by_ticker = sector_by_ticker or {} 

493 candidate_metadata_by_ticker = candidate_metadata_by_ticker or {} 

494 as_live = bool(hold_positions_on_veto) 

495 anchor_on_formed_book = as_live if hysteresis_anchor_on_formed_book is None else bool(hysteresis_anchor_on_formed_book) 

496 kill_switch_active = bool(kill_switch_config) and bool((kill_switch_config or {}).get("enabled", False)) 

497 kill_switch_returns: list[float] = [] 

498 kill_switch_latched = False 

499 kill_switch_sharpe_tripped = False # main.py's _kill_switch_rolling_sharpe_tripped (the release band's state) 

500 kill_switch_below_run = 0 # main.py's _kill_switch_rolling_sharpe_below_run (trip_confirm_bars' counter) 

501 kill_switch_previous_drawdown: float | None = None 

502 kill_switch_consecutive_losses = 0 

503 num_kill_switch_locked_dates = 0 

504 num_kill_switch_frozen_decisions = 0 

505 kill_switch_locked_dates: list[str] = [] 

506 pv_for_costs = assumed_portfolio_value_usd if assumed_portfolio_value_usd > 0 else DEFAULT_ASSUMED_PORTFOLIO_VALUE_USD 

507 formed_book: dict[str, BookAllocation] = {} 

508 last_rebalance_vetoed = False 

509 num_vetoed_rebalances = 0 

510 veto_reasons: dict[str, int] = {} 

511 entry_date_index_by_ticker: dict[str, int] = {} 

512 last_trade_index_by_ticker: dict[str, int] = {} 

513 peak_close_by_ticker: dict[str, float] = {} 

514 rebalance_log: list[dict] = [] 

515 weights_log: list[dict] = [] 

516 working = frame.dropna(subset=[prediction_column]).copy() 

517 unique_dates = sorted(working[date_column].unique()) 

518 guard = resolve_sleeve_guard_config(sleeve_guard_config) 

519 guard_suspended_until: int | None = None 

520 num_sleeve_guard_suspended_dates = 0 

521 guard_resume_pending = False 

522 

523 held_weights: dict[str, float] = {} 

524 held_allocations: dict[str, BookAllocation] = {} 

525 held_days_by_ticker: dict[str, int] = {} 

526 # V6.1.0 - live's book between rebalances: the last rebalance's allocations (empty after a veto), their weights before 

527 # the member chain (main.py's _book_target_weights) and the ranks the book was formed on. 

528 active_allocations: dict[str, BookAllocation] = {} 

529 active_base_weights: dict[str, float] = {} 

530 active_ranks: dict[str, float] = {} 

531 legacy_state = _new_legacy_state() if legacy_component else None 

532 book_component_returns: list[float] = [] 

533 legacy_component_returns: list[float] = [] 

534 kill_switch_cumprod = 1.0 

535 kill_switch_peak = 1.0 

536 sweep = cash_sweep or None 

537 sweep_weight = 0.0 

538 sweep_component_returns: list[float] = [] 

539 

540 gross_returns: list[float] = [] 

541 net_returns: list[float] = [] 

542 per_date_used: list = [] 

543 names_long_series: list[int] = [] 

544 names_short_series: list[int] = [] 

545 gross_exposure_series: list[float] = [] 

546 net_exposure_series: list[float] = [] 

547 total_turnover = 0.0 

548 total_cost_return = 0.0 

549 num_rebalances = 0 

550 rebalance_counter = int(rebalance_counter_start) 

551 # V5.2.1 - one held_weights snapshot per processed date, appended AFTER 

552 # that date's own rebalance (if any) - see entry_lag_bars's docstring. 

553 weights_history: list[dict[str, float]] = [] 

554 

555 net_cumprod = 1.0 

556 gross_cumprod = 1.0 

557 net_running_peak = 1.0 

558 net_max_drawdown = 0.0 

559 

560 def _commission_override_delta(symbol: str) -> float: 

561 # Per-ticker fee (e.g. a crypto exchange percentage) replaces the generic commission for that 

562 # ticker; 0.0 for everything else, so books without overrides cost exactly what they always did. 

563 if not commission_bps_by_ticker or symbol not in commission_bps_by_ticker: 

564 return 0.0 

565 return float(commission_bps_by_ticker[symbol]) - commission_bps 

566 

567 for date in unique_dates: 

568 date_frame = working[working[date_column] == date] 

569 eligible = date_frame.dropna(subset=[forward_return_column]) 

570 if len(eligible) < min_universe_size: 

571 if accrue_skipped_dates and net_returns: 

572 returns_today = dict(zip(eligible[ticker_column].astype(str), eligible[forward_return_column], strict=False)) 

573 book_extra = sum(weight * float(returns_today.get(symbol, 0.0)) for symbol, weight in (weights_history[-1] if weights_history else {}).items()) 

574 legacy_extra = _legacy_mark(legacy_state, returns_today) if legacy_state is not None else 0.0 

575 extra = book_extra + legacy_extra 

576 if extra: 

577 previous = net_returns[-1] 

578 net_cumprod = net_cumprod / (1.0 + previous) * (1.0 + previous + extra) 

579 gross_cumprod = gross_cumprod / (1.0 + gross_returns[-1]) * (1.0 + gross_returns[-1] + extra) 

580 net_returns[-1] = previous + extra 

581 gross_returns[-1] += extra 

582 book_component_returns[-1] += book_extra 

583 legacy_component_returns[-1] += legacy_extra 

584 net_running_peak = max(net_running_peak, net_cumprod) 

585 net_max_drawdown = min(net_max_drawdown, net_cumprod / net_running_peak - 1.0) 

586 if kill_switch_active and kill_switch_returns: 

587 previous_portfolio = kill_switch_returns[-1] 

588 kill_switch_cumprod = kill_switch_cumprod / (1.0 + previous_portfolio) * (1.0 + previous_portfolio + extra) 

589 kill_switch_peak = max(kill_switch_peak, kill_switch_cumprod) 

590 kill_switch_previous_drawdown = kill_switch_cumprod / kill_switch_peak - 1.0 

591 kill_switch_returns[-1] = previous_portfolio + extra 

592 continue 

593 

594 is_session = rebalance_session_dates is None or str(date) in rebalance_session_dates 

595 is_rebalance = is_session and (rebalance_counter % max(1, rebalance_every_bars)) == 0 

596 if retry_rebalance_after_veto and last_rebalance_vetoed and is_session: 

597 is_rebalance = True 

598 if decision_overrides is not None: 

599 is_rebalance = str(date) in decision_overrides # replay: live's own rebalance dates 

600 if is_session: 

601 rebalance_counter += 1 

602 cost_this_date = 0.0 

603 date_returns = dict(zip(eligible[ticker_column], eligible[forward_return_column], strict=False)) 

604 

605 kill_switch_locked = False 

606 if kill_switch_active: 

607 # main.py's _refresh_risk_state() runs at the start of the tick on the portfolio value that already includes 

608 # today's price move on yesterday's positions; with entry_lag_bars > 0 that move is known before deciding. 

609 window = list(kill_switch_returns) 

610 today_return = None 

611 if entry_lag_bars > 0: 

612 lag_index = len(weights_history) - entry_lag_bars 

613 lagged_weights = weights_history[lag_index] if lag_index >= 0 else {} 

614 today_return = sum(weight * float(date_returns.get(symbol, 0.0)) for symbol, weight in lagged_weights.items()) 

615 if legacy_state is not None: 

616 today_return += _legacy_lagged_return(legacy_state, date_returns, entry_lag_bars) 

617 today_return += float((kill_switch_extra_returns or {}).get(str(date), 0.0)) 

618 window.append(today_return) 

619 drawdown_velocity = None 

620 if kill_switch_previous_drawdown is not None: 

621 value_now = kill_switch_cumprod * (1.0 + (today_return or 0.0)) 

622 drawdown_now = value_now / max(kill_switch_peak, value_now) - 1.0 

623 drawdown_velocity = abs(drawdown_now) - abs(kill_switch_previous_drawdown) 

624 decision = evaluate_kill_switch( 

625 { 

626 "recent_bar_returns": window[-_KILL_SWITCH_HISTORY_MAXLEN:], 

627 "drawdown_velocity_pct_per_bar": drawdown_velocity, 

628 "live_rank_ic": None, 

629 "consecutive_losses": kill_switch_consecutive_losses, 

630 "slippage_divergence_bps": None, 

631 "model_age_days": None, 

632 "reconciliation_breach": False, 

633 "rolling_sharpe_tripped_last_bar": kill_switch_sharpe_tripped, 

634 "rolling_sharpe_below_run_last_bar": kill_switch_below_run, 

635 }, 

636 kill_switch_config, 

637 ) 

638 kill_switch_sharpe_tripped = decision.rolling_sharpe_tripped 

639 kill_switch_below_run = decision.rolling_sharpe_below_run 

640 if decision.tripped and kill_switch_sticky: 

641 kill_switch_latched = True 

642 kill_switch_locked = decision.tripped or kill_switch_latched 

643 if kill_switch_locked: 

644 num_kill_switch_locked_dates += 1 

645 kill_switch_locked_dates.append(str(date)) 

646 

647 # V5.5.0 - live's `exits.max_holding_bars` age exit (as-live only). 

648 if max_holding_dates is not None and held_weights: 

649 date_index = rebalance_counter - 1 

650 expired = [ 

651 symbol 

652 for symbol in held_weights 

653 if date_index - entry_date_index_by_ticker.get(symbol, date_index) >= max_holding_dates 

654 ] 

655 if expired: 

656 exit_cost = ( 

657 sum(abs(held_weights[symbol]) for symbol in expired) * (cost_bps_per_side + commission_bps) / 1e4 

658 + sum(abs(held_weights[symbol]) * _commission_override_delta(symbol) for symbol in expired) / 1e4 

659 ) 

660 cost_this_date += exit_cost 

661 total_cost_return += exit_cost 

662 total_turnover += sum(abs(held_weights[symbol]) for symbol in expired) 

663 held_weights = {symbol: weight for symbol, weight in held_weights.items() if symbol not in expired} 

664 held_allocations = { 

665 symbol: allocation for symbol, allocation in held_allocations.items() if symbol not in expired 

666 } 

667 for symbol in expired: 

668 entry_date_index_by_ticker.pop(symbol, None) 

669 peak_close_by_ticker.pop(symbol, None) 

670 last_trade_index_by_ticker[symbol] = date_index 

671 

672 if trailing_stop_pct is not None and held_weights and close_column in eligible.columns: 

673 date_index = rebalance_counter - 1 

674 closes_today = dict(zip(eligible[ticker_column].astype(str), eligible[close_column], strict=False)) 

675 stopped = [] 

676 for symbol, weight in held_weights.items(): 

677 close = closes_today.get(symbol) 

678 if close is None or close != close or close <= 0.0: 

679 continue 

680 peak = peak_close_by_ticker.get(symbol) 

681 reason = evaluate_non_model_exit( 

682 date_index, True, 10**9, float(trailing_stop_pct), entry_date_index_by_ticker.get(symbol, date_index), 

683 peak, "long" if weight > 0 else "short", float(close), 

684 ) 

685 if reason == "trailing_stop_triggered": 

686 stopped.append(symbol) 

687 elif peak is None or (weight > 0 and close > peak) or (weight < 0 and close < peak): 

688 peak_close_by_ticker[symbol] = float(close) 

689 if stopped: 

690 exit_cost = ( 

691 sum(abs(held_weights[symbol]) for symbol in stopped) * (cost_bps_per_side + commission_bps) / 1e4 

692 + sum(abs(held_weights[symbol]) * _commission_override_delta(symbol) for symbol in stopped) / 1e4 

693 ) 

694 cost_this_date += exit_cost 

695 total_cost_return += exit_cost 

696 total_turnover += sum(abs(held_weights[symbol]) for symbol in stopped) 

697 held_weights = {symbol: weight for symbol, weight in held_weights.items() if symbol not in stopped} 

698 held_allocations = {symbol: allocation for symbol, allocation in held_allocations.items() if symbol not in stopped} 

699 for symbol in stopped: 

700 entry_date_index_by_ticker.pop(symbol, None) 

701 peak_close_by_ticker.pop(symbol, None) 

702 last_trade_index_by_ticker[symbol] = date_index 

703 

704 if guard.enabled: 

705 guard_decision = evaluate_sleeve_guard( 

706 net_returns, 1.0, guard, current_bar=rebalance_counter - 1, suspended_until_bar=guard_suspended_until 

707 ) 

708 guard_suspended_until = guard_decision["suspended_until_bar"] 

709 if not guard_decision["active"]: 

710 num_sleeve_guard_suspended_dates += 1 

711 if held_weights: 

712 flattened = sum(abs(weight) for weight in held_weights.values()) 

713 exit_cost = flattened * (cost_bps_per_side + commission_bps) / 1e4 + sum( 

714 abs(weight) * _commission_override_delta(symbol) for symbol, weight in held_weights.items() 

715 ) / 1e4 

716 cost_this_date += exit_cost 

717 total_cost_return += exit_cost 

718 total_turnover += flattened 

719 held_weights = {} 

720 held_allocations = {} 

721 entry_date_index_by_ticker.clear() 

722 is_rebalance = False 

723 active_allocations, active_base_weights, active_ranks = {}, {}, {} 

724 guard_resume_pending = True 

725 elif guard_resume_pending: 

726 is_rebalance = True # re-form the book on the first date the guard lets it trade again 

727 guard_resume_pending = False 

728 

729 mid_cycle = bool(mid_cycle_member_updates and not is_rebalance and is_session and active_allocations) 

730 if is_rebalance or mid_cycle: 

731 if is_rebalance: 

732 raw_scores_by_ticker = { 

733 str(ticker): float(rank) for ticker, rank in zip(eligible[ticker_column], eligible[prediction_column], strict=False) 

734 } 

735 candidate_ranks = ( 

736 grouped_cross_sectional_rank_scores( 

737 raw_scores_by_ticker, rank_group_by_ticker, 

738 sector_by_ticker if sector_relative_rank else None, sector_relative_min_size, 

739 ) 

740 if normalize_to_percentile 

741 else raw_scores_by_ticker 

742 ) 

743 if rank_overlay_fn is not None and normalize_to_percentile: 

744 # V6.4.0 (lead L2): live applies portfolio.direction_overlay to the normalised ranks, after the percentile 

745 # and before the book; the spread gate below keeps reading the raw scores 

746 candidate_ranks = rank_overlay_fn(str(date), candidate_ranks) 

747 spread_scores = raw_scores_by_ticker 

748 if rank_group_by_ticker: 

749 spread_scores = { 

750 ticker: score 

751 for ticker, score in raw_scores_by_ticker.items() 

752 if rank_group_by_ticker.get(ticker, MAIN_RANK_GROUP) == MAIN_RANK_GROUP 

753 } 

754 book_candidates = { 

755 ticker: { 

756 "predicted_rank_20d": float(rank), 

757 "trading_eligible": bool(candidate_metadata_by_ticker.get(ticker, {}).get("trading_eligible", True)) 

758 and asset_listed_on_venue(ticker, str(date), venue_listing_dates), 

759 "asset_class": candidate_metadata_by_ticker.get(ticker, {}).get("asset_class"), 

760 } 

761 for ticker, rank in candidate_ranks.items() 

762 } 

763 gate_result = rolling_ic_gate_fn(str(date)) if rolling_ic_gate_fn is not None else None 

764 override = (decision_overrides or {}).get(str(date)) 

765 if override is not None: 

766 # a locked date still forms the book; the kill switch then freezes its entries and resizes 

767 engaged = override in ("engaged", "locked") 

768 gate_result = {"engaged": True, "reason": None} if engaged else {"engaged": False, "reason": "replayed_veto"} 

769 kill_switch_locked = override == "locked" 

770 veto_reason_out: dict[str, str] = {} 

771 # min_rank_confidence_spread defaults to 0.0 DELIBERATELY (as-live 

772 # mode passes the live gate value instead), not an 

773 # oversight: this simulator measures book QUALITY (what would 

774 # this rank prediction have earned, net of costs) uncapped by 

775 # the live entry gate's conviction filter - those are two 

776 # different questions. Do not "fix" this into reading 

777 # phase_v2.portfolio_book.min_rank_confidence_spread to try to 

778 # mirror live engagement; that number is calibrated 

779 # specifically for the RAW pre-normalization score scale 

780 # (aq evaluate --calibrate-book-spread, portfolio/rank_signal.py), 

781 # which this function's `prediction_column` is not guaranteed 

782 # to be (callers may pass an already-normalized column). A 

783 # healthy net_sharpe here is evidence the RANKING has value, 

784 # never evidence the live gate will engage on any given day. 

785 allocations = build_rank_based_book( 

786 book_candidates, 

787 top_n=top_n, 

788 bottom_n=bottom_n, 

789 min_rank_confidence_spread=0.0 if override in ("engaged", "locked") else min_rank_confidence_spread, 

790 per_asset_class_slots=per_asset_class_slots or None, 

791 previous_allocations=(formed_book if anchor_on_formed_book else held_allocations) or None, 

792 hysteresis_rank_margin=hysteresis_rank_margin, 

793 spread_check_ranks=spread_scores if normalize_to_percentile else None, 

794 rolling_ic_gate_result=gate_result, 

795 veto_reason_out=veto_reason_out, 

796 ) 

797 last_rebalance_vetoed = not allocations 

798 if not allocations: 

799 num_vetoed_rebalances += 1 

800 veto_key = veto_reason_out.get("reason", "empty_book") 

801 veto_reasons[veto_key] = veto_reasons.get(veto_key, 0) + 1 

802 formed_book = remember_formed_book(formed_book, allocations) 

803 rebalance_log.append( 

804 {"date": str(date), "engaged": bool(allocations), "reason": None if allocations else veto_reason_out.get("reason", "empty_book"), 

805 "locked": bool(kill_switch_locked)} 

806 ) 

807 

808 if not allocations and hold_positions_on_veto: 

809 # Live parity: a vetoed rebalance leaves the existing book 

810 # untouched (no turnover, no cost, no new positions). 

811 new_weights = dict(held_weights) 

812 elif allocations: 

813 long_symbols = [symbol for symbol, allocation in allocations.items() if allocation.role == "long"] 

814 short_symbols = [symbol for symbol, allocation in allocations.items() if allocation.role == "short"] 

815 raw_weights: dict[str, float] = {} 

816 if raw_weights_fn is not None: 

817 raw_weights = raw_weights_fn(allocations, str(date)) 

818 elif live_weighting: 

819 raw_weights = build_book_raw_weights(allocations, max_position_weight) 

820 else: 

821 if long_symbols: 

822 per_name = (gross_exposure / 2.0) / len(long_symbols) 

823 raw_weights.update(dict.fromkeys(long_symbols, per_name)) 

824 if short_symbols: 

825 per_name = (gross_exposure / 2.0) / len(short_symbols) 

826 raw_weights.update(dict.fromkeys(short_symbols, -per_name)) 

827 

828 new_weights, _diagnostics = apply_book_neutrality( 

829 raw_weights, 

830 sector_by_symbol=sector_by_ticker, 

831 dollar_neutral=dollar_neutral, 

832 sector_neutral=sector_neutral, 

833 gross_exposure_cap=gross_exposure, 

834 max_weight_per_name=max_weight_per_name, 

835 sector_max_net_weight=sector_max_net_weight, 

836 reapply_sector_cap_after_dollar_neutral=reapply_sector_cap_after_dollar_neutral, 

837 ) 

838 if class_weight_caps: 

839 new_weights = apply_class_weight_caps( 

840 new_weights, 

841 {ticker: meta.get("asset_class") for ticker, meta in candidate_metadata_by_ticker.items()}, 

842 class_weight_caps, 

843 ) 

844 held_allocations = { 

845 symbol: replace(allocation, target_weight=new_weights.get(symbol, 0.0)) 

846 for symbol, allocation in allocations.items() 

847 } 

848 else: 

849 new_weights = {} 

850 held_allocations = {} 

851 active_allocations = dict(allocations) if allocations else {} 

852 active_base_weights = dict(new_weights) if allocations else {} 

853 active_ranks = {symbol: candidate_ranks.get(symbol) for symbol in allocations} if allocations else {} 

854 else: 

855 # live between rebalances: the same members, the same pre-chain weights, today's rows 

856 allocations = active_allocations 

857 candidate_ranks = active_ranks 

858 new_weights = dict(active_base_weights) 

859 override = None 

860 

861 if member_weight_fn is not None and new_weights and allocations: 

862 rows_by_ticker = eligible.set_index(ticker_column).to_dict("index") 

863 adjusted_weights = { 

864 symbol: float( 

865 member_weight_fn( 

866 symbol=symbol, 

867 date=str(date), 

868 base_weight=weight, 

869 held_weight=held_weights.get(symbol, 0.0), 

870 predicted_rank=candidate_ranks.get(symbol), 

871 row=rows_by_ticker.get(symbol, {}), 

872 ) 

873 ) 

874 for symbol, weight in new_weights.items() 

875 } 

876 new_weights = {symbol: weight for symbol, weight in adjusted_weights.items() if weight != 0.0} 

877 held_allocations = {symbol: allocation for symbol, allocation in held_allocations.items() if symbol in new_weights} 

878 

879 if entry_veto_column and entry_veto_column in eligible.columns and new_weights: 

880 # Live's analyzer Priority 3 (elevated topology volatility) turns a NEW book entry into 

881 # reduce_risk; positions already held are not force-closed by it. 

882 vetoed_entries = { 

883 str(ticker) 

884 for ticker, flag in zip(eligible[ticker_column], eligible[entry_veto_column], strict=False) 

885 if flag == flag and float(flag) > 0.5 

886 } 

887 new_weights = { 

888 symbol: weight 

889 for symbol, weight in new_weights.items() 

890 if symbol in held_weights or symbol not in vetoed_entries 

891 } 

892 held_allocations = {symbol: allocation for symbol, allocation in held_allocations.items() if symbol in new_weights} 

893 

894 if kill_switch_locked and new_weights: 

895 # analyzer Priority 1: with the lock on, a member's entry or resize becomes reduce_risk (no trade); 

896 # only the exits (names the book dropped, handled by the missing keys) go through. 

897 frozen = {symbol: held_weights[symbol] for symbol in new_weights if symbol in held_weights} 

898 if allocations and is_rebalance: 

899 num_kill_switch_frozen_decisions += len(new_weights) 

900 new_weights = frozen 

901 held_allocations = {symbol: allocation for symbol, allocation in held_allocations.items() if symbol in new_weights} 

902 

903 if (resize_threshold_weight > 0.0 or trade_cooldown_dates > 0 or (mid_cycle and not member_pass_resizes)) and new_weights: 

904 date_index = rebalance_counter - 1 

905 adjusted = dict(new_weights) 

906 for symbol, target in new_weights.items(): 

907 held = held_weights.get(symbol, 0.0) 

908 if target == held: 

909 continue 

910 same_side_hold = held != 0.0 and (held > 0) == (target > 0) 

911 if same_side_hold and mid_cycle and not member_pass_resizes: 

912 adjusted[symbol] = held 

913 continue 

914 if same_side_hold and resize_threshold_weight > 0.0 and not should_scale_position(held, target, resize_threshold_weight): 

915 adjusted[symbol] = held # live: a trivial resize is not traded 

916 continue 

917 last = last_trade_index_by_ticker.get(symbol) 

918 if not same_side_hold and trade_cooldown_dates > 0 and last is not None and date_index - last < trade_cooldown_dates: 

919 adjusted[symbol] = held # live: inside the cooldown a new entry or a flip is not traded 

920 new_weights = {symbol: weight for symbol, weight in adjusted.items() if weight != 0.0} 

921 held_allocations = {symbol: allocation for symbol, allocation in held_allocations.items() if symbol in new_weights} 

922 

923 if max_active_positions is not None and new_weights: 

924 new_weights = _cap_new_entries( 

925 new_weights, held_weights, candidate_ranks, 

926 int(max_active_positions) - (len(legacy_state["weights"]) if legacy_state is not None else 0), 

927 ) 

928 held_allocations = {symbol: allocation for symbol, allocation in held_allocations.items() if symbol in new_weights} 

929 

930 if partial_adjust_fraction < 1.0 and is_rebalance and new_weights != held_weights: 

931 new_weights = partial_adjust_weights(held_weights, new_weights, partial_adjust_fraction) 

932 held_allocations = {symbol: allocation for symbol, allocation in held_allocations.items() if symbol in new_weights} 

933 

934 for symbol in set(new_weights) | set(held_weights): 

935 if new_weights.get(symbol, 0.0) != held_weights.get(symbol, 0.0): 

936 last_trade_index_by_ticker[symbol] = rebalance_counter - 1 

937 if symbol not in new_weights: 

938 peak_close_by_ticker.pop(symbol, None) 

939 for symbol in new_weights: 

940 if symbol not in held_weights: 

941 entry_date_index_by_ticker[symbol] = rebalance_counter - 1 

942 for symbol in list(entry_date_index_by_ticker): 

943 if symbol not in new_weights: 

944 entry_date_index_by_ticker.pop(symbol, None) 

945 

946 all_symbols = set(new_weights) | set(held_weights) 

947 deltas_by_symbol = { 

948 symbol: new_weights.get(symbol, 0.0) - held_weights.get(symbol, 0.0) for symbol in all_symbols 

949 } 

950 turnover_this_rebalance = sum(abs(delta) for delta in deltas_by_symbol.values()) 

951 total_turnover += turnover_this_rebalance 

952 turnover_cost = turnover_this_rebalance * (cost_bps_per_side + commission_bps) / 1e4 

953 turnover_cost += sum(abs(delta) * _commission_override_delta(symbol) for symbol, delta in deltas_by_symbol.items()) / 1e4 

954 # V5.2.1 (development/Problems.md) - honestly-approximate 

955 # per-order minimum-commission floor, see this function's own 

956 # docstring. No-op (0.0) unless both inputs are configured. 

957 if min_commission_usd > 0.0 and assumed_portfolio_value_usd > 0.0: 

958 names_traded = sum(1 for delta in deltas_by_symbol.values() if delta != 0.0) 

959 turnover_cost += names_traded * min_commission_usd / assumed_portfolio_value_usd 

960 cost_this_date += turnover_cost 

961 total_cost_return += turnover_cost 

962 if min_commission_usd_by_ticker: 

963 # Top each traded name up to the broker's dollar floor: the rate leg is already in commission_bps*. 

964 floor_topup = 0.0 

965 for symbol, delta in deltas_by_symbol.items(): 

966 floor_usd = float(min_commission_usd_by_ticker.get(symbol, 0.0)) 

967 if floor_usd <= 0.0 or delta == 0.0: 

968 continue 

969 rate_bps = float(commission_bps_by_ticker.get(symbol, commission_bps)) if commission_bps_by_ticker else commission_bps 

970 rate_usd = abs(delta) * pv_for_costs * rate_bps / 1e4 

971 floor_topup += max(0.0, floor_usd - rate_usd) / pv_for_costs 

972 cost_this_date += floor_topup 

973 total_cost_return += floor_topup 

974 

975 # V5.4.2 - Almgren-style sqrt impact (optional, off by default). Impact is a cost RATE on the notional 

976 # traded, so the NAV cost is rate x |delta weight|; V5.7.0 fixed the old date-level estimate, which 

977 # charged the rate itself as a fraction of NAV on a $1M book. 

978 if impact_model_config and impact_model_config.get("enabled", False): 

979 from evaluation.impact_model import compute_sqrt_impact_bps 

980 

981 eta = float(impact_model_config.get("eta", 0.5)) 

982 impact_cost = 0.0 

983 if impact_inputs_fn is not None: 

984 for symbol, delta in deltas_by_symbol.items(): 

985 inputs = impact_inputs_fn(symbol, str(date)) 

986 if inputs is None or delta == 0.0: 

987 continue 

988 symbol_vol, symbol_adv = inputs 

989 impact_cost += abs(delta) * compute_sqrt_impact_bps( 

990 trade_size_fraction=abs(delta), 

991 daily_volatility=float(symbol_vol), 

992 avg_daily_dollar_volume=float(symbol_adv), 

993 portfolio_value=pv_for_costs, 

994 eta=eta, 

995 ) / 1e4 

996 else: 

997 impact_bps = compute_sqrt_impact_bps( 

998 trade_size_fraction=turnover_this_rebalance, 

999 daily_volatility=float(impact_model_config.get("daily_volatility", 0.02)), 

1000 avg_daily_dollar_volume=float(impact_model_config.get("avg_daily_dollar_volume", 50_000_000)), 

1001 portfolio_value=pv_for_costs, 

1002 eta=eta, 

1003 ) 

1004 impact_cost = turnover_this_rebalance * impact_bps / 1e4 

1005 cost_this_date += impact_cost 

1006 total_cost_return += impact_cost 

1007 

1008 if is_rebalance: 

1009 num_rebalances += 1 

1010 held_weights = new_weights 

1011 

1012 legacy_net_return = 0.0 

1013 if legacy_state is not None: 

1014 legacy_cost, legacy_turnover = _legacy_step( 

1015 legacy_state, legacy_component, eligible=eligible, date=str(date), date_index=rebalance_counter - 1, 

1016 is_session=is_session, ticker_column=ticker_column, close_column=close_column, 

1017 book_members=set(active_allocations) | set(formed_book), book_held=held_weights, 

1018 book_active=bool(active_allocations), kill_switch_locked=kill_switch_locked, 

1019 candidate_metadata_by_ticker=candidate_metadata_by_ticker, 

1020 cost_bps=cost_bps_per_side + commission_bps, commission_override=_commission_override_delta, 

1021 min_commission_usd_by_ticker=min_commission_usd_by_ticker, pv_for_costs=pv_for_costs, 

1022 max_active_positions=max_active_positions, cooldown_dates=trade_cooldown_dates, 

1023 resize_threshold_weight=resize_threshold_weight, 

1024 ) 

1025 total_turnover += legacy_turnover 

1026 total_cost_return += legacy_cost 

1027 legacy_net_return = _legacy_lagged_return(legacy_state, date_returns, entry_lag_bars, record=True) - legacy_cost 

1028 if intraday_next_return_column and entry_lag_bars == 1 and intraday_next_return_column in eligible.columns: 

1029 legacy_net_return += _legacy_intraday(legacy_state, eligible, ticker_column, intraday_next_return_column) 

1030 

1031 for symbol in held_weights: 

1032 held_days_by_ticker[symbol] = held_days_by_ticker.get(symbol, 0) + 1 

1033 names_long_series.append(sum(1 for weight in held_weights.values() if weight > 0.0)) 

1034 names_short_series.append(sum(1 for weight in held_weights.values() if weight < 0.0)) 

1035 

1036 # V5.2.1 - entry_lag_bars=0 (default) uses held_weights directly, 

1037 # byte-identical to before this parameter existed. > 0 looks back 

1038 # into weights_history instead - see this function's own docstring. 

1039 if entry_lag_bars > 0: 

1040 lag_index = len(weights_history) - entry_lag_bars 

1041 effective_weights = weights_history[lag_index] if lag_index >= 0 else {} 

1042 else: 

1043 effective_weights = held_weights 

1044 bar_return = sum( 

1045 weight * float(date_returns.get(symbol, 0.0)) for symbol, weight in effective_weights.items() 

1046 ) 

1047 if intraday_next_return_column and entry_lag_bars == 1 and intraday_next_return_column in eligible.columns: 

1048 # The order filled at the next open: the next session's open-to-close move belongs to the new weights. 

1049 changed = { 

1050 symbol: held_weights.get(symbol, 0.0) - effective_weights.get(symbol, 0.0) 

1051 for symbol in set(held_weights) | set(effective_weights) 

1052 } 

1053 intraday = dict(zip(eligible[ticker_column], eligible[intraday_next_return_column], strict=False)) 

1054 bar_return += sum( 

1055 delta * float(intraday.get(symbol, 0.0) or 0.0) 

1056 for symbol, delta in changed.items() 

1057 if delta != 0.0 and intraday.get(symbol) == intraday.get(symbol) 

1058 ) 

1059 net_return = bar_return - cost_this_date 

1060 book_component_returns.append(net_return) 

1061 legacy_component_returns.append(legacy_net_return) 

1062 if legacy_state is not None: 

1063 net_return += legacy_net_return 

1064 bar_return += legacy_net_return 

1065 strategy_net_return = net_return 

1066 if sweep is not None: 

1067 sweep_net, sweep_weight = _cash_sweep_step( 

1068 sweep, sweep_weight, date=str(date), is_session=is_session, book_weights=held_weights, 

1069 legacy_weights=legacy_state["weights"] if legacy_state is not None else {}, 

1070 rebalance_next=(not active_allocations) or (rebalance_counter % max(1, rebalance_every_bars)) == 0, 

1071 formed_weights=active_base_weights, pv_for_costs=pv_for_costs, 

1072 ) 

1073 sweep_component_returns.append(sweep_net) 

1074 net_return += sweep_net 

1075 bar_return += sweep_net 

1076 total_cost_return += sweep.get("_last_cost", 0.0) 

1077 if not sweep["config"]["exclude_from_risk_controls"]: 

1078 strategy_net_return = net_return 

1079 gross_exposure_series.append(sum(abs(weight) for weight in effective_weights.values())) 

1080 net_exposure_series.append(sum(effective_weights.values())) 

1081 

1082 gross_returns.append(bar_return) 

1083 net_returns.append(net_return) 

1084 per_date_used.append(str(date)) 

1085 weights_history.append(dict(held_weights)) 

1086 if log_weights: 

1087 weights_log.append(dict(held_weights)) 

1088 gross_cumprod *= 1.0 + bar_return 

1089 net_cumprod *= 1.0 + net_return 

1090 net_running_peak = max(net_running_peak, net_cumprod) 

1091 net_max_drawdown = min(net_max_drawdown, net_cumprod / net_running_peak - 1.0) 

1092 if kill_switch_active: 

1093 # live's kill switch watches the whole portfolio: this simulation plus anything modelled outside it 

1094 portfolio_return = strategy_net_return + float((kill_switch_extra_returns or {}).get(str(date), 0.0)) 

1095 kill_switch_returns.append(portfolio_return) 

1096 kill_switch_cumprod *= 1.0 + portfolio_return 

1097 kill_switch_peak = max(kill_switch_peak, kill_switch_cumprod) 

1098 kill_switch_previous_drawdown = kill_switch_cumprod / kill_switch_peak - 1.0 

1099 kill_switch_consecutive_losses = kill_switch_consecutive_losses + 1 if portfolio_return < 0.0 else 0 

1100 

1101 if not per_date_used: 

1102 return _empty_result(trading_days_per_year), held_days_by_ticker 

1103 

1104 num_dates_used = len(per_date_used) 

1105 years = num_dates_used / trading_days_per_year 

1106 gross_array = np.asarray(gross_returns, dtype=float) 

1107 net_array = np.asarray(net_returns, dtype=float) 

1108 

1109 result = RankBookSimulationResult( 

1110 gross_sharpe=_annualized_sharpe(gross_array, trading_days_per_year), 

1111 net_sharpe=_annualized_sharpe(net_array, trading_days_per_year), 

1112 gross_total_return=float(gross_cumprod - 1.0), 

1113 net_total_return=float(net_cumprod - 1.0), 

1114 net_max_drawdown=float(net_max_drawdown), 

1115 annualized_turnover=float(total_turnover / years) if years > 0 else 0.0, 

1116 cost_drag_annual_bps=float(total_cost_return / years * 10_000.0) if years > 0 else 0.0, 

1117 num_rebalances=num_rebalances, 

1118 num_dates_used=num_dates_used, 

1119 mean_names_long=float(np.mean(names_long_series)) if names_long_series else 0.0, 

1120 mean_names_short=float(np.mean(names_short_series)) if names_short_series else 0.0, 

1121 per_date_net_return=[float(value) for value in net_returns], 

1122 per_date=per_date_used, 

1123 num_vetoed_rebalances=num_vetoed_rebalances, 

1124 veto_reasons=dict(sorted(veto_reasons.items())), 

1125 num_kill_switch_locked_dates=num_kill_switch_locked_dates, 

1126 num_kill_switch_frozen_decisions=num_kill_switch_frozen_decisions, 

1127 kill_switch_locked_date_list=kill_switch_locked_dates, 

1128 num_sleeve_guard_suspended_dates=num_sleeve_guard_suspended_dates, 

1129 mean_gross_exposure=float(np.mean(gross_exposure_series)) if gross_exposure_series else 0.0, 

1130 mean_net_exposure=float(np.mean(net_exposure_series)) if net_exposure_series else 0.0, 

1131 rebalance_log=rebalance_log, 

1132 weights_log=weights_log, 

1133 per_date_component_returns=( 

1134 ({"main_book": dict(zip(per_date_used, book_component_returns, strict=False)), "legacy": dict(zip(per_date_used, legacy_component_returns, strict=False))} 

1135 if legacy_state is not None else {}) 

1136 | ({"cash_sweep": dict(zip(per_date_used, sweep_component_returns, strict=False))} if sweep is not None else {}) 

1137 ), 

1138 ) 

1139 return result, held_days_by_ticker 

1140 

1141 

1142def _cash_sweep_step( 

1143 sweep: dict[str, Any], weight: float, *, date: str, is_session: bool, book_weights: dict[str, float], 

1144 legacy_weights: dict[str, float], rebalance_next: bool, formed_weights: dict[str, float], pv_for_costs: float, 

1145) -> tuple[float, float]: 

1146 """One date of the T-bill sweep: yesterday's sweep weight earns today's ETF return (it filled at today's open), then 

1147 the new target is sized from the weights just decided (main.py sizes it after Pass 2 from holdings plus open 

1148 orders) and traded when it moved by `min_trade_weight`. Returns (net return, new weight); the cost is left in 

1149 `sweep["_last_cost"]` for the run's cost total.""" 

1150 from portfolio.cash_sweep import cash_sweep_target_weight, margin_fraction, strategy_reserve, sweep_order_needed 

1151 

1152 config = sweep["config"] 

1153 earned = weight * float(sweep["returns_by_date"].get(date, 0.0) or 0.0) 

1154 sweep["_last_cost"] = 0.0 

1155 if not is_session: 

1156 return earned, weight 

1157 types = sweep.get("security_type_by_ticker") or {} 

1158 long_weight = short_weight = 0.0 

1159 margin_inputs = [] 

1160 for symbol, value in list(book_weights.items()) + list(legacy_weights.items()): 

1161 if value > 0.0: 

1162 long_weight += value 

1163 else: 

1164 short_weight -= value 

1165 margin_inputs.append((types.get(symbol, "equity"), value)) 

1166 book_long = sum(value for value in book_weights.values() if value > 0.0) 

1167 book_short = -sum(value for value in book_weights.values() if value < 0.0) 

1168 reserve = strategy_reserve( 

1169 rebalance_next=rebalance_next, book_gross_cap=float(sweep.get("book_gross_cap", 1.0)), 

1170 max_short_exposure=float(sweep.get("max_short_exposure", 0.3)), 

1171 formed_long=sum(value for value in formed_weights.values() if value > 0.0), 

1172 formed_short=-sum(value for value in formed_weights.values() if value < 0.0), 

1173 book_long=book_long, book_short=book_short, other_budget_remaining=float(sweep.get("other_budget", 0.0)), 

1174 neutral_budget=float(sweep.get("neutral_budget", 0.0)), 

1175 ) 

1176 target = cash_sweep_target_weight( 

1177 long_weight=long_weight, short_weight=short_weight, margin_used=margin_fraction(margin_inputs), reserve=reserve, 

1178 config=config, 

1179 ) 

1180 if not sweep_order_needed(weight, target, config["min_trade_weight"]): 

1181 return earned, weight 

1182 traded = abs(target - weight) 

1183 cost = traded * config["cost_bps_per_side"] / 1e4 

1184 if traded > 0.0 and pv_for_costs > 0.0: 

1185 cost = max(cost, float(sweep.get("min_commission_usd", 1.0)) / pv_for_costs) 

1186 sweep["_last_cost"] = cost 

1187 return earned - cost, target 

1188 

1189 

1190def simulate_rank_book(frame: pd.DataFrame, **kwargs: Any) -> RankBookSimulationResult: 

1191 """Public entry point - see _simulate_rank_book_core()'s docstring for 

1192 the full algorithm. Discards held_days_by_ticker (only capacity_curve() 

1193 needs it).""" 

1194 result, _held_days_by_ticker = _simulate_rank_book_core(frame, **kwargs) 

1195 return result 

1196 

1197 

1198def capacity_curve( 

1199 frame: pd.DataFrame, 

1200 *, 

1201 dollar_volume_column: str = "liquidity_log_dollar_volume", 

1202 participation_cap: float, 

1203 base_kwargs: dict[str, Any], 

1204 top_n_sweep: list[int], 

1205) -> dict[str, Any]: 

1206 """Breadth + capacity check (V5.1 Phase 0, an addition beyond the 

1207 original roadmap table - see the V5.1 plan's own §1 "one thing missing 

1208 from the list"): sweeps top_n==bottom_n across top_n_sweep, holding 

1209 every other simulate_rank_book() kwarg fixed via base_kwargs, so a 

1210 rank-IC concentrated in a handful of names (net_sharpe collapses as 

1211 top_n shrinks toward the extreme) is visibly distinguishable from one 

1212 genuinely spread across the cross-section. 

1213 

1214 capacity_usd is a deliberately simple, honestly-approximate estimate, 

1215 not a precision claim: among names actually held during the BASE run 

1216 (base_kwargs's own top_n/bottom_n), the one with the lowest average 

1217 dollar volume (dollar_volume_column, a log1p value - inverted with 

1218 expm1 here, the correct inverse) is the binding constraint; scaling its 

1219 average dollar volume by participation_cap and by the number of held 

1220 names gives a rough total-book capacity ceiling. binding_ticker names 

1221 exactly which held name limits it, so this is auditable rather than a 

1222 black-box number. 

1223 

1224 A held ticker with dollar_volume_column == 0.0 exactly (e.g. a forex 

1225 pair - Yahoo Finance reports no real Volume for FX, so 

1226 log1p(close*volume) is always 0.0 for them, see development/Problems.md) 

1227 is EXCLUDED from the binding-ticker search: a true zero here means "no 

1228 real liquidity signal for this asset," not "zero capacity," and letting 

1229 it win the minimum would make one data-quality artifact dictate the 

1230 whole book's capacity regardless of every other held name's real 

1231 liquidity. If every held ticker lacks real volume data, this honestly 

1232 degrades to capacity_usd=0.0 / binding_ticker=None, the same "can't 

1233 estimate" result already returned when the base run holds nothing.""" 

1234 per_top_n: list[dict] = [] 

1235 base_held_days: dict[str, int] | None = None 

1236 base_top_n = base_kwargs.get("top_n") 

1237 

1238 for n in top_n_sweep: 

1239 sweep_kwargs = dict(base_kwargs) 

1240 sweep_kwargs["top_n"] = n 

1241 sweep_kwargs["bottom_n"] = n 

1242 result, held_days = _simulate_rank_book_core(frame, **sweep_kwargs) 

1243 per_top_n.append({"top_n": n, "net_sharpe": result.net_sharpe}) 

1244 if n == base_top_n: 

1245 base_held_days = held_days 

1246 

1247 if base_held_days is None: 

1248 _, base_held_days = _simulate_rank_book_core(frame, **base_kwargs) 

1249 

1250 if not base_held_days: 

1251 return {"capacity_usd": 0.0, "binding_ticker": None, "per_top_n": per_top_n} 

1252 

1253 ticker_column = base_kwargs.get("ticker_column", "ticker") 

1254 avg_log_dollar_volume = frame.groupby(ticker_column)[dollar_volume_column].mean() 

1255 held_avg_dollar_volume = { 

1256 ticker: float(np.expm1(avg_log_dollar_volume.get(ticker, 0.0))) for ticker in base_held_days 

1257 } 

1258 # Zero means "no real volume data for this ticker" (e.g. forex - see 

1259 # this function's own docstring), not "zero liquidity" - exclude it 

1260 # from the binding-ticker search so a data-quality artifact can't 

1261 # dictate the whole book's capacity. 

1262 tickers_with_real_volume = {ticker: value for ticker, value in held_avg_dollar_volume.items() if value > 0.0} 

1263 if not tickers_with_real_volume: 

1264 return {"capacity_usd": 0.0, "binding_ticker": None, "per_top_n": per_top_n} 

1265 

1266 binding_ticker = min(tickers_with_real_volume, key=tickers_with_real_volume.get) 

1267 capacity_usd = float(tickers_with_real_volume[binding_ticker] * participation_cap * len(held_avg_dollar_volume)) 

1268 return {"capacity_usd": capacity_usd, "binding_ticker": binding_ticker, "per_top_n": per_top_n} 

1269 

1270 

1271def stress_test_costs(frame: pd.DataFrame, *, base_kwargs: dict[str, Any], cost_multipliers: tuple[Any, ...] = (1.0, 2.0, 3.0)) -> list[dict]: 

1272 """One simulate_rank_book() run per cost multiplier, scaling BOTH 

1273 cost_bps_per_side and commission_bps - answers "does the edge survive 

1274 if real-world costs turn out to be 2x/3x the calibrated estimate", 

1275 the robustness check item 12 of the V5.1 roadmap asks for.""" 

1276 results = [] 

1277 for multiplier in cost_multipliers: 

1278 stressed_kwargs = dict(base_kwargs) 

1279 stressed_kwargs["cost_bps_per_side"] = float(base_kwargs.get("cost_bps_per_side", 0.0)) * multiplier 

1280 stressed_kwargs["commission_bps"] = float(base_kwargs.get("commission_bps", 0.0)) * multiplier 

1281 if base_kwargs.get("commission_bps_by_ticker"): 

1282 stressed_kwargs["commission_bps_by_ticker"] = { 

1283 ticker: float(value) * multiplier for ticker, value in base_kwargs["commission_bps_by_ticker"].items() 

1284 } 

1285 result = simulate_rank_book(frame, **stressed_kwargs) 

1286 results.append({"cost_multiplier": multiplier, **result.to_dict()}) 

1287 return results 

1288 

1289 

1290def _bootstrap_mean_confidence_interval( 

1291 values: list[float], n_resamples: int = 2000, confidence: float = 0.95, seed: int = 42 

1292) -> dict[str, Any]: 

1293 """Torch-free duplicate of train.py::bootstrap_ic_confidence_interval()'s 

1294 resample-with-replacement bootstrap over a plain float series - same 

1295 algorithm and defaults, deliberately reimplemented here (not imported) 

1296 since train.py imports torch and this package must stay torch-free (see 

1297 evaluation/__init__.py's docstring).""" 

1298 if not values: 

1299 return {"lower_bound": 0.0, "upper_bound": 0.0, "mean": 0.0} 

1300 rng = np.random.default_rng(seed) 

1301 array = np.asarray(values, dtype=float) 

1302 resampled_means = np.empty(n_resamples) 

1303 for i in range(n_resamples): 

1304 resampled_means[i] = rng.choice(array, size=len(array), replace=True).mean() 

1305 alpha = (1.0 - confidence) / 2.0 

1306 return { 

1307 "lower_bound": float(np.quantile(resampled_means, alpha)), 

1308 "upper_bound": float(np.quantile(resampled_means, 1.0 - alpha)), 

1309 "mean": float(array.mean()), 

1310 } 

1311 

1312 

1313def summarize_metric_stability(per_window_values: list[float], *, min_windows: int, max_sign_flip_fraction: float) -> dict[str, Any]: 

1314 """Cross-window stability summary (used by Phase 4's walk-forward 

1315 evaluation and Phase 5's ablation) - mirrors 

1316 train.py::assess_ranking_quality()'s era-sign-instability check, one 

1317 level up: a window whose sign disagrees with the overall mean's sign is 

1318 a "flip", same concept as an opposite-sign era. num_windows below 

1319 min_windows or a sign-flip fraction above max_sign_flip_fraction both 

1320 fail "stable".""" 

1321 values = [float(value) for value in per_window_values] 

1322 num_windows = len(values) 

1323 if num_windows == 0: 

1324 return { 

1325 "num_windows": 0, "mean": 0.0, "sign_flip_fraction": 0.0, "stable": False, 

1326 "failures": ["no_windows"], "bootstrap": _bootstrap_mean_confidence_interval([]), 

1327 } 

1328 

1329 mean_value = float(np.mean(values)) 

1330 overall_positive = mean_value >= 0.0 

1331 flips = sum(1 for value in values if (value >= 0.0) != overall_positive) 

1332 sign_flip_fraction = flips / num_windows 

1333 

1334 failures = [] 

1335 if num_windows < min_windows: 

1336 failures.append("insufficient_windows") 

1337 if sign_flip_fraction > max_sign_flip_fraction: 

1338 failures.append("sign_flip_fraction_above_gate") 

1339 

1340 return { 

1341 "num_windows": num_windows, 

1342 "mean": mean_value, 

1343 "sign_flip_fraction": sign_flip_fraction, 

1344 "stable": not failures, 

1345 "failures": failures, 

1346 "bootstrap": _bootstrap_mean_confidence_interval(values), 

1347 }