Coverage for evaluation/live_parity.py: 100%
312 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""As-live inputs for `rank_book_simulator` (V5.5.0, Problems.md #128).
3The idealized offline rank book scored well while real Lean backtests lost
4money. A read-only trace of both paths found the simulator differed from
5`main.py` in ways that all flatter the offline number: a different rank head,
6a 0.05 (not 0.15) sector cap, hysteresis in raw-score (not percentile) units,
7no confidence-spread / rolling-IC gates, a vetoed book that LIQUIDATES instead
8of holding, equal (not confidence-weighted) weights, forex/crypto decided on
9the same day's row instead of the previous bar, and a flat cost model.
11This module turns a config + dataset into the keyword arguments that make
12`simulate_rank_book()` mirror the live path, WITHOUT changing the idealized
13default. Everything here is pure (pandas/numpy/stdlib, no torch) - same
14contract as the rest of the `evaluation` package.
15"""
17from __future__ import annotations
19import bisect
20import itertools
21import math
22from collections.abc import Iterable
23from pathlib import Path
25import pandas as pd
27from analyzer.market_analyzer import build_market_analysis_decision
28from evaluation.rank_book_simulator import DEFAULT_ASSUMED_PORTFOLIO_VALUE_USD
29from evaluation.rolling_ic_gate_calibration import build_event_buffer
30from evaluation.rolling_ic_series import make_rolling_ic_state_fn
31from execution.cost_model import build_net_edge_decision
32from liquidity.market_liquidity import TYPICAL_DAILY_DOLLAR_VOLUME_BY_TYPE, build_liquidity_decision, cap_spread_proxy
33from portfolio.book_construction import (
34 apply_book_weight_floor,
35 apply_hrp_weights,
36 build_book_raw_weights,
37 pct_returns_from_closes,
38)
39from portfolio.rolling_ic_gate import evaluate_rolling_ic_gate
40from risk.position_sizing import build_dynamic_position_sizing, cost_sizing_multiplier
41from risk.rl_sizing import build_rl_sizing_state, resolve_rl_shadow_guard, rl_excess_return, rl_shadow_guard_allows
43# Asset classes whose bar lands AFTER the equity-session tick (forex 19:00/20:00,
44# crypto ~midnight UTC): live decides them on the previous day's bar
45# (main.py on_data() "borrowed bar" path), so offline must too.
46LATE_BAR_ASSET_CLASSES = frozenset({"forex", "crypto"})
47# Cross-asset inputs are built from the bars available strictly before the tick, so for a late-bar symbol they belong to
48# the tick's own dataset row; the symbol's own price / volume / liquidity / sensitivity block is the previous row
49# (measured on BT1 and BT2 snapshots of ETHUSD and EURUSD, Problems.md #172).
50LATE_BAR_SAME_ROW_FEATURE_PREFIXES = (
51 "peer_", "alt_", "topology_", "cs_momentum_rank", "bond_yield_curve", "bond_credit_spread", "macro_crypto_risk_appetite",
52 "fx_carry", # FRED-dated like alt_: live reads the rate as of the tick's date, which is the dataset row D's value
53)
56# V6.0.0 `phase1.features.late_bar_cross_asset: "own_tick"`: the topology / peer / cross-sectional momentum payloads are the
57# symbol's own-tick ones, i.e. the previous dataset row's; only the FRED-dated and bond / macro-proxy blocks stay the tick's.
58OWN_TICK_PAYLOAD_PREFIXES = ("peer_", "topology_", "cs_momentum_rank")
61def late_bar_same_row_prefixes(config: dict | None) -> tuple[str, ...]:
62 mode = str(((config or {}).get("phase1", {}).get("features", {}) or {}).get("late_bar_cross_asset", "equity_tick"))
63 if mode != "own_tick":
64 return LATE_BAR_SAME_ROW_FEATURE_PREFIXES
65 return tuple(prefix for prefix in LATE_BAR_SAME_ROW_FEATURE_PREFIXES if prefix not in OWN_TICK_PAYLOAD_PREFIXES)
68def forex_monday_payload_only(offline_row: dict | None, same_row_prefixes: tuple[str, ...]) -> dict | None:
69 """A forex tick on a Monday holds Sunday's fill-forward bar, which has no dataset row (its previous row is Friday), so the
70 own-price block cannot be compared; only the payload / FRED-dated features of the merged row are."""
71 if offline_row is None:
72 return None
73 return {name: value for name, value in offline_row.items() if str(name).startswith(same_row_prefixes)}
76def forex_tick_holds_fill_forward_bar(tick_date: str, previous_row_date: str | None, holidays: frozenset[int] = frozenset()) -> bool:
77 """True when a forex tick on `tick_date` holds a Lean fill-forward bar: the calendar day before the tick (whose bar
78 closes at the tick's midnight) is an open day - not a Saturday, not a Lean market holiday - with no dataset row. That
79 covers Sunday before Monday and a weekday the zip has no bar for (2025-12-25, 2026-01-01); generalises the V6.0.0
80 Monday-only rule (V6.1.0)."""
81 from datetime import date as _date
82 from datetime import timedelta
84 held = _date.fromisoformat(str(tick_date)[:10]) - timedelta(days=1)
85 if held.weekday() == 5 or held.toordinal() in holidays:
86 return False
87 return str(previous_row_date or "")[:10] != held.isoformat()
90def late_bar_offline_row(
91 previous_row: dict | None, same_row: dict | None, same_row_prefixes: tuple[str, ...] = LATE_BAR_SAME_ROW_FEATURE_PREFIXES
92) -> dict | None:
93 """The dataset row a late-bar symbol's live features at tick D correspond to: the previous row, with the features
94 under `same_row_prefixes` taken from row D. None when the previous row is missing."""
95 if previous_row is None:
96 return None
97 merged = dict(previous_row)
98 merged.update({name: value for name, value in (same_row or {}).items() if str(name).startswith(same_row_prefixes)})
99 return merged
100ROOT_DIR = Path(__file__).resolve().parents[1]
103def lag_predictions_for_tickers(
104 frame: pd.DataFrame,
105 *,
106 prediction_column: str,
107 tickers: set[str] | frozenset[str],
108 ticker_column: str = "ticker",
109 date_column: str = "date",
110) -> pd.DataFrame:
111 """Return a copy of `frame` where, for each ticker in `tickers`, the
112 prediction on date D is the prediction made on that ticker's PREVIOUS
113 row (the first row becomes NaN and is dropped by the simulator). The
114 forward return column is deliberately left alone: the return is still
115 earned from D, but it is ranked on information that is one bar stale."""
116 lagged = frame.sort_values([ticker_column, date_column]).copy()
117 mask = lagged[ticker_column].astype(str).isin(set(map(str, tickers)))
118 shifted = lagged.groupby(ticker_column)[prediction_column].shift(1)
119 lagged.loc[mask, prediction_column] = shifted[mask]
120 return lagged.sort_index()
123def with_live_event_duplicates(
124 frame: pd.DataFrame, late_bar_tickers: set[str] | frozenset[str] | None, *, ticker_column: str = "ticker"
125) -> pd.DataFrame:
126 """The rolling-IC event rows as live records them (V6.1.0, Problems.md #196). Pass 1c appends an event for every pending
127 symbol on every tick, and a crypto pair is pending on BOTH its own midnight tick and the next equity tick (which re-scores
128 the same bar), both stamped with that day's `Time.date()` and the same close: a late-bar symbol therefore enters the event
129 buffer twice per date. Counting each once made the offline gate read +0.012 above the logged live value (same side of the
130 floor on 73% of dates); the doubled events bring it to correlation 0.98, offset -0.0003 and 92% on the same side."""
131 if not late_bar_tickers:
132 return frame
133 duplicated = frame[frame[ticker_column].astype(str).isin({str(t) for t in late_bar_tickers})]
134 if duplicated.empty:
135 return frame
136 return pd.concat([frame, duplicated], ignore_index=True)
139def make_rolling_ic_gate_fn(
140 frame: pd.DataFrame,
141 *,
142 raw_score_column: str,
143 gate_config: dict,
144 ticker_column: str = "ticker",
145 date_column: str = "date",
146 close_column: str = "close",
147 state_fn=None,
148 include_tickers: set[str] | frozenset[str] | None = None,
149 late_bar_tickers: set[str] | frozenset[str] | None = None,
150):
151 """A date -> gate-result callable for `rolling_ic_gate_fn`: the rolling-IC state as of that date (no lookahead)
152 run through main.py's own `evaluate_rolling_ic_gate()`. The state comes from `make_rolling_ic_state_fn`, which
153 equals `compute_rolling_ic_state()` on the events dated <= that date; it does not depend on the floor, so pass one
154 shared `state_fn` to build several floor variants without re-resolving anything. `include_tickers` (V5.8.0) keeps
155 only those tickers' events - main.py feeds the buffer from the main rank group only when ranking is grouped.
156 `late_bar_tickers` (V6.1.0) counts those tickers' events twice per date, as live records them
157 (`with_live_event_duplicates`), unless the config's `late_bar_event_count` is "once" (V6.2.0)."""
158 from portfolio.rolling_ic_gate import resolve_late_bar_event_count
160 config = dict(gate_config)
161 config["enabled"] = True
162 if state_fn is None:
163 if include_tickers is not None:
164 frame = frame[frame[ticker_column].astype(str).isin(set(map(str, include_tickers)))]
165 if resolve_late_bar_event_count(config) == "per_tick":
166 frame = with_live_event_duplicates(frame, late_bar_tickers, ticker_column=ticker_column)
167 state_fn = make_rolling_ic_state_fn(
168 build_event_buffer(
169 frame,
170 raw_score_column=raw_score_column,
171 ticker_column=ticker_column,
172 date_column=date_column,
173 close_column=close_column,
174 ),
175 horizon_days=int(config.get("horizon_days", 20)),
176 rolling_window_days=int(config.get("rolling_window_days", 40)),
177 min_names_per_date=int(config.get("min_names_per_date", 10)),
178 )
179 cache: dict[str, dict] = {}
181 def gate_fn(date: str) -> dict:
182 key = str(date)[:10]
183 if key not in cache:
184 cache[key] = evaluate_rolling_ic_gate(state_fn(key), config)
185 return cache[key]
187 return gate_fn
190def _finite(value, default: float = 0.0) -> float:
191 try:
192 number = float(value)
193 except (TypeError, ValueError):
194 return default
195 return number if math.isfinite(number) else default
198def build_live_member_weight_fn(
199 config: dict,
200 *,
201 security_type_by_ticker: dict[str, str],
202 nav: float = DEFAULT_ASSUMED_PORTFOLIO_VALUE_USD,
203 core_crypto_tickers: set[str] | frozenset[str] | None = None,
204 predicted_volatility_by_key: dict | None = None,
205 rl_model: dict | None = None,
206 daily_returns_by_date: dict[str, dict[str, float]] | None = None,
207 topology_inputs_fn=None,
208 use_live_analyzer: bool = False,
209):
210 """`member_weight_fn` for `simulate_rank_book`: the live per-member decision chain of `main.py`'s Pass 2 built
211 from the SAME pure functions (nothing re-derived here): dynamic sizing (`build_dynamic_position_sizing`), the
212 liquidity gate (`build_liquidity_decision` on the capped spread proxy), the reduce_size haircut, the net-edge
213 decision and cost multiplier, the book weight floor, then the analyzer's verdicts for a book member (min confidence,
214 liquidity block / thin market and a failing net edge on a new entry -> no trade; a held member keeps its weight).
216 Offline approximations, all conservative to document: no learned-topology multiplier unless `topology_inputs_fn`
217 ((symbol, date) -> {topology_source, topology_confidence, topology_disagreement} or None, see
218 topology.learned_topology.learned_sizing_inputs) supplies it, volatility comes from `rolling_volatility_20d` unless `predicted_volatility_by_key`
219 ({(date, ticker): value}) supplies the multitask head, RL sizing is whatever the config says, and the regime override
220 (Priority 2) uses the dataset's `regime_risk_off` flag.
222 V5.8.0 - RL sizing: with `rl_model` and `dynamic_risk.rl_sizing_enabled`, the member's sizing gets the same
223 `rl_model` / `rl_state` / multiplier range main.py passes to `build_dynamic_position_sizing` (state from the row's
224 raw feature columns, as train_rl_sizing.py builds it). With `dynamic_risk.rl_shadow_guard.enabled` the RL-vs-constant
225 excess return of the positions this function sized is accumulated per date from `daily_returns_by_date`
226 ({date: {ticker: target_return_1d}}) and `risk.rl_sizing.rl_shadow_guard_allows` switches RL off exactly as live.
228 V6.1.0 - `use_live_analyzer`: the verdict comes from `analyzer.market_analyzer.build_market_analysis_decision` itself
229 (the composite signal-quality score, topology isolation / elevation, the risk-off override at its configured
230 severity, liquidity and the net-edge gate, in live's priority order) with the regime / topology inputs rebuilt from
231 the dataset row; any action other than "trade" holds. The returned function also sizes a legacy-signal entry
232 (`confidence=` the probability signal's confidence, `is_book_selected=False`); without a predicted rank the net-edge
233 gate is skipped (fail-open, as `build_net_edge_decision` does for a missing rank)."""
234 phase_v2 = config.get("phase_v2", {})
235 risk = phase_v2.get("dynamic_risk", {})
236 book = phase_v2.get("portfolio_book", {})
237 costs = phase_v2.get("costs", {})
238 liquidity = phase_v2.get("liquidity", {})
239 phase6 = config.get("phase6", {}).get("risk", {})
240 max_position_weight = float(phase6.get("max_position_weight", 0.25))
241 min_confidence = phase6.get("min_confidence_to_trade_book_selected")
242 min_confidence = float(min_confidence if min_confidence is not None else phase6.get("min_confidence_to_trade", 0.12))
243 floor_fraction = float(book.get("sizing_floor_fraction", 0.0))
244 rank_sizing_applies = bool(book.get("rank_sizing_applies_to_members", True))
245 spread_caps = dict(liquidity.get("max_spread_proxy_by_type", {}))
246 fallback_ddv = {
247 str(kind): float(value)
248 for kind, value in liquidity.get("zero_volume_fallback_ddv_by_type", TYPICAL_DAILY_DOLLAR_VOLUME_BY_TYPE).items()
249 }
250 configured_cost_cap = liquidity.get("max_round_trip_cost_fraction")
251 thresholds = {
252 "thin_participation_threshold": float(liquidity.get("thin_participation_threshold", 0.002)),
253 "high_impact_participation_threshold": float(liquidity.get("high_impact_participation_threshold", 0.01)),
254 "blocked_participation_threshold": float(liquidity.get("blocked_participation_threshold", 0.05)),
255 "min_daily_dollar_volume": float(liquidity.get("min_daily_dollar_volume", 100_000.0)),
256 "high_impact_size_factor": float(liquidity.get("high_impact_size_factor", 0.5)),
257 "slippage_factor": float(liquidity.get("slippage_factor", 0.1)),
258 "max_round_trip_cost_fraction": float(configured_cost_cap) if configured_cost_cap is not None else None,
259 }
260 cost_sizing_enabled = bool(costs.get("cost_sizing_enabled", False))
261 min_cost_multiplier = float(costs.get("min_cost_multiplier", 0.25))
262 core = frozenset(core_crypto_tickers or ())
263 forex_enabled = bool(phase_v2.get("forex_risk", {}).get("enabled", False))
264 sizing_risk = phase_v2.get("dynamic_risk", {}) # main.py reads the topology sizing keys from dynamic_risk
265 topology_sizing_enabled = bool(sizing_risk.get("topology_sizing_enabled", True)) and topology_inputs_fn is not None
266 min_topology_multiplier = float(sizing_risk.get("min_topology_multiplier", 0.5))
267 max_topology_multiplier = float(sizing_risk.get("max_topology_multiplier", 1.0))
268 rl_enabled = bool(risk.get("rl_sizing_enabled", False)) and rl_model is not None
269 analyzer_config = phase_v2.get("market_analyzer", {})
270 regime_config = phase_v2.get("regime_detection", {}) # main.py's key (phase_v2.regime does not exist)
271 severity = regime_config.get("risk_off_override_min_severity")
272 book_floor = phase6.get("min_confidence_to_trade_book_selected")
273 analyzer_settings = {
274 "min_confidence_to_trade": float(phase6.get("min_confidence_to_trade", 0.12)),
275 "min_confidence_to_trade_book_selected": float(book_floor) if book_floor is not None else None,
276 "retrain_min_regime_confidence": float(analyzer_config.get("retrain_min_regime_confidence", 0.20)),
277 "low_regime_confidence_threshold": float(analyzer_config.get("low_regime_confidence_threshold", 0.35)),
278 "use_composite_signal_score": bool(analyzer_config.get("use_composite_signal_score", False)),
279 "risk_off_override_min_severity": float(severity) if severity is not None else None,
280 "topology_veto_applies_to_book_members": bool(phase_v2.get("topology", {}).get("elevated_veto_applies_to_book_members", True)),
281 }
282 rl_guard = resolve_rl_shadow_guard(risk.get("rl_shadow_guard"))
283 rl_state_holder: dict = {"history": [], "positions": {}, "last_date": None, "allows": True}
284 sorted_return_dates = sorted(daily_returns_by_date or {})
286 def _advance_rl_guard(date: str) -> None:
287 last = rl_state_holder["last_date"]
288 if last == date:
289 return
290 if last is not None and rl_guard["enabled"] and rl_state_holder["positions"]:
291 start = bisect.bisect_right(sorted_return_dates, last)
292 end = bisect.bisect_right(sorted_return_dates, date)
293 for day in sorted_return_dates[start:end]:
294 rl_state_holder["history"].append(
295 rl_excess_return(rl_state_holder["positions"], daily_returns_by_date.get(day, {}))
296 )
297 rl_state_holder["allows"] = rl_shadow_guard_allows(rl_state_holder["history"], rl_guard)
298 rl_state_holder["last_date"] = date
300 def member_weight_fn(*, symbol, date, base_weight, held_weight, predicted_rank=None, row, confidence=None,
301 is_book_selected=True, **_unused):
302 if rl_enabled:
303 _advance_rl_guard(str(date)[:10])
304 rank_known = predicted_rank is not None and math.isfinite(float(predicted_rank))
305 if not rank_known and confidence is None:
306 return held_weight
307 security_type = str(security_type_by_ticker.get(symbol, "equity"))
308 if security_type == "forex" and not forex_enabled:
309 return held_weight
310 if confidence is None:
311 confidence = min(1.0, abs(float(predicted_rank) - 0.5) * 2.0)
312 predicted_volatility = (predicted_volatility_by_key or {}).get((date, symbol))
313 rolling_volatility = _finite(row.get("rolling_volatility_20d"))
314 topology_inputs = (topology_inputs_fn(symbol, date) if topology_sizing_enabled else None) or {}
315 sizing = build_dynamic_position_sizing(
316 base_weight,
317 confidence,
318 rolling_volatility,
319 max_position_weight,
320 target_daily_volatility=float(risk.get("target_daily_volatility", 0.015)),
321 min_position_weight=float(risk.get("min_position_weight", 0.0)),
322 low_volatility_threshold=float(risk.get("low_volatility_threshold", 0.01)),
323 high_volatility_threshold=float(risk.get("high_volatility_threshold", 0.03)),
324 min_volatility_multiplier=float(risk.get("min_volatility_multiplier", 0.35)),
325 max_volatility_multiplier=float(risk.get("max_volatility_multiplier", 1.25)),
326 max_leverage=float(risk.get("max_leverage", 1.0)),
327 predicted_volatility=predicted_volatility,
328 use_predicted_volatility=bool(risk.get("use_predicted_volatility", False)),
329 predicted_rank_20d=float(predicted_rank) if rank_known else None,
330 rank_sizing_enabled=bool(risk.get("rank_sizing_enabled", False)) and rank_sizing_applies,
331 min_rank_multiplier=float(risk.get("min_rank_multiplier", 0.75)),
332 max_rank_multiplier=float(risk.get("max_rank_multiplier", 1.25)),
333 rl_model=rl_model if rl_enabled else None,
334 rl_state=build_rl_sizing_state(row, confidence) if rl_enabled else None,
335 rl_sizing_enabled=rl_enabled and rl_state_holder["allows"],
336 min_rl_multiplier=float(risk.get("min_rl_multiplier", 0.6)),
337 max_rl_multiplier=float(risk.get("max_rl_multiplier", 1.0)),
338 topology_source=topology_inputs.get("topology_source"),
339 topology_confidence=topology_inputs.get("topology_confidence"),
340 topology_disagreement=topology_inputs.get("topology_disagreement"),
341 min_topology_multiplier=min_topology_multiplier,
342 max_topology_multiplier=max_topology_multiplier,
343 )
344 target = float(sizing.target_weight)
345 rl_multiplier = float(sizing.rl_multiplier)
346 fallback = None
347 if security_type == "forex":
348 fallback = fallback_ddv.get("forex")
349 elif security_type == "crypto" and symbol in core:
350 fallback = fallback_ddv.get("crypto")
351 liquidity_decision = build_liquidity_decision(
352 close=_finite(row.get("close")),
353 volume=_finite(row.get("volume")),
354 target_weight=target,
355 portfolio_value=nav,
356 annualized_volatility=float(sizing.annualized_volatility),
357 security_type=security_type,
358 dynamic_spread=cap_spread_proxy(row.get("liquidity_spread_proxy"), security_type, spread_caps),
359 zero_volume_fallback_ddv=fallback,
360 **thresholds,
361 )
362 action = liquidity_decision.recommended_action
363 if action == "reduce_size":
364 target = float(liquidity_decision.adjusted_target_weight)
365 net_edge = build_net_edge_decision(
366 float(predicted_rank) if rank_known else None,
367 liquidity_decision.to_dict(),
368 abs(target - held_weight) * nav,
369 costs,
370 trade_direction=1 if target >= 0.0 else -1,
371 security_type=security_type,
372 )
373 multiplier, _reason = cost_sizing_multiplier(
374 net_edge.expected_edge_bps, net_edge.expected_cost_bps, cost_sizing_enabled, min_cost_multiplier
375 )
376 target *= multiplier
377 if floor_fraction > 0.0 and security_type not in ("future", "option", "forex"):
378 target = apply_book_weight_floor(target, base_weight, floor_fraction, skip_floor=(action == "reduce_size"))
379 invested = held_weight != 0.0
380 if use_live_analyzer:
381 decision = build_market_analysis_decision(
382 signal_name="buy" if target >= 0.0 else "short", confidence=float(confidence), probability_up=0.5,
383 target_weight=target, regime=_row_regime(row), gating={"decision_source": "blend"}, trading_eligible=True,
384 trade_lock_active=False, topology=_row_topology(row), liquidity=liquidity_decision.to_dict(),
385 min_confidence_to_trade=analyzer_settings["min_confidence_to_trade"],
386 retrain_min_regime_confidence=analyzer_settings["retrain_min_regime_confidence"],
387 low_regime_confidence_threshold=analyzer_settings["low_regime_confidence_threshold"],
388 use_composite_signal_score=analyzer_settings["use_composite_signal_score"],
389 is_currently_invested=invested, net_edge=net_edge.to_dict(), is_book_selected=bool(is_book_selected),
390 min_confidence_to_trade_book_selected=analyzer_settings["min_confidence_to_trade_book_selected"],
391 risk_off_override_min_severity=analyzer_settings["risk_off_override_min_severity"],
392 topology_veto_applies_to_book_members=analyzer_settings["topology_veto_applies_to_book_members"],
393 )
394 if decision.action != "trade":
395 return held_weight
396 if rl_enabled:
397 if target != 0.0:
398 rl_state_holder["positions"][symbol] = (target, rl_multiplier)
399 else:
400 rl_state_holder["positions"].pop(symbol, None)
401 return target
402 if confidence < min_confidence or action in ("block", "simulate_instead"):
403 return held_weight
404 if not invested and not net_edge.passes:
405 return 0.0
406 # analyzer Priority 2: risk_off overrides a directional trade only at the configured severity
407 if float(row.get("regime_risk_off", 0.0) or 0.0) > 0.5 and (
408 analyzer_settings["risk_off_override_min_severity"] is None
409 or _finite(row.get("regime_signal_risk_score")) <= -analyzer_settings["risk_off_override_min_severity"]
410 ):
411 return held_weight
412 if rl_enabled:
413 if target != 0.0:
414 rl_state_holder["positions"][symbol] = (target, rl_multiplier)
415 else:
416 rl_state_holder["positions"].pop(symbol, None)
417 return target
419 member_weight_fn.rl_state = rl_state_holder
420 return member_weight_fn
423def _row_regime(row: dict) -> dict:
424 """The analyzer's regime payload from a dataset row (the model-input regime vector, drawdown 0.0; live's risk
425 regime also reads the account drawdown, which an offline row cannot know)."""
426 risk_regime = "risk_neutral"
427 if float(row.get("regime_risk_off", 0.0) or 0.0) > 0.5:
428 risk_regime = "risk_off"
429 elif float(row.get("regime_risk_on", 0.0) or 0.0) > 0.5:
430 risk_regime = "risk_on"
431 return {
432 "risk_regime": risk_regime,
433 "risk_score": _finite(row.get("regime_signal_risk_score")),
434 "confidence": _finite(row.get("regime_signal_confidence")),
435 }
438def _row_topology(row: dict) -> dict:
439 """The analyzer's topology payload from a dataset row (its risk one-hots and correlation strength)."""
440 risk = "normal"
441 if float(row.get("topology_risk_isolated", 0.0) or 0.0) > 0.5:
442 risk = "isolated"
443 elif float(row.get("topology_risk_elevated", 0.0) or 0.0) > 0.5:
444 risk = "elevated"
445 return {"topology_risk": risk, "correlation_strength": _finite(row.get("topology_correlation_strength"))}
448def build_hrp_raw_weights_fn(
449 frame: pd.DataFrame,
450 *,
451 window_bars: int = 25,
452 gross_exposure: float = 1.0,
453 max_position_weight: float = 0.25,
454 ticker_column: str = "ticker",
455 date_column: str = "date",
456 close_column: str = "close",
457 session_dates: Iterable[str] | None = None,
458 next_bar_tickers: Iterable[str] = (),
459 linkage_method: str = "ward",
460):
461 """`raw_weights_fn` for the HRP book sizing path (`allocation_method="hrp"`): the live code feeds
462 `apply_hrp_weights` each member's last `window_bars` closes, and falls back to the rank formula when HRP returns nothing.
464 With `session_dates` (V6.6.9, #383) each ticker is sampled once per equity session, as `main.py`'s `_session_closes` is: an
465 equity's close on the session, a ticker in `next_bar_tickers` (crypto, forex) its last close dated before it. Without them each
466 ticker keeps its own bar calendar (the pre-V6.6.9 behaviour, kept so earlier results can be reproduced)."""
467 closes: dict[str, tuple[list[str], list[float]]] = {}
468 for ticker, group in frame.sort_values(date_column).groupby(ticker_column):
469 closes[str(ticker)] = ([str(d)[:10] for d in group[date_column]], [float(c) for c in group[close_column]])
470 if session_dates is not None:
471 sessions = sorted({str(day)[:10] for day in session_dates})
472 late = {str(ticker) for ticker in next_bar_tickers}
473 for ticker, (dates, values) in list(closes.items()):
474 side = bisect.bisect_left if ticker in late else bisect.bisect_right
475 sampled = []
476 for session in sessions:
477 end = side(dates, session)
478 sampled.append(values[end - 1] if end else float("nan"))
479 closes[ticker] = (sessions, sampled)
481 def raw_weights_fn(allocations, date):
482 key = str(date)[:10]
483 returns_by_symbol = {}
484 for symbol in allocations:
485 dates, values = closes.get(str(symbol), ([], []))
486 end = bisect.bisect_right(dates, key)
487 returns_by_symbol[symbol] = pct_returns_from_closes(values[max(0, end - window_bars) : end])
488 hrp = apply_hrp_weights(allocations, returns_by_symbol, gross_exposure=gross_exposure, linkage_method=linkage_method)
489 return dict(hrp) if hrp else build_book_raw_weights(allocations, max_position_weight)
491 return raw_weights_fn
494def build_impact_inputs_fn(
495 frame: pd.DataFrame,
496 *,
497 security_type_by_ticker: dict[str, str],
498 zero_volume_fallback_ddv_by_type: dict[str, float] | None = None,
499 ticker_column: str = "ticker",
500 date_column: str = "date",
501):
502 """`impact_inputs_fn` for the Almgren impact: (daily volatility, ADV in dollars) of one name on one date from the
503 dataset's own `rolling_volatility_20d` and `liquidity_log_dollar_volume`; volume-less classes use the configured
504 fallback ADV (the same one the liquidity gate uses)."""
505 fallback = dict(zero_volume_fallback_ddv_by_type or TYPICAL_DAILY_DOLLAR_VOLUME_BY_TYPE)
506 table: dict[tuple[str, str], tuple[float, float]] = {}
507 if not {"rolling_volatility_20d", "liquidity_log_dollar_volume"} <= set(frame.columns):
508 return lambda symbol, date: None # a frame without the liquidity columns charges no per-name impact
509 for ticker, date, volatility, log_dollar_volume in zip(
510 frame[ticker_column], frame[date_column], frame["rolling_volatility_20d"], frame["liquidity_log_dollar_volume"], strict=False
511 ):
512 adv = math.expm1(_finite(log_dollar_volume))
513 if adv <= 0.0:
514 adv = float(fallback.get(str(security_type_by_ticker.get(str(ticker), "equity")), 0.0))
515 table[(str(date)[:10], str(ticker))] = (_finite(volatility), adv)
517 def impact_inputs_fn(symbol, date):
518 return table.get((str(date)[:10], str(symbol)))
520 return impact_inputs_fn
523def build_live_mechanisms(
524 config: dict,
525 frame: pd.DataFrame,
526 *,
527 core_crypto_tickers: set[str] | frozenset[str] | None = None,
528 nav: float | None = None,
529 include: tuple[str, ...] = ("kill_switch", "member_sizing", "hrp", "impact"),
530 predicted_volatility_by_key: dict | None = None,
531 rl_model_path: str | None = None,
532 topology_inputs_fn=None,
533) -> dict:
534 """The optional live mechanisms of `build_as_live_kwargs`, built from the config: kill switch (+ whether a
535 trip latches, i.e. no backtest bypass), the member sizing/liquidity/net-edge chain, HRP weights when
536 `allocation_method == "hrp"`, and the per-name impact inputs. `include` lets a lever turn one off."""
537 phase_v2 = config.get("phase_v2", {})
538 book = phase_v2.get("portfolio_book", {})
539 assets = config.get("phase1", {}).get("universe", {}).get("assets", [])
540 security_types = {str(asset["ticker"]): str(asset.get("security_type", "equity")) for asset in assets}
541 portfolio_nav = float(nav) if nav else float(config.get("runtime", {}).get("initial_cash", 0) or 0)
542 if portfolio_nav <= 0.0:
543 portfolio_nav = DEFAULT_ASSUMED_PORTFOLIO_VALUE_USD
544 mechanisms: dict = {}
545 if "kill_switch" in include:
546 kill_switch = dict(phase_v2.get("risk", {}).get("kill_switch", {}))
547 mechanisms["kill_switch_config"] = kill_switch or None
548 mechanisms["kill_switch_sticky"] = not bool(phase_v2.get("backtest", {}).get("bypass_sticky_trade_lock", False))
549 if "member_sizing" in include and {"close", "volume", "rolling_volatility_20d"} <= set(frame.columns):
550 rl_model = None
551 daily_returns_by_date = None
552 if bool(phase_v2.get("dynamic_risk", {}).get("rl_sizing_enabled", False)):
553 from risk.rl_sizing import load_rl_sizing_model
555 rl_model = load_rl_sizing_model(Path(rl_model_path) if rl_model_path else ROOT_DIR / "ml" / "rl_sizing_model.json")
556 if "target_return_1d" in frame.columns:
557 daily_returns_by_date = {}
558 for date, ticker, value in zip(frame["date"].astype(str), frame["ticker"].astype(str), frame["target_return_1d"], strict=False):
559 if value == value:
560 daily_returns_by_date.setdefault(date[:10], {})[ticker] = float(value)
561 mechanisms["member_weight_fn"] = build_live_member_weight_fn(
562 config,
563 security_type_by_ticker=security_types,
564 nav=portfolio_nav,
565 core_crypto_tickers=core_crypto_tickers,
566 predicted_volatility_by_key=predicted_volatility_by_key,
567 rl_model=rl_model,
568 daily_returns_by_date=daily_returns_by_date,
569 topology_inputs_fn=topology_inputs_fn,
570 use_live_analyzer="analyzer" in include,
571 )
572 if "hrp" in include and str(book.get("allocation_method", "rank")) == "hrp":
573 mechanisms["raw_weights_fn"] = build_hrp_raw_weights_fn(
574 frame, max_position_weight=float(config.get("phase6", {}).get("risk", {}).get("max_position_weight", 0.25))
575 )
576 if "impact" in include:
577 mechanisms["impact_inputs_fn"] = build_impact_inputs_fn(
578 frame,
579 security_type_by_ticker=security_types,
580 zero_volume_fallback_ddv_by_type=phase_v2.get("liquidity", {}).get("zero_volume_fallback_ddv_by_type"),
581 )
582 return mechanisms
585def build_candidate_metadata(
586 asset_class_by_ticker: dict[str, str],
587 trading_eligible_by_ticker: dict[str, bool],
588) -> dict[str, dict]:
589 """{ticker: {"asset_class", "trading_eligible"}} - the per-symbol fields
590 main.py hands build_rank_based_book(), instead of the simulator's
591 default of forcing every row eligible with no asset class."""
592 tickers = set(asset_class_by_ticker) | set(trading_eligible_by_ticker)
593 return {
594 ticker: {
595 "asset_class": asset_class_by_ticker.get(ticker),
596 "trading_eligible": bool(trading_eligible_by_ticker.get(ticker, True)),
597 }
598 for ticker in tickers
599 }
602def build_as_live_kwargs(
603 base_kwargs: dict,
604 *,
605 book_config: dict,
606 exits_config: dict,
607 max_position_weight: float,
608 candidate_metadata: dict[str, dict],
609 rolling_ic_gate_fn=None,
610 topology_config: dict | None = None,
611 kill_switch_config: dict | None = None,
612 kill_switch_sticky: bool = False,
613 member_weight_fn=None,
614 raw_weights_fn=None,
615 impact_inputs_fn=None,
616 rank_group_by_ticker: dict[str, str] | None = None,
617 rank_signal_config: dict | None = None,
618 sector_relative_min_size: int = 3,
619 venue_listing_dates: dict[str, dict] | None = None,
620 class_weight_caps: dict[str, dict] | None = None,
621 next_open_fills: bool = False,
622 resize_threshold_weight: float = 0.0,
623 trade_cooldown_bars: int = 0,
624) -> dict:
625 """base_kwargs (idealized, from `phase1...net_performance`) + the live
626 overrides, read from `phase_v2.portfolio_book` / `phase_v2.exits` - the
627 ONE config source live uses (the idealized run reads net_performance, a
628 second source that had drifted: sector cap 0.05 vs 0.15).
630 V5.7.0: `hold_positions_on_veto` now follows `portfolio_book.hold_owned_positions_on_veto` (it was hardcoded True,
631 so flipping the config changed live but not this run). The optional live mechanisms (kill switch, member sizing /
632 liquidity / net-edge chain, HRP weights, per-name impact) are passed in already built; None leaves them off.
634 V6.0.0: `portfolio_book.per_asset_class_slots` goes to the same book builder live uses; `next_open_fills` makes a
635 decided order earn from the next open (the frame needs `add_next_intraday_return`); the resize threshold
636 (`functionality.position_scaling`), the entry cooldown (`phase6.risk.trade_cooldown_bars`) and the trailing stop
637 (`exits.trailing_stop_pct`) gate trades as live does."""
638 from portfolio.book_construction import normalize_per_asset_class_slots
640 neutrality = book_config.get("neutrality", {})
641 slots, _skipped = normalize_per_asset_class_slots(book_config.get("per_asset_class_slots"))
642 kwargs = dict(base_kwargs)
643 kwargs.update(
644 top_n=int(book_config.get("top_n", base_kwargs.get("top_n", 6))),
645 bottom_n=int(book_config.get("bottom_n", base_kwargs.get("bottom_n", 6))),
646 rebalance_every_bars=int(book_config.get("rebalance_every_bars", base_kwargs.get("rebalance_every_bars", 10))),
647 hysteresis_rank_margin=float(book_config.get("hysteresis_rank_margin", 0.0)),
648 dollar_neutral=bool(neutrality.get("dollar_neutral", base_kwargs.get("dollar_neutral", True))),
649 sector_neutral=bool(neutrality.get("sector_neutral", base_kwargs.get("sector_neutral", True))),
650 gross_exposure=float(neutrality.get("gross_exposure_cap", base_kwargs.get("gross_exposure", 1.0))),
651 max_weight_per_name=float(neutrality.get("max_weight_per_name", base_kwargs.get("max_weight_per_name", 0.12))),
652 sector_max_net_weight=float(neutrality.get("sector_max_net_weight", 0.15)),
653 reapply_sector_cap_after_dollar_neutral=bool(neutrality.get("reapply_sector_cap_after_dollar_neutral", False)),
654 entry_lag_bars=1,
655 candidate_metadata_by_ticker=candidate_metadata,
656 normalize_to_percentile=True,
657 min_rank_confidence_spread=float(book_config.get("min_rank_confidence_spread", 0.0)),
658 rolling_ic_gate_fn=rolling_ic_gate_fn,
659 live_weighting=True,
660 max_position_weight=float(max_position_weight),
661 hold_positions_on_veto=bool(book_config.get("hold_owned_positions_on_veto", True)),
662 # live's hysteresis anchor is the last NON-EMPTY book whether or not positions are held through a veto
663 hysteresis_anchor_on_formed_book=True,
664 retry_rebalance_after_veto=True,
665 kill_switch_config=kill_switch_config,
666 kill_switch_sticky=kill_switch_sticky,
667 member_weight_fn=member_weight_fn,
668 raw_weights_fn=raw_weights_fn,
669 impact_inputs_fn=impact_inputs_fn,
670 rank_group_by_ticker=rank_group_by_ticker or None,
671 sector_relative_rank=str((rank_signal_config or {}).get("normalization", "cross_sectional")) == "sector_relative",
672 sector_relative_min_size=int(sector_relative_min_size),
673 partial_adjust_fraction=float(book_config.get("tranche_adjust_fraction", 1.0)),
674 venue_listing_dates=venue_listing_dates or None,
675 class_weight_caps=class_weight_caps or None,
676 per_asset_class_slots=slots or None,
677 resize_threshold_weight=float(resize_threshold_weight),
678 trade_cooldown_dates=int(trade_cooldown_bars),
679 trailing_stop_pct=(
680 float(exits_config["trailing_stop_pct"])
681 if exits_config.get("enabled", False) and exits_config.get("trailing_stop_pct") is not None
682 else None
683 ),
684 intraday_next_return_column=NEXT_INTRADAY_RETURN_COLUMN if next_open_fills else None,
685 max_holding_dates=(
686 int(exits_config["max_holding_bars"])
687 if exits_config.get("enabled", False) and exits_config.get("max_holding_bars") is not None
688 else None
689 ),
690 # analyzer Priority 3 (elevated topology volatility) cancels new book entries unless the config exempts members.
691 entry_veto_column=(
692 "topology_risk_elevated" if (topology_config or {}).get("elevated_veto_applies_to_book_members", True) else None
693 ),
694 )
695 return kwargs
698NEXT_INTRADAY_RETURN_COLUMN = "next_intraday_return"
701def add_next_intraday_return(frame, *, ticker_column: str = "ticker", date_column: str = "date"):
702 """Adds `next_intraday_return`: each row's NEXT session close/open - 1 for the same ticker (NaN on its last row), the
703 part of `target_return_1d` an order decided on this row's close earns after filling at the next open."""
704 import numpy as np
706 ordered = frame.sort_values([ticker_column, date_column])
707 next_open = ordered.groupby(ticker_column)["open"].shift(-1)
708 next_close = ordered.groupby(ticker_column)["close"].shift(-1)
709 values = (next_close / next_open - 1.0).replace([np.inf, -np.inf], np.nan)
710 frame[NEXT_INTRADAY_RETURN_COLUMN] = values.reindex(frame.index)
711 return frame
714def build_rank_groups(config: dict, asset_class_by_ticker: dict[str, str]) -> dict[str, str] | None:
715 """{ticker: rank group} when `phase_v2.rank_signal.grouped_normalization` is on (main.py's `_rank_group_by_symbol`),
716 else None: the as-live run then ranks one pool exactly as before."""
717 from portfolio.rank_signal import rank_group_by_symbol
719 if not bool(config.get("phase_v2", {}).get("rank_signal", {}).get("grouped_normalization", False)):
720 return None
721 groups = config.get("phase1", {}).get("target", {}).get("ranking", {}).get("separate_rank_groups")
722 return rank_group_by_symbol(dict(asset_class_by_ticker), groups)
725def main_group_tickers(rank_groups: dict[str, str] | None, tickers) -> set[str] | None:
726 """Tickers whose events feed the rolling-IC gate (main group only), None when ranking is not grouped."""
727 from portfolio.rank_signal import MAIN_RANK_GROUP
729 if not rank_groups:
730 return None
731 return {str(ticker) for ticker in tickers if rank_groups.get(str(ticker), MAIN_RANK_GROUP) == MAIN_RANK_GROUP}
734def load_live_venue_listing_dates(config: dict, root_dir) -> dict[str, dict] | None:
735 """main.py's `venue_listing_dates`: the listing file when `phase_v2.venue_listing_guard.enabled`, else None."""
736 from pathlib import Path
738 from risk.asset_class_router import load_venue_listing_dates
740 guard = config.get("phase_v2", {}).get("venue_listing_guard", {})
741 if not guard.get("enabled", False):
742 return None
743 return load_venue_listing_dates(Path(root_dir) / guard.get("path", "data/reference/crypto_listing_dates.json")) or None
746def build_cash_sweep_kwarg(config: dict, root_dir, *, force_enabled: bool = False) -> dict | None:
747 """V6.2.0: `simulate_rank_book(cash_sweep=...)` from the live config, as main.py sizes the T-bill sweep: the ETF's
748 forward close-to-close return per date (the dataset's target_return_1d convention), Lean's security types, the
749 book's gross cap, live's short-exposure cap and the legacy / sleeve budgets at full size. None when the sweep is off
750 (unless `force_enabled`, for a what-if) or its data zip is missing."""
751 from evaluation.lean_attribution import LEAN_EQUITY_PRICE_SCALE, read_daily_closes
752 from portfolio.cash_sweep import resolve_cash_sweep_config
754 phase_v2 = config.get("phase_v2", {})
755 sweep = resolve_cash_sweep_config(phase_v2.get("cash_sweep"))
756 if not (sweep["enabled"] or force_enabled):
757 return None
758 closes = read_daily_closes(Path(root_dir) / sweep["data_path"], LEAN_EQUITY_PRICE_SCALE)
759 if not closes:
760 return None
761 dates = sorted(closes)
762 forward = {day: closes[after] / closes[day] - 1.0 for day, after in itertools.pairwise(dates) if closes[day] > 0}
763 legacy, bond, forex = phase_v2.get("legacy_sleeve", {}), phase_v2.get("bond_sleeve", {}), phase_v2.get("forex_risk", {})
764 other = float(legacy.get("max_gross_exposure", 0.0)) if legacy.get("enabled") else 0.0
765 neutral = (float(bond.get("gross_budget", 0.0)) if bond.get("enabled") else 0.0) + (
766 float(forex.get("gross_budget", 0.0)) if forex.get("enabled") else 0.0)
767 neutrality = (phase_v2.get("portfolio_book", {}) or {}).get("neutrality", {}) or {}
768 return {
769 "returns_by_date": forward,
770 "config": dict(sweep, enabled=True),
771 "security_type_by_ticker": {str(a["ticker"]): str(a.get("security_type", "equity")) for a in config["phase1"]["universe"]["assets"]},
772 "book_gross_cap": float(neutrality.get("gross_exposure_cap", 1.0)),
773 "max_short_exposure": float(config.get("phase9", {}).get("portfolio", {}).get("max_short_exposure", 0.30)),
774 "other_budget": other,
775 "neutral_budget": neutral,
776 "min_commission_usd": 1.0,
777 }