Coverage for portfolio/book_construction.py: 100%

257 statements  

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

1"""Stage-2 cross-sectional long/short book construction (Phase 3 of the 

25/10 -> 9/10 roadmap) - the first use of the rank_20d signal that decides 

3*which direction* a symbol trades, not just how large an already-decided 

4trade should be. 

5 

6Every existing sizing multiplier in this codebase (topology_sizing_multiplier(), 

7rank_sizing_multiplier() in risk/position_sizing.py) is deliberately 

8bounded and direction-PRESERVING: it can only shrink or (for rank_sizing_multiplier()) 

9modestly scale an already-decided position, never flip its sign. This 

10module is the one deliberate departure from that convention - 

11build_rank_based_book()'s `book_role_multiplier` (+1.0 long, -1.0 short) 

12SETS direction for the symbols it selects, because that is the entire 

13point of a cross-sectional book (rank the universe, go long the top, 

14short the bottom) - short-selling doesn't exist anywhere else in this 

15codebase today (`phase5.backtest.strategy_mode: "long_flat"` is the 

16existing ceiling everywhere else). 

17 

18Deliberately its own package, not folded into risk/ or analyzer/: 

19- Not risk/position_sizing.py: book construction needs the WHOLE-universe 

20 view (every symbol's rank_20d for this bar, seen at once) that 

21 position_sizing.py's pure single-symbol functions structurally don't 

22 have - see main.py::on_data()'s two-pass restructuring, which collects 

23 every symbol's candidate data in Pass 1 before this module ever runs. 

24- Not analyzer/market_analyzer.py: that module's per-symbol trade/simulate/ 

25 observe/reduce_risk categorization stays deterministic and per-symbol by 

26 design (see analyzer/README.md) - a book-selected symbol still passes 

27 through that exact same categorization afterward, unchanged; this module 

28 only ever decides the role (long/short) BEFORE that, never bypasses it. 

29 

30Ships config-gated OFF by default (phase_v2.portfolio_book.enabled: false) 

31- same precedent as rank_sizing_enabled - since this is a bigger structural 

32 change (direction-setting, not just direction-preserving) than any prior 

33 rank_20d integration, and the same non-overlapping-date-subsample caveat 

34 documented in risk/position_sizing.py::rank_sizing_multiplier() applies 

35 here too. 

36""" 

37 

38from __future__ import annotations 

39 

40import itertools 

41import math 

42from collections.abc import Mapping 

43from dataclasses import asdict, dataclass 

44from typing import Any 

45 

46 

47def _is_finite_number(value) -> bool: 

48 """V5.4.5 (development/Problems.md #117): a NaN rank score is not None - 

49 it passed the old `is not None` eligibility check, poisoned the sort 

50 order, made every hysteresis comparison False, and (worst of all) made 

51 the spread veto's `spread < floor` comparison False, silently disabling 

52 it. Non-finite = not a usable rank, same degrade path as missing.""" 

53 if value is None: 

54 return False 

55 try: 

56 return math.isfinite(float(value)) 

57 except (TypeError, ValueError): 

58 return False 

59 

60 

61@dataclass(frozen=True) 

62class BookAllocation: 

63 """One name's place in the rank book: long or short, its multiplier, its predicted rank and why it was chosen.""" 

64 role: str 

65 book_role_multiplier: float 

66 predicted_rank_20d: float 

67 book_reason: str 

68 # V5.1 Phase 0/1 (development/Problems.md - item 6 of the V5.1 roadmap): 

69 # both defaulted, so every existing positional construction and 

70 # asdict()/to_dict() consumer is unaffected. rank_head records which 

71 # blended signal (see portfolio/rank_signal.py) drove this allocation; 

72 # target_weight is filled in by callers that run the neutrality pass 

73 # (portfolio/book_neutrality.py) - None means "neutrality not applied, 

74 # read book_role_multiplier * the caller's own weight formula instead", 

75 # same convention as every other Optional payload field in this codebase. 

76 rank_head: str = "blend" 

77 target_weight: float | None = None 

78 

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

80 return asdict(self) 

81 

82 

83def normalize_per_asset_class_slots( 

84 raw: dict[str, object] | None, 

85) -> tuple[dict[str, tuple[int, int]], list[str]]: 

86 """Validates and coerces a raw `phase_v2.portfolio_book.per_asset_class_slots` 

87 config dict into build_rank_based_book()'s expected shape. 

88 `build_rank_based_book()` unpacks each value unconditionally 

89 (`for asset_class, (top_n, bottom_n) in per_asset_class_slots.items()`), 

90 so a malformed entry (wrong length, wrong type) would otherwise hard- 

91 crash every bar instead of degrading gracefully like every other 

92 optional config-driven feature in this codebase - development/ 

93 Problems.md. Each value must be a 2-element `[top_n, bottom_n]` 

94 list/tuple; anything else is skipped, not fatal. 

95 

96 Returns `(valid_slots, skipped_asset_classes)` - pure and no-logging 

97 by design (so it stays independently testable); callers with access 

98 to a logger (main.py's `self.Debug()`) should report the skipped 

99 list themselves.""" 

100 valid: dict[str, tuple[int, int]] = {} 

101 skipped: list[str] = [] 

102 for asset_class, slots in (raw or {}).items(): 

103 if isinstance(slots, (list, tuple)) and len(slots) == 2: 

104 valid[asset_class] = tuple(slots) 

105 else: 

106 skipped.append(asset_class) 

107 return valid, skipped 

108 

109 

110def _hysteresis_adjusted_selection( 

111 strength_ordered_candidates: list[str], 

112 eligible_ranks: dict[str, float], 

113 n: int, 

114 role: str, 

115 previous_allocations: dict[str, BookAllocation] | None, 

116 hysteresis_rank_margin: float, 

117) -> list[str]: 

118 """Sticky top/bottom-N selection (V5.1 Phase 0/1, development/Problems.md 

119 #43's rebalance-churn work continued): an incumbent (same `role` in 

120 `previous_allocations`) whose rank has fallen just outside the natural 

121 n-slot cutoff, but is still within `hysteresis_rank_margin` of it, keeps 

122 its slot rather than being dropped and immediately re-entered on the 

123 next small rank wobble - directly reduces turnover/fees, the whole point 

124 of this parameter (see book_neutrality.py's module docstring). 

125 

126 `strength_ordered_candidates` must already be sorted BEST-FIRST for this 

127 leg - i.e. descending by predicted_rank_20d for role="long" (highest 

128 rank = most long-worthy), ascending by predicted_rank_20d for 

129 role="short" (lowest rank = most short-worthy). Normalizing both legs to 

130 "best first" here (rather than each leg carrying its own sign 

131 convention) is what keeps this function's cutoff/margin arithmetic 

132 identical for both roles - only the caller's ordering differs. 

133 

134 Bounded at exactly `n` slots (never grows the book past what was 

135 requested). `previous_allocations` empty/None or `hysteresis_rank_margin 

136 <= 0` returns `strength_ordered_candidates[:n]` unchanged - BYTE- 

137 IDENTICAL to the pre-hysteresis plain top-n slice, so every existing 

138 caller/test that doesn't pass these new params is unaffected.""" 

139 natural = strength_ordered_candidates[:n] 

140 if not previous_allocations or hysteresis_rank_margin <= 0.0 or n <= 0 or not natural: 

141 return natural 

142 

143 cutoff_rank = eligible_ranks[natural[-1]] 

144 incumbents = [ 

145 symbol 

146 for symbol in strength_ordered_candidates 

147 if symbol in previous_allocations and previous_allocations[symbol].role == role 

148 ] 

149 if role == "long": 

150 retained_incumbents = [ 

151 symbol for symbol in incumbents if eligible_ranks[symbol] >= cutoff_rank - hysteresis_rank_margin 

152 ] 

153 else: 

154 retained_incumbents = [ 

155 symbol for symbol in incumbents if eligible_ranks[symbol] <= cutoff_rank + hysteresis_rank_margin 

156 ] 

157 # Cap incumbents at n slots, keeping the strongest ones first (order 

158 # already inherited from strength_ordered_candidates) - an incumbent 

159 # list longer than n would otherwise grow the book past what was 

160 # requested, which hysteresis is meant to reduce churn within, not 

161 # override entirely. 

162 retained_incumbents = [ 

163 symbol for symbol in strength_ordered_candidates if symbol in retained_incumbents 

164 ][:n] 

165 

166 final = list(retained_incumbents) 

167 for symbol in strength_ordered_candidates: 

168 if len(final) >= n: 

169 break 

170 if symbol not in final: 

171 final.append(symbol) 

172 return final[:n] 

173 

174 

175def compute_confidence_spread( 

176 long_symbols: list[str], 

177 short_symbols: list[str], 

178 spread_ranks: dict[str, float], 

179 eligible_ranks: dict[str, float], 

180) -> float | None: 

181 """mean(long-side score) - mean(short-side score), the exact quantity 

182 _select_book_group()'s min_rank_confidence_spread gate compares 

183 against a floor. Public (not module-private) so a calibration tool can 

184 compute the identical statistic against historical data without 

185 re-deriving the formula - the two can then never disagree on what 

186 "spread" means for a given day's selection. 

187 

188 `spread_ranks.get(symbol, eligible_ranks[symbol])` - a symbol missing 

189 from spread_ranks (e.g. a caller-supplied dict that doesn't cover 

190 every eligible symbol) falls back to its own eligible_ranks value 

191 rather than a KeyError, same defensive convention as every other 

192 optional-override lookup in this module. 

193 

194 None if either list is empty - spread is undefined without both 

195 sides (mirrors the caller never reaching this check for a long-only 

196 book).""" 

197 if not long_symbols or not short_symbols: 

198 return None 

199 long_mean = sum(spread_ranks.get(symbol, eligible_ranks[symbol]) for symbol in long_symbols) / len(long_symbols) 

200 short_mean = sum(spread_ranks.get(symbol, eligible_ranks[symbol]) for symbol in short_symbols) / len(short_symbols) 

201 return long_mean - short_mean 

202 

203 

204def _select_book_group( 

205 eligible_ranks: dict[str, float], 

206 top_n: int, 

207 bottom_n: int, 

208 min_rank_confidence_spread: float, 

209 previous_allocations: dict[str, BookAllocation] | None = None, 

210 hysteresis_rank_margin: float = 0.0, 

211 spread_check_ranks: dict[str, float] | None = None, 

212 rolling_ic_gate_result: dict[str, Any] | None = None, 

213 veto_reason_out: dict[str, Any] | None = None, 

214) -> dict[str, BookAllocation]: 

215 """Core discrete top-N-long / bottom-N-short selection over an already- 

216 filtered `{symbol: predicted_rank_20d}` pool - shared by the pooled 

217 (build_rank_based_book()'s default) and per-asset-class 

218 (`per_asset_class_slots`) paths, so both apply identical selection 

219 logic to whatever pool they're given, just scoped differently. See 

220 build_rank_based_book()'s docstring for the full behavior contract. 

221 

222 `previous_allocations`/`hysteresis_rank_margin` (V5.1 Phase 0/1, 

223 defaults None/0.0): optional sticky-selection pass over the natural 

224 top/bottom-N slice - see _hysteresis_adjusted_selection()'s docstring. 

225 Both defaults are a strict no-op, reproducing the pre-hysteresis 

226 selection exactly. 

227 

228 `spread_check_ranks` (V5.1 Phase 1, development/Problems.md #77): 

229 optional separate `{symbol: raw_score}` dict used ONLY for the 

230 min_rank_confidence_spread comparison below - defaults to 

231 `eligible_ranks` itself when not given (byte-identical to before this 

232 parameter existed). Selection (WHICH symbols end up long/short) is 

233 unaffected either way, since sorting is invariant under a monotone 

234 transform - `eligible_ranks` may already be a per-bar cross-sectional 

235 percentile (portfolio/rank_signal.py::cross_sectional_rank_scores()), 

236 and a fixed top-N/bottom-N split out of that ALWAYS shows a large 

237 spread by construction (e.g. ~0.9 for top-6/bottom-6 of ~74 names), 

238 regardless of whether the underlying model had any real conviction 

239 that day - a normalized-scale spread check is statistically 

240 meaningless, it can never distinguish a genuinely dispersed day from a 

241 noisy one. Passing the pre-normalization raw scores here restores the 

242 gate's actual purpose: does the RAW output show real dispersion. 

243 

244 `rolling_ic_gate_result` (V5.3.5, development/Problems.md #102): 

245 optional output of portfolio.rolling_ic_gate.evaluate_rolling_ic_gate() - 

246 an INDEPENDENT second veto alongside min_rank_confidence_spread above. 

247 Default None is a strict no-op (byte-identical to before this 

248 parameter existed) - same "missing/degraded signal never changes 

249 trading behavior" contract every optional overlay in this function 

250 already guarantees. Where the dispersion check asks "did the model 

251 differentiate symbols today," this one asks "has the model's recent 

252 trailing prediction quality actually been good" - #102 found a real 

253 backtest where the answer to the first question was "yes" throughout 

254 a stretch where the honest answer to the second was "no." 

255 

256 `veto_reason_out` (V5.3.5, development/Problems.md #102): optional 

257 output-by-mutation dict - when not None, this function sets 

258 `veto_reason_out["reason"]` to a short string identifying WHY `{}` was 

259 returned, for each of the veto paths below. Deliberately NOT a return- 

260 type change (this function has real callers beyond main.py - the 

261 offline reconciliation/ablation/capacity tools - that must never need 

262 to change how they read this function's result just to get a 

263 diagnostic only main.py's own book-history logging wants); a caller 

264 that doesn't pass this argument is completely unaffected.""" 

265 if len(eligible_ranks) < 2 or top_n <= 0: 

266 if veto_reason_out is not None: 

267 veto_reason_out["reason"] = "thin_universe_or_zero_top_n" 

268 return {} 

269 spread_ranks = spread_check_ranks if spread_check_ranks is not None else eligible_ranks 

270 

271 ranked_symbols = sorted(eligible_ranks, key=lambda symbol: eligible_ranks[symbol], reverse=True) 

272 natural_long_symbols = ranked_symbols[:top_n] 

273 remaining_symbols = [symbol for symbol in ranked_symbols if symbol not in natural_long_symbols] 

274 

275 long_symbols = _hysteresis_adjusted_selection( 

276 ranked_symbols, eligible_ranks, top_n, "long", previous_allocations, hysteresis_rank_margin 

277 ) 

278 # Short leg's "best first" ordering is ascending rank (lowest = most 

279 # short-worthy) - the mirror image of ranked_symbols' descending order. 

280 short_ordered_candidates = sorted(remaining_symbols, key=lambda symbol: eligible_ranks[symbol]) 

281 short_symbols = _hysteresis_adjusted_selection( 

282 short_ordered_candidates, eligible_ranks, bottom_n, "short", previous_allocations, hysteresis_rank_margin 

283 ) 

284 # Guard against a pathological case: hysteresis retaining a symbol on 

285 # both legs simultaneously (only possible if previous_allocations 

286 # itself was inconsistent - it never is, since a symbol can only ever 

287 # hold ONE role) - re-derive remaining_symbols/short candidates from the 

288 # ACTUAL long_symbols chosen above so the two legs never overlap. 

289 if long_symbols != natural_long_symbols: 

290 remaining_symbols = [symbol for symbol in ranked_symbols if symbol not in long_symbols] 

291 short_ordered_candidates = sorted(remaining_symbols, key=lambda symbol: eligible_ranks[symbol]) 

292 short_symbols = _hysteresis_adjusted_selection( 

293 short_ordered_candidates, eligible_ranks, bottom_n, "short", previous_allocations, hysteresis_rank_margin 

294 ) 

295 

296 if not long_symbols: 

297 if veto_reason_out is not None: 

298 veto_reason_out["reason"] = "no_long_candidates" 

299 return {} 

300 # bottom_n > 0 means a short side was actually requested - if nothing 

301 # was left over to fill it (long_n consumed the whole eligible pool), 

302 # stay strict and refuse the whole book, matching this function's 

303 # original behavior. bottom_n == 0 (main.py passes this for 

304 # phase5.backtest.strategy_mode == "long_flat" - see main.py's own 

305 # strategy_mode enforcement) is a deliberate long-only request, not a 

306 # degenerate case - falls through to the long-only book below. 

307 if bottom_n > 0 and not short_symbols: 

308 if veto_reason_out is not None: 

309 veto_reason_out["reason"] = "no_short_candidates" 

310 return {} 

311 

312 if short_symbols: 

313 # compute_confidence_spread() (module-level, above) - shared with 

314 # the calibration tool that derives min_rank_confidence_spread 

315 # from real data, so the two can never disagree on what "spread" 

316 # means for a given selection. 

317 spread = compute_confidence_spread(long_symbols, short_symbols, spread_ranks, eligible_ranks) 

318 if spread is not None and spread < min_rank_confidence_spread: 

319 if veto_reason_out is not None: 

320 veto_reason_out["reason"] = "min_rank_confidence_spread_below_floor" 

321 return {} 

322 

323 # V5.3.5 (development/Problems.md #102) - an INDEPENDENT second veto, 

324 # checked regardless of whether a short leg was requested (unlike the 

325 # spread check above, which only has meaning for a two-sided book): 

326 # the model can look genuinely dispersed today (clearing the check 

327 # above) while its recent TRAILING predictions have carried near-zero 

328 # or negative realized skill - a real backtest showed this happens, 

329 # and that the dispersion-only gate can't tell the difference. 

330 if rolling_ic_gate_result is not None and not rolling_ic_gate_result["engaged"]: 

331 if veto_reason_out is not None: 

332 veto_reason_out["reason"] = rolling_ic_gate_result["reason"] 

333 return {} 

334 

335 allocations: dict[str, BookAllocation] = {} 

336 for symbol in long_symbols: 

337 allocations[symbol] = BookAllocation( 

338 role="long", 

339 book_role_multiplier=1.0, 

340 predicted_rank_20d=eligible_ranks[symbol], 

341 book_reason="rank_based_book_long", 

342 ) 

343 for symbol in short_symbols: 

344 allocations[symbol] = BookAllocation( 

345 role="short", 

346 book_role_multiplier=-1.0, 

347 predicted_rank_20d=eligible_ranks[symbol], 

348 book_reason="rank_based_book_short", 

349 ) 

350 return allocations 

351 

352 

353def build_rank_based_book( 

354 book_candidates: dict[str, dict], 

355 top_n: int, 

356 bottom_n: int, 

357 min_rank_confidence_spread: float = 0.0, 

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

359 previous_allocations: dict[str, BookAllocation] | None = None, 

360 hysteresis_rank_margin: float = 0.0, 

361 spread_check_ranks: dict[str, float] | None = None, 

362 rolling_ic_gate_result: dict[str, Any] | None = None, 

363 veto_reason_out: dict[str, Any] | None = None, 

364) -> dict[str, BookAllocation]: 

365 """Discrete top-N-long / bottom-N-short book construction from each 

366 symbol's predicted_rank_20d for this bar. Continuous rank-weighted 

367 sizing (rather than a hard top/bottom-N cutoff) is a documented future 

368 extension, not built here - the discrete version is simpler to reason 

369 about and test first. 

370 

371 `book_candidates` is `{symbol: {"predicted_rank_20d": float | None, 

372 "trading_eligible": bool, "asset_class": str | None, ...}}` - one entry 

373 per symbol Pass 1 of main.py::on_data() collected this bar (extra keys 

374 like probability_up/confidence are ignored here, kept only so callers 

375 can pass the same dict they already built for other purposes). A 

376 symbol is eligible for book selection only if `trading_eligible` is 

377 true (this is exactly how phase9.asset_quality's observation-only 

378 assets get excluded - main.py already computes this per-symbol flag 

379 identically for every other decision) and `predicted_rank_20d` is not 

380 None (model unavailable/still warming up that bar). 

381 

382 `bottom_n == 0` requests a deliberate long-only book (no shorts at all) - 

383 used by main.py to honor `phase5.backtest.strategy_mode == "long_flat"` 

384 while still getting rank-driven entry/rotation on the long side. Any 

385 `bottom_n > 0` still requires at least one eligible symbol on EACH side 

386 to form a book at all - a one-sided book isn't attempted when a short 

387 side was actually requested but nothing was available for it; returns 

388 {} in that case, same as every other degenerate-input case below. 

389 `top_n`/`bottom_n` (or each 

390 asset class's own pair, see `per_asset_class_slots` below) exceeding 

391 the number of eligible symbols degrades gracefully to however many are 

392 actually available (never raises) - same "pad/truncate rather than 

393 error on a thin universe" convention as topology/market_topology.py's 

394 rank_correlated_peers(). 

395 

396 `min_rank_confidence_spread` is a floor on (mean long-side rank - mean 

397 short-side rank) before a book (or, with `per_asset_class_slots`, each 

398 individual asset class's own book) engages at all - on a day where the 

399 ranked pool's predicted ranks are all clustered near 0.5 (no real 

400 dispersion), forcing a long/short split would be noise, not signal; 

401 the book disengages entirely (returns {} for that pool) rather than 

402 trading a meaningless split. Every symbol then falls through to 

403 whatever non-book decision main.py's Pass 2 would have made anyway - 

404 byte-identical to this module not existing at all, the same "missing/ 

405 degraded signal never changes trading behavior" contract this 

406 codebase's other optional overlays already guarantee. 

407 

408 `per_asset_class_slots` (default None - pooled ranking, this function's 

409 original and only behavior before this parameter existed) is an 

410 optional `{asset_class: (top_n, bottom_n)}` map. When provided, `top_n`/ 

411 `bottom_n` are ignored and every eligible symbol is ranked *within its 

412 own asset_class group only* instead of one combined-universe pool - so 

413 e.g. equities and crypto each get their own long/short slot budget 

414 instead of one side potentially being filled entirely by a single 

415 dominant asset class. A symbol whose `asset_class` isn't a key in 

416 `per_asset_class_slots` is excluded from book selection entirely (not 

417 silently folded into some catch-all group) - same explicit-opt-in 

418 convention risk/asset_class_router.py already uses for future/option. 

419 `min_rank_confidence_spread` is applied independently per asset class 

420 (each class's own long/short spread must individually clear the bar - 

421 pooling the check across classes with potentially very different rank 

422 distributions would be misleading). Results from every class are 

423 unioned into one returned dict, same shape as the pooled path. 

424 

425 Returns a dict covering ONLY the symbols the book actively wants long 

426 or short (not a "flat" entry for every candidate) - callers should 

427 treat "symbol absent from the returned dict" as "book has no view on 

428 this symbol," not "book says flat." 

429 

430 `previous_allocations`/`hysteresis_rank_margin` (V5.1 Phase 0/1, 

431 defaults None/0.0 - a strict no-op reproducing pre-hysteresis selection 

432 exactly): threaded straight through to _select_book_group() (pooled 

433 path) or applied identically within each asset class (per-asset-class 

434 path) - see _hysteresis_adjusted_selection()'s docstring for the actual 

435 sticky-selection behavior. 

436 

437 `spread_check_ranks` (V5.1 Phase 1, development/Problems.md #77): 

438 optional `{symbol: raw_score}` override for the min_rank_confidence_spread 

439 check only - see _select_book_group()'s docstring for why this must be 

440 the PRE-normalization score when the caller's `book_candidates` 

441 predicted_rank_20d values are already a cross-sectional percentile. 

442 Defaults to None (falls back to book_candidates' own predicted_rank_20d, 

443 byte-identical to before this parameter existed). 

444 

445 `rolling_ic_gate_result`/`veto_reason_out` (V5.3.5, development/ 

446 Problems.md #102): threaded straight through to _select_book_group() - 

447 see that function's own docstring. Both default to None, a strict 

448 no-op. With `per_asset_class_slots`, `rolling_ic_gate_result` is 

449 applied identically to every class's own selection (this signal is 

450 portfolio-wide, not asset-class-specific, unlike min_rank_confidence_spread 

451 which already gets a note above about being checked per class); if 

452 more than one class vetoes, `veto_reason_out` ends up holding 

453 whichever class's reason was computed last - an accepted, documented 

454 simplification, since the only thing that consumes this diagnostic 

455 (main.py's book-history logging) only reads it when the OVERALL 

456 `allocations` result comes back completely empty, at which point any 

457 one real reason is more useful than none.""" 

458 eligible = { 

459 symbol: candidate 

460 for symbol, candidate in book_candidates.items() 

461 if candidate.get("trading_eligible") and _is_finite_number(candidate.get("predicted_rank_20d")) 

462 } 

463 

464 if per_asset_class_slots is None: 

465 eligible_ranks = {symbol: candidate["predicted_rank_20d"] for symbol, candidate in eligible.items()} 

466 return _select_book_group( 

467 eligible_ranks, top_n, bottom_n, min_rank_confidence_spread, 

468 previous_allocations, hysteresis_rank_margin, spread_check_ranks, 

469 rolling_ic_gate_result, veto_reason_out, 

470 ) 

471 

472 allocations: dict[str, BookAllocation] = {} 

473 for asset_class, (class_top_n, class_bottom_n) in per_asset_class_slots.items(): 

474 class_eligible_ranks = { 

475 symbol: candidate["predicted_rank_20d"] 

476 for symbol, candidate in eligible.items() 

477 if candidate.get("asset_class") == asset_class 

478 } 

479 allocations.update( 

480 _select_book_group( 

481 class_eligible_ranks, class_top_n, class_bottom_n, min_rank_confidence_spread, 

482 previous_allocations, hysteresis_rank_margin, spread_check_ranks, 

483 rolling_ic_gate_result, veto_reason_out, 

484 ) 

485 ) 

486 return allocations 

487 

488 

489def pct_returns_from_closes(closes: list[Any]) -> list[float]: 

490 """V5.4.4 - close-to-close simple returns from a symbol's rolling 

491 close window (main.py's `self.symbol_windows[symbol]` "close" values, 

492 oldest first). The per-symbol return history `apply_hrp_weights()` 

493 consumes for its covariance estimation. 

494 

495 Pairs containing a missing/non-positive/non-finite close are SKIPPED 

496 (not emitted as NaN/inf/-1.0) - a split-adjusted 0 or a None from a 

497 partially-populated window would otherwise poison the covariance 

498 matrix HRP estimates downstream (a 0 CURRENT close would emit a 

499 -100% return, a variance bomb, even though its previous close is 

500 technically usable). V5.4.5 (#117): NaN closes pass the old `<= 0.0` 

501 check (`nan <= 0` is False) and poisoned the covariance the same way. 

502 Fewer than 2 usable closes returns [] (no return can exist without at 

503 least one previous close to diff against).""" 

504 returns: list[float] = [] 

505 for previous_close, current_close in itertools.pairwise(closes): 

506 if ( 

507 previous_close is None 

508 or current_close is None 

509 or not math.isfinite(float(previous_close)) 

510 or not math.isfinite(float(current_close)) 

511 or previous_close <= 0.0 

512 or current_close <= 0.0 

513 ): 

514 continue 

515 returns.append(float(current_close) / float(previous_close) - 1.0) 

516 return returns 

517 

518 

519def apply_hrp_weights( 

520 book_allocations: dict[str, BookAllocation], 

521 returns_by_symbol: dict[str, list[float]], 

522 gross_exposure: float = 1.0, 

523 linkage_method: str = "ward", 

524) -> dict[str, float]: 

525 """V5.4.4 - HRP book SIZING over an already-selected book. Replaces 

526 the per-symbol confidence formula (min(max_position_weight, 

527 0.10+0.15*confidence) * book_role_multiplier) with Hierarchical Risk 

528 Parity inverse-variance weights derived from the selected symbols' 

529 return correlation structure - SAME symbols, SAME roles, different 

530 sizing only. Selection (build_rank_based_book()) always runs first 

531 and is never affected; this function must be called with its output. 

532 

533 `returns_by_symbol` is `{symbol_key: [close-to-close returns]}` - 

534 main.py builds it from each selected symbol's own rolling window 

535 (self.symbol_windows, the 25-bar deque) via pct_returns_from_closes(); 

536 symbols missing from the dict (or with < 2 usable returns) are simply 

537 excluded from the covariance estimation by build_hrp_allocation()'s 

538 own filtering, never a KeyError. 

539 

540 Per-leg weight contract (mirrors portfolio/hrp_allocation.py:: 

541 build_hrp_allocation(), which this delegates to): with BOTH legs 

542 populated each leg sums to +/-gross_exposure/2 (dollar-neutral book); 

543 a single-sided book (long_flat strategy_mode, bottom_n=0) gives the 

544 present leg the FULL gross. Insufficient history (< 2 symbols with 

545 usable returns) or an HRP convergence failure degrades to equal 

546 weight within each leg - sizing always covers exactly the selected 

547 symbol set, {} only when book_allocations itself is empty. 

548 

549 Deliberately a lazy import of portfolio.hrp_allocation inside the 

550 function body: that module imports scipy at module scope, and this 

551 keeps book_construction.py (imported by main.py on EVERY run, HRP 

552 engaged or not) scipy-free on the default "rank" path - the same 

553 isolator-timeout/import-weight concern that keeps evaluation/ 

554 rank_ic_core.py torch-free (development/Problems.md #16/#102).""" 

555 if not book_allocations: 

556 return {} 

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

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

559 from portfolio.hrp_allocation import build_hrp_allocation 

560 

561 return build_hrp_allocation( 

562 returns_by_symbol, 

563 selected_tickers_long=long_symbols, 

564 selected_tickers_short=short_symbols, 

565 gross_exposure=gross_exposure, 

566 linkage_method=linkage_method, 

567 ) 

568 

569 

570def should_rebalance_this_bar( 

571 bar_index: int, 

572 rebalance_every_bars: int, 

573 has_previous_allocation: bool, 

574 is_trading_day_bar: bool = True, 

575 phase_offset: int = 0, 

576) -> bool: 

577 """Stage 2 of the rank-pivot roadmap (development/Problems.md#43): the 

578 book previously re-ranked and re-formed on EVERY bar, churning positions 

579 far faster than rank_20d's actual ~20-trading-day horizon can support 

580 (653 orders/~2yr, no edge left after costs). This is a pure, main.py- 

581 independent extraction of main.py::on_data()'s rebalance-gating decision 

582 so it's unit-testable without a running Lean/QCAlgorithm instance (this 

583 module has no Lean import, main.py does). 

584 

585 `bar_index` is main.py's 1-indexed `self.bar_index` (incremented to 1 on 

586 the very first `on_data()` call, before any bar has been processed). 

587 `rebalance_every_bars` is `phase_v2.portfolio_book.rebalance_every_bars` 

588 (1 reproduces the previous every-bar-rebalance behavior exactly, since 

589 `(n - 1) % 1 == 0` for every n). `has_previous_allocation` should be 

590 False only on a genuinely fresh run (no cached book yet) - it forces a 

591 rebalance regardless of the modulo so the book is never left empty. 

592 

593 `is_trading_day_bar` (V5.2.4, development/Problems.md #91) - default 

594 True, fully backward-compatible with every existing caller. False on a 

595 tick main.py has determined isn't the equity-session tick (e.g. an 

596 off-session crypto/forex-only Lean Slice, see main.py's own 

597 `is_equity_session_bar`) - never rebalances on such a tick, full stop, 

598 regardless of `bar_index`'s modulo or `has_previous_allocation`. This 

599 exists because `main.py`'s `bar_index` only advances on equity-session 

600 ticks post-V5.2.4 - without this explicit gate, several consecutive 

601 off-session ticks following a real rebalance-eligible bar would keep 

602 re-evaluating the SAME already-satisfied modulo condition and could 

603 re-trigger a rebalance that already happened. 

604 

605 Returns True on bar_index 1, 1+N, 1+2N, ... (i.e. 0, N, 2N, ... in 

606 0-indexed bar terms) - False on every bar in between, where the caller 

607 should reuse its previously cached allocation and simply hold. 

608 

609 `phase_offset` (V6.2.0, staggered tranches): shifts the cadence by that many bars (0 = the cadence above).""" 

610 if not is_trading_day_bar: 

611 return False 

612 if not has_previous_allocation: 

613 return True 

614 return (bar_index - 1 - int(phase_offset)) % max(1, rebalance_every_bars) == 0 

615 

616 

617def tranche_offsets(rebalance_every_bars: int, tranches: int) -> list[int]: 

618 """V6.2.0 staggered book: the phase offset of each of `tranches` sub-books, spread evenly over one cadence 

619 (20 bars, 2 tranches -> [0, 10]). One tranche -> [0], the single book.""" 

620 count = max(1, int(tranches)) 

621 every = max(1, int(rebalance_every_bars)) 

622 return [int(round(index * every / count)) % every for index in range(count)] 

623 

624 

625def tranche_book_params(top_n: int, bottom_n: int, gross_exposure_cap: float, tranches: int, 

626 max_active_positions: int | None = None) -> dict[str, Any]: 

627 """One tranche's share of the book: ceil(top_n / K) longs and ceil(bottom_n / K) shorts (a side with 0 names stays 0), 

628 gross cap / K and, when given, ceil(position cap / K) positions. K = 1 returns the book's own values.""" 

629 count = max(1, int(tranches)) 

630 return { 

631 "top_n": -(-int(top_n) // count) if top_n else 0, 

632 "bottom_n": -(-int(bottom_n) // count) if bottom_n else 0, 

633 "gross_exposure_cap": float(gross_exposure_cap) / count, 

634 "max_active_positions": (-(-int(max_active_positions) // count)) if max_active_positions else max_active_positions, 

635 } 

636 

637 

638def partial_adjust_weights(current: dict[str, float], target: dict[str, float], fraction: float, 

639 min_weight: float = 1e-3) -> dict[str, float]: 

640 """V6.4.0 (lead L6): move `fraction` of the way from the held weights to the new target on a rebalance, 

641 `current + fraction * (target - current)` per name; weights that fall under `min_weight` are dropped. A fraction of 1 

642 returns the target unchanged (the shipped book); the blend of two valid books stays inside the same gross cap.""" 

643 fraction = float(fraction) 

644 if fraction >= 1.0: 

645 return dict(target) 

646 adjusted = {} 

647 for symbol in set(current) | set(target): 

648 before = float(current.get(symbol, 0.0)) 

649 weight = before + fraction * (float(target.get(symbol, 0.0)) - before) 

650 if abs(weight) >= min_weight: 

651 adjusted[symbol] = weight 

652 return adjusted 

653 

654 

655def combine_tranche_weights(tranche_weights: list[dict[str, float]]) -> dict[str, float]: 

656 """The live book target: the sum of the tranches' signed weights per name (a name held by two tranches nets); names 

657 that net to zero are dropped.""" 

658 combined: dict[str, float] = {} 

659 for weights in tranche_weights: 

660 for symbol, weight in weights.items(): 

661 combined[symbol] = combined.get(symbol, 0.0) + float(weight) 

662 return {symbol: weight for symbol, weight in combined.items() if weight != 0.0} 

663 

664 

665def should_exit_non_selected_book_symbol( 

666 book_is_active: bool, 

667 portfolio_book_enabled: bool, 

668 is_currently_invested: bool, 

669) -> bool: 

670 """V5.2.4 (development/Problems.md #91) - whether main.py's Pass 2 

671 should force-close a currently-invested, book-managed position because 

672 the book engaged this bar and didn't select it (the "rotation exit"). 

673 

674 Returns False whenever `book_is_active` is False (this bar's 

675 `book_allocations` came back empty) - matching `build_rank_based_book()`'s 

676 own documented contract just above: a disengaged book 

677 (`min_rank_confidence_spread` gate failure, or - pre-V5.2.4 - a thin/ 

678 off-session-tick artifact) is "byte-identical to this module not 

679 existing at all", never a liquidation trigger. Before this function 

680 existed, main.py's own Pass 2 violated that documented contract - 

681 force-selling EVERY currently-invested book symbol whenever 

682 `book_allocations` didn't contain it, without distinguishing "the whole 

683 book disengaged today" from "this specific symbol got rotated out of a 

684 REAL, active book" (the only case that should ever force an exit). 

685 

686 Callers pass `book_is_active=bool(book_allocations)` - `symbol_key not 

687 in book_allocations` (i.e. "this symbol specifically wasn't selected") 

688 is the caller's own responsibility to check separately, same as before; 

689 this function only answers "is a force-exit ever appropriate given the 

690 book's overall state this bar", not "for this particular symbol".""" 

691 return portfolio_book_enabled and book_is_active and is_currently_invested 

692 

693 

694def build_book_raw_weights( 

695 book_allocations: Mapping[str, BookAllocation], 

696 max_position_weight: float, 

697) -> dict[str, float]: 

698 """V5.5.0 (Problems.md #128) - the live book's pre-neutrality weight per 

699 symbol: min(max_position_weight, 0.10 + 0.15 * confidence) * role 

700 multiplier, confidence = min(1, |rank - 0.5| * 2). Extracted from 

701 main.py's inline loop so the offline simulator's as-live mode feeds 

702 apply_book_neutrality() the IDENTICAL raw weights instead of equal 

703 weights (parity rule, AGENTS.md). Non-finite rank -> skipped.""" 

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

705 for symbol, allocation in book_allocations.items(): 

706 if not _is_finite_number(allocation.predicted_rank_20d): 

707 continue 

708 confidence = min(1.0, abs(float(allocation.predicted_rank_20d) - 0.5) * 2.0) 

709 raw_weights[symbol] = min(float(max_position_weight), 0.10 + 0.15 * confidence) * allocation.book_role_multiplier 

710 return raw_weights 

711 

712 

713def remember_formed_book(previous_formed: dict[str, Any] | None, new_allocations: dict[str, Any] | None) -> dict[str, Any]: 

714 """V5.5.0 (Problems.md #128) - the hysteresis memory a veto must NOT wipe. 

715 

716 main.py stored every rebalance result into the one dict it also uses as 

717 "the book to trade", so a gate veto (empty allocations) erased the 

718 previous book. The next rebalance then selected with no hysteresis 

719 anchor, and `has_previous_allocation` read False so the book re-formed 

720 on every following bar until a gate opened. The positions the book had 

721 opened were still held the whole time. This keeps the last NON-EMPTY 

722 book as the anchor: a veto leaves it untouched, a real book replaces it. 

723 """ 

724 if new_allocations: 

725 return dict(new_allocations) 

726 return dict(previous_formed) if previous_formed else {} 

727 

728 

729def apply_book_weight_floor( 

730 target_weight: float, 

731 base_target_weight: float, 

732 floor_fraction: float, 

733 skip_floor: bool = False, 

734) -> float: 

735 """V5.5.0 (Problems.md #128) - bound how far the multiplier chain can 

736 shrink a book member below the weight the book chose for it. 

737 

738 The offline simulation trades the book's own weight (~8% a name); live 

739 stacks volatility (0.35-1.25), confidence (0.5-1.0), topology 

740 (0.5-1.0), cost (>=0.25) and liquidity (0.35) multipliers on top, which 

741 left equity at ~3% of NAV. The floor is symmetric (|weight| only, sign 

742 kept) so it cannot tilt the long/short balance, and is a no-op at 

743 `floor_fraction <= 0` (the pre-V5.5.0 behavior). `skip_floor` is for the 

744 liquidity "reduce_size" haircut, which is a safety cut that must never be 

745 undone. Never raises the weight above |base_target_weight|. 

746 """ 

747 try: 

748 weight = float(target_weight) 

749 base = abs(float(base_target_weight)) 

750 floor_fraction = float(floor_fraction) 

751 except (TypeError, ValueError): 

752 return 0.0 

753 if not (math.isfinite(weight) and math.isfinite(base) and math.isfinite(floor_fraction)): 

754 return 0.0 

755 if skip_floor or floor_fraction <= 0.0 or weight == 0.0 or base <= 0.0: 

756 return weight 

757 floor = min(1.0, floor_fraction) * base 

758 if abs(weight) >= floor: 

759 return weight 

760 return floor if weight > 0.0 else -floor 

761 

762 

763def update_book_owned_symbols( 

764 owned: set[str], 

765 symbol_key: str, 

766 is_book_member: bool, 

767 is_currently_invested: bool, 

768) -> bool: 

769 """V5.5.0 (Problems.md #128) - which held positions the BOOK opened, as 

770 opposed to the legacy-signal sleeve. Mutates `owned` in place and returns 

771 whether `symbol_key` is book-owned after the update: invested AND a member 

772 this bar adds it; a flat symbol is dropped; an invested non-member keeps 

773 whatever status it already had (that is exactly the rotated-out case).""" 

774 if not is_currently_invested: 

775 owned.discard(symbol_key) 

776 return False 

777 if is_book_member: 

778 owned.add(symbol_key) 

779 return symbol_key in owned 

780 

781 

782def is_rotation_exit_candidate( 

783 is_currently_invested: bool, 

784 sleeve_enabled: bool, 

785 is_book_owned: bool, 

786) -> bool: 

787 """V5.5.0 (Problems.md #128) - may the rotation exit force-sell this 

788 position when the book is active and did not select it? 

789 

790 should_exit_non_selected_book_symbol() was documented as applying to a 

791 symbol "previously book-selected" but applied to EVERY invested non-member. 

792 With the legacy sleeve on, that would liquidate a sleeve entry the very 

793 next bar (and, with exits no longer blocked by the trade cooldown, 

794 re-enter and re-exit it - pure churn), so the sleeve's positions must be 

795 left to the non-model exits (max holding age, trailing stop) and their 

796 own sell signal. With the sleeve OFF this is the pre-V5.5.0 rule 

797 unchanged: every invested non-member is a candidate.""" 

798 if not is_currently_invested: 

799 return False 

800 return is_book_owned if sleeve_enabled else True 

801 

802 

803def should_hold_owned_position_on_veto( 

804 enabled: bool, 

805 is_book_member: bool, 

806 is_book_owned: bool, 

807 is_currently_invested: bool, 

808 book_is_active: bool, 

809) -> bool: 

810 """V5.5.0 (Problems.md #133) - while the book is VETOED (empty allocations: 

811 spread / rolling-IC gate), a position the book opened must be HELD, not 

812 handed to the legacy probability signal. Live never liquidates on a veto 

813 (should_exit_non_selected_book_symbol needs an active book) and the 

814 offline as-live simulator holds through one (`hold_positions_on_veto`), 

815 but main.py let the legacy signal manage those positions: its next 

816 "sell" closed them, so book positions lasted ~6 days instead of the 

817 designed ~20+ (and shorts were re-sized to legacy weights). Only the 

818 max-holding / trailing-stop backstops and the next ACTIVE book's rotation 

819 exit may close an owned position. Off (False) reproduces pre-V5.5.0.""" 

820 return bool(enabled and is_book_owned and is_currently_invested and not is_book_member and not book_is_active) 

821 

822 

823def build_book_history_record( 

824 date_str: str, 

825 book_allocations: dict[str, BookAllocation], 

826 raw_scores_by_symbol: dict[str, float], 

827 target_weights_by_symbol: dict[str, float], 

828 sector_by_symbol: dict[str, str], 

829 rank_signal_policy: dict[str, Any], 

830 full_universe_signals: dict[str, dict] | None = None, 

831 book_member_decisions: dict[str, dict] | None = None, 

832 gate_veto_reason: str | None = None, 

833 feature_snapshot: dict[str, dict] | None = None, 

834 run_id: str | None = None, 

835 rolling_ic_state: dict[str, Any] | None = None, 

836 member_probabilities: dict[str, dict] | None = None, 

837) -> dict[str, Any]: 

838 """V5.2.2 (development/Problems.md) - a diagnostic snapshot of one 

839 rebalance bar's book, for `main.py`'s optional (config-gated, off by 

840 default, backtest-only) book-history log. Exists to make a real, 

841 ground-truth reconciliation possible between what a live/backtest run 

842 actually selected and what `evaluation/rank_book_simulator.py`'s 

843 offline simulator would select for the identical date - the tool 

844 this project needed after six other hypotheses for a large live-vs- 

845 offline Sharpe gap were tested and ruled out without finding the 

846 cause (see Problems.md #89-#90). 

847 

848 Pure: no I/O, no `self`, never raises on well-formed inputs - every 

849 per-symbol field degrades via `.get(..., None)` rather than 

850 `KeyError`, since a symbol missing from `raw_scores_by_symbol` or 

851 `target_weights_by_symbol` (e.g. `target_weight` is never populated 

852 when `phase_v2.portfolio_book.neutrality.enabled` is False - see 

853 `BookAllocation.target_weight`'s own `None`-means-"not applicable" 

854 convention) is expected, not exceptional. 

855 

856 `rank_signal_policy` (main.py's own `self._rank_signal_policy`, 

857 resolved once in `Initialize()`) is embedded INLINE in every record, 

858 not referenced externally - deliberately, so the log stays self- 

859 contained and correctly interpretable even if config or training 

860 metrics change between when a run produced this line and when a 

861 later reconciliation reads it back. 

862 

863 `full_universe_signals` (V5.2.3, opt-in via 

864 `phase_v2.diagnostics.book_history.include_full_universe`): `None` 

865 (default) reproduces this function's exact V5.2.2 return shape - no 

866 `"universe"` key at all, so every existing caller/log consumer is 

867 unaffected. When given `{symbol: {"raw_rank_score", "feature_ready", 

868 "reason", "trading_eligible", "security_type"}}` (main.py's own Phase 

869 1a `signals` payload, one entry per symbol with a bar this tick, 

870 selected or not), adds a `"universe"` key with the same shape - 

871 closes the exact gap that made the V5.2.2 tool unable to see WHY a 

872 symbol was never selected (e.g. crypto/FX consistently absent from 

873 every live book - Problems.md #91): the V5.2.2 log only ever recorded 

874 `book_allocations`, i.e. symbols that already made the cut, with no 

875 way to see what score/readiness a NON-selected symbol had that day. 

876 Each per-symbol sub-dict degrades the same `.get(..., None)` way as 

877 every other field here - a caller-supplied dict missing a key never 

878 raises. 

879 

880 `book_member_decisions` (V5.2.6, opt-in via 

881 `phase_v2.diagnostics.book_history.include_decisions`): `None` 

882 (default) reproduces this function's exact pre-V5.2.6 return shape - 

883 no `"book_member_decisions"` key at all, same convention as 

884 `full_universe_signals`. When given 

885 `{symbol: MarketAnalysisDecision.to_dict()}` (main.py's own Pass 2, 

886 collected per book member as each symbol's decision is computed), 

887 adds a `"book_member_decisions"` key recording each book member's 

888 final `action`/`reasons` - closes the gap where a symbol could be 

889 logged here as "selected" via `book_allocations` even though it was 

890 later diverted to `simulate`/`reduce_risk`/`retrain_candidate` by a 

891 risk/execution gate `book_allocations` alone can never reveal (see 

892 development/Problems.md - the crypto/FX zero-order-execution 

893 finding). 

894 

895 `gate_veto_reason` (V5.3.5, development/Problems.md #102): `None` 

896 (default) omits the key entirely, same convention as the two fields 

897 above. When main.py calls this on a genuine rebalance bar whose 

898 `build_rank_based_book()` call came back empty, it passes the 

899 `veto_reason_out["reason"]` string that call populated (see 

900 `_select_book_group()`'s own docstring) - without this, a vetoed 

901 rebalance bar left ZERO trace in this log (the write was gated on 

902 `book_allocations` being truthy), making it impossible to tell from 

903 the log alone whether a disengaged stretch came from 

904 `min_rank_confidence_spread` or the new rolling-IC gate, or anything 

905 else. main.py now writes a record on every genuine rebalance bar 

906 regardless of whether `book_allocations` came back empty. 

907 

908 `feature_snapshot` (V5.3.5.3 Workstream B, development/Problems.md 

909 #91/#100): `None` (default) omits the key entirely, same convention 

910 as the three fields above. When given `{symbol: {feature: value}}` 

911 (main.py's own `pass1_state[symbol]["feature_payload"]["base_features"]` 

912 dict, captured ONLY for the symbols in 

913 `phase_v2.diagnostics.book_history.feature_snapshot_symbols`'s 

914 allowlist and only when 

915 `phase_v2.diagnostics.book_history.include_feature_snapshot` is on), 

916 adds a `"feature_snapshot"` key - the raw per-feature values the live 

917 model actually saw for those symbols that bar. Exists so 

918 `evaluation/feature_reconciliation.py::reconcile_feature_snapshot()` 

919 can diff these against the same (ticker, date) row of 

920 `ml/datasets/full_dataset.csv`: XOM is the one tracked ticker whose 

921 live-vs-offline book-selection mismatch never resolved across 

922 #91/#97/#99/#100, and until this field existed there was nothing in 

923 the log to diff feature-by-feature. Allowlist-bounded by design - 

924 without it every bar would serialize ~77 symbols x dozens of floats, 

925 ballooning this log for a diagnostic only ever needed for a handful 

926 of tickers. 

927 

928 `run_id` (V5.7.0): the backtest's start stamp; `None` omits the key. Lets the audit and reconcile tools select a 

929 run by id instead of guessing run boundaries from a date that goes backwards.""" 

930 record = { 

931 "date": date_str, 

932 "rank_signal_policy": { 

933 "heads": dict(rank_signal_policy.get("heads", {})), 

934 "model_priority": list(rank_signal_policy.get("model_priority", [])), 

935 "demoted": list(rank_signal_policy.get("demoted", [])), 

936 "normalization": rank_signal_policy.get("normalization", "cross_sectional"), 

937 }, 

938 "allocations": { 

939 symbol_key: { 

940 "role": allocation.role, 

941 "book_role_multiplier": allocation.book_role_multiplier, 

942 "predicted_rank_20d": allocation.predicted_rank_20d, 

943 "rank_head": allocation.rank_head, 

944 "raw_rank_score": raw_scores_by_symbol.get(symbol_key), 

945 "target_weight": target_weights_by_symbol.get(symbol_key), 

946 "sector": sector_by_symbol.get(symbol_key, "Unknown"), 

947 } 

948 for symbol_key, allocation in book_allocations.items() 

949 }, 

950 } 

951 if full_universe_signals is not None: 

952 record["universe"] = { 

953 symbol_key: { 

954 "raw_rank_score": signal.get("raw_rank_score"), 

955 "feature_ready": signal.get("feature_ready"), 

956 "reason": signal.get("reason"), 

957 "trading_eligible": signal.get("trading_eligible"), 

958 "security_type": signal.get("security_type"), 

959 } 

960 for symbol_key, signal in full_universe_signals.items() 

961 } 

962 if book_member_decisions is not None: 

963 record["book_member_decisions"] = { 

964 symbol_key: { 

965 "action": decision.get("action"), 

966 "reasons": list(decision.get("reasons", [])), 

967 } 

968 for symbol_key, decision in book_member_decisions.items() 

969 } 

970 if gate_veto_reason is not None: 

971 record["gate_veto_reason"] = gate_veto_reason 

972 if rolling_ic_state is not None: 

973 # The gate's reading itself, so an offline replay can compare values, not only veto / no veto (V6.1.0). 

974 mean_ic = rolling_ic_state.get("rolling_mean_ic") 

975 record["rolling_ic"] = { 

976 "rolling_mean_ic": float(mean_ic) if isinstance(mean_ic, (int, float)) and math.isfinite(mean_ic) else None, 

977 "num_resolved_dates": rolling_ic_state.get("num_resolved_dates"), 

978 } 

979 if feature_snapshot is not None: 

980 record["feature_snapshot"] = { 

981 symbol_key: dict(snapshot) if isinstance(snapshot, Mapping) else snapshot 

982 for symbol_key, snapshot in feature_snapshot.items() 

983 } 

984 if run_id is not None: 

985 record["run_id"] = str(run_id) 

986 if member_probabilities is not None: 

987 record["member_probabilities"] = { 

988 symbol_key: {key: _finite_or_none(value) for key, value in probabilities.items()} 

989 for symbol_key, probabilities in member_probabilities.items() 

990 } 

991 return record 

992 

993 

994def _finite_or_none(value) -> float | None: 

995 return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) else None 

996 

997 

998def book_history_mode_allowed(runtime_mode: str, enabled: bool, paper_enabled: bool = False) -> tuple[bool, bool]: 

999 """(write the book history this rebalance?, bounded record). Backtests log the full record; `paper_enabled` (V6.4.0, 

1000 default off) also logs paper runs with the bounded record (no full universe, no feature snapshot: one small line per 

1001 rebalance); live never logs. Disabled = nothing.""" 

1002 if not enabled: 

1003 return False, False 

1004 if runtime_mode == "backtest": 

1005 return True, False 

1006 if runtime_mode == "paper" and paper_enabled: 

1007 return True, True 

1008 return False, False 

1009 

1010 

1011def _positive_cap(entry: dict, key: str) -> float | None: 

1012 try: 

1013 value = float(entry.get(key, 0.0)) 

1014 except (TypeError, ValueError): 

1015 return None 

1016 return value if value > 0.0 and value == value and value != float("inf") else None 

1017 

1018 

1019def resolve_class_weight_caps(raw: dict[str, Any] | None) -> dict[str, dict]: 

1020 """`phase_v2.class_weight_caps` -> {asset_class: {"per_name_cap", "class_gross_cap", "exempt"}} for the enabled classes. 

1021 Absent/empty = no caps (the pre-V5.8.0 behaviour). A cap of 0 or less means "no cap on that dimension".""" 

1022 caps: dict[str, dict] = {} 

1023 for asset_class, entry in (raw or {}).items(): 

1024 if not isinstance(entry, dict) or not bool(entry.get("enabled", True)): 

1025 continue 

1026 per_name, gross = _positive_cap(entry, "per_name_cap"), _positive_cap(entry, "class_gross_cap") 

1027 if per_name is None and gross is None: 

1028 continue 

1029 caps[str(asset_class)] = {"per_name_cap": per_name, "class_gross_cap": gross, "exempt": frozenset(map(str, entry.get("exempt", ())))} 

1030 return caps 

1031 

1032 

1033def crypto_core_only_settings(class_weight_caps_config: dict[str, Any] | None) -> tuple[bool, frozenset[str]]: 

1034 """(core_only, core names) from `phase_v2.class_weight_caps.crypto`: `core_only` (V6.4.0, default false, lead L9) keeps the 

1035 crypto pairs that are not `exempt` (the proven core, BTC / LTC) out of the main book's candidates.""" 

1036 entry = (class_weight_caps_config or {}).get("crypto") 

1037 if not isinstance(entry, dict): 

1038 return False, frozenset() 

1039 return bool(entry.get("core_only", False)), frozenset(map(str, entry.get("exempt", ()))) 

1040 

1041 

1042def crypto_graduate_excluded(ticker: str, asset_class: str | None, core_only: bool, core_names: frozenset[str]) -> bool: 

1043 """True when `core_only` is on and `ticker` is a crypto pair outside the core: it takes no book slot or neutrality weight. 

1044 One definition for main.py's live candidates and the offline simulator's candidate metadata.""" 

1045 return bool(core_only) and asset_class == "crypto" and str(ticker) not in core_names 

1046 

1047 

1048def apply_class_weight_caps( 

1049 weights: dict[str, float], asset_class_by_symbol: dict[str, str | None], caps: dict[str, dict] 

1050) -> dict[str, float]: 

1051 """V5.8.0: bounds the book weights of a class — each name to `per_name_cap`, then the class to `class_gross_cap` 

1052 (proportional scale-down) — leaving `exempt` names (the proven core, e.g. BTC/LTC) and every other class untouched. 

1053 Used for the names that must trade without a proven edge (the 10 crypto pairs that became eligible with the 

1054 extended window). Capping a leg of a dollar-neutral book can leave a small net exposure; the sizing chain and the 

1055 kill switch run after this, exactly as live and as-live both do. Pure; input is not mutated.""" 

1056 if not caps: 

1057 return dict(weights) 

1058 result = dict(weights) 

1059 for asset_class, cap in caps.items(): 

1060 names = [s for s in result if asset_class_by_symbol.get(s) == asset_class and s not in cap["exempt"]] 

1061 if cap["per_name_cap"] is not None: 

1062 for symbol in names: 

1063 result[symbol] = max(-cap["per_name_cap"], min(cap["per_name_cap"], result[symbol])) 

1064 if cap["class_gross_cap"] is not None: 

1065 gross = sum(abs(result[s]) for s in names) 

1066 if gross > cap["class_gross_cap"] > 0.0: 

1067 scale = cap["class_gross_cap"] / gross 

1068 for symbol in names: 

1069 result[symbol] *= scale 

1070 return result