Coverage for risk/asset_class_router.py: 100%
136 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"""Single dispatch point routing a symbol's position sizing to the right
2asset-class-specific model, while every downstream consumer
3(portfolio/book_construction.py, liquidity, analyzer, main.py::_apply_signal())
4keeps working against ONE shared PositionSizingDecision shape
5(risk/position_sizing.py:13-28) regardless of which asset class produced it.
7Design: equity/crypto/bond all resolve via the EXISTING, unchanged
8build_dynamic_position_sizing() - bonds get no new sizing formula in this
9pass, only better upstream features (features/bond_features.py); a
10duration-sensitive ETF is still correctly modeled as a vol-scaled weight on
11a liquid, longable-only instrument. future/option resolve via
12risk/futures_risk.py / portfolio/options_strategy.py, then get ADAPTED
13onto the shared PositionSizingDecision shape by the two functions below.
15The adapters can't express everything a futures/options decision carries
16(an integer contract_count, a specific option contract) inside
17PositionSizingDecision's fixed field set - route_position_sizing() returns
18a (PositionSizingDecision, extra) pair, where `extra` carries whatever
19asset-class-specific raw decision main.py::_apply_signal() needs to place
20the RIGHT kind of order (MarketOrder(symbol, contract_count) for futures,
21vs. SetHoldings(symbol, target_weight) for everything else) - `extra` is
22empty for equity/crypto/bond, so existing callers that only ever look at
23the PositionSizingDecision stay completely unaffected.
24"""
26from __future__ import annotations
28from typing import TYPE_CHECKING, Any
30from risk.forex_risk import ForexSizingDecision, build_forex_position_sizing
31from risk.futures_risk import FuturesSizingDecision, build_futures_position_sizing
32from risk.position_sizing import PositionSizingDecision, build_dynamic_position_sizing
34if TYPE_CHECKING:
35 from collections.abc import Iterable, Mapping
36 from datetime import date, datetime
37 from pathlib import Path
39from portfolio.options_arbitrage_detector import build_arbitrage_position_sizing
40from portfolio.options_margin_sizing import build_margin_position_sizing
41from portfolio.options_strategy import (
42 MULTI_LEG_STRATEGY_REGISTRY,
43 build_multi_leg_position_sizing,
44 build_options_position_sizing,
45 build_vertical_spread_position_sizing,
46 group_chain_by_expiry,
47 order_enabled_strategies,
48 rerank_enabled_strategies_by_score,
49 strategies_for_volatility_view,
50)
52FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME = "not_applicable_non_volatility_sizing"
55def _futures_decision_to_position_sizing(decision: FuturesSizingDecision) -> PositionSizingDecision:
56 """Maps FuturesSizingDecision onto PositionSizingDecision's exact field
57 set. volatility fields are 0.0/sentinel-string (futures sizing isn't
58 volatility-driven at all - a real 0.0, not a missing value).
59 leverage_factor repurposes its existing "how much of the cap did we
60 use" semantic as margin_utilization / max_margin_utilization."""
61 max_margin_utilization = decision.max_margin_utilization or 1.0
62 return PositionSizingDecision(
63 base_target_weight=decision.base_target_weight,
64 target_weight=decision.target_weight,
65 rolling_volatility=0.0,
66 annualized_volatility=0.0,
67 volatility_regime=FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME,
68 volatility_multiplier=0.0,
69 confidence_multiplier=decision.confidence_multiplier,
70 topology_multiplier=1.0,
71 leverage_factor=decision.margin_utilization / max_margin_utilization,
72 max_leverage=max_margin_utilization,
73 sizing_reason=decision.sizing_reason,
74 topology_sizing_reason="not_applicable_futures",
75 volatility_source="not_applicable",
76 rank_multiplier=1.0,
77 rank_sizing_reason="not_applicable_futures",
78 )
81def _forex_decision_to_position_sizing(decision: ForexSizingDecision) -> PositionSizingDecision:
82 """V4.6 - the Forex sibling of _futures_decision_to_position_sizing()
83 above, same mapping shape (volatility fields sentinel/zeroed - forex
84 sizing here isn't volatility-driven either; leverage_factor repurposes
85 "how much of the cap did we use" as margin_utilization /
86 max_leverage_utilization)."""
87 max_leverage_utilization = decision.max_leverage_utilization or 1.0
88 return PositionSizingDecision(
89 base_target_weight=decision.base_target_weight,
90 target_weight=decision.target_weight,
91 rolling_volatility=0.0,
92 annualized_volatility=0.0,
93 volatility_regime=FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME,
94 volatility_multiplier=0.0,
95 confidence_multiplier=decision.confidence_multiplier,
96 topology_multiplier=1.0,
97 leverage_factor=decision.margin_utilization / max_leverage_utilization,
98 max_leverage=max_leverage_utilization,
99 sizing_reason=decision.sizing_reason,
100 topology_sizing_reason="not_applicable_forex",
101 volatility_source="not_applicable",
102 rank_multiplier=1.0,
103 rank_sizing_reason="not_applicable_forex",
104 )
107def _options_decision_to_position_sizing(decision, portfolio_value: float, max_vega_budget_pct_of_equity: float) -> PositionSizingDecision:
108 """Maps target_delta -> volatility_multiplier's slot (delta IS the
109 options-world analogue of "how much of the underlying's move this
110 position captures"), and vega_budget_used / max budget ->
111 leverage_factor (same "how much of the cap did we use" semantic as the
112 futures adapter)."""
113 max_budget = max_vega_budget_pct_of_equity or 1.0
114 direction = 1.0 if decision.right == "call" else -1.0
115 return PositionSizingDecision(
116 base_target_weight=direction * decision.target_delta,
117 target_weight=direction * (decision.vega_budget_used),
118 rolling_volatility=0.0,
119 annualized_volatility=0.0,
120 volatility_regime=FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME,
121 volatility_multiplier=decision.actual_delta,
122 confidence_multiplier=1.0,
123 topology_multiplier=1.0,
124 leverage_factor=decision.vega_budget_used / max_budget,
125 max_leverage=max_budget,
126 sizing_reason=decision.sizing_reason,
127 topology_sizing_reason="not_applicable_options",
128 volatility_source="not_applicable",
129 rank_multiplier=1.0,
130 rank_sizing_reason="not_applicable_options",
131 )
134def _options_spread_decision_to_position_sizing(
135 decision, portfolio_value: float, max_vega_budget_pct_of_equity: float
136) -> PositionSizingDecision:
137 """Vertical-spread sibling of _options_decision_to_position_sizing()
138 above - same mapping semantics (net delta -> volatility_multiplier's
139 slot, net vega budget-used -> leverage_factor), spread-level instead
140 of single-leg. decision.net_vega is already a budget-used FRACTION
141 (see OptionsSpreadPositionDecision's own field docstring), not a raw
142 vega number - used directly here, matching how the single-leg
143 adapter above uses vega_budget_used directly too."""
144 max_budget = max_vega_budget_pct_of_equity or 1.0
145 direction = 1.0 if decision.legs[0].right == "call" else -1.0
146 return PositionSizingDecision(
147 base_target_weight=direction * decision.net_delta,
148 target_weight=direction * decision.net_vega,
149 rolling_volatility=0.0,
150 annualized_volatility=0.0,
151 volatility_regime=FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME,
152 volatility_multiplier=decision.net_delta,
153 confidence_multiplier=1.0,
154 topology_multiplier=1.0,
155 leverage_factor=decision.net_vega / max_budget,
156 max_leverage=max_budget,
157 sizing_reason=decision.sizing_reason,
158 topology_sizing_reason="not_applicable_options",
159 volatility_source="not_applicable",
160 rank_multiplier=1.0,
161 rank_sizing_reason="not_applicable_options",
162 )
165def _multi_leg_decision_to_position_sizing(
166 decision, portfolio_value: float, max_vega_budget_pct_of_equity: float
167) -> PositionSizingDecision:
168 """OptionsMultiLegPositionDecision sibling of
169 _options_spread_decision_to_position_sizing() above - N-leg
170 generalization of the identical net-delta/net-vega mapping. Direction
171 is read off the FIRST leg's right (matches the 2-leg adapter's own
172 "legs[0].right" convention) - a reasonable single-scalar proxy for a
173 decision this codebase's shared PositionSizingDecision shape can't
174 fully represent regardless of leg count, exactly the same limitation
175 the 2-leg adapter already documents."""
176 max_budget = max_vega_budget_pct_of_equity or 1.0
177 direction = 1.0 if decision.legs[0].right == "call" else -1.0
178 return PositionSizingDecision(
179 base_target_weight=direction * decision.net_delta,
180 target_weight=direction * decision.net_vega,
181 rolling_volatility=0.0,
182 annualized_volatility=0.0,
183 volatility_regime=FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME,
184 volatility_multiplier=decision.net_delta,
185 confidence_multiplier=1.0,
186 topology_multiplier=1.0,
187 leverage_factor=decision.net_vega / max_budget,
188 max_leverage=max_budget,
189 sizing_reason=decision.sizing_reason,
190 topology_sizing_reason="not_applicable_options",
191 volatility_source="not_applicable",
192 rank_multiplier=1.0,
193 rank_sizing_reason="not_applicable_options",
194 )
197def _margin_decision_to_position_sizing(decision, portfolio_value: float) -> PositionSizingDecision:
198 """MarginSizingDecision adapter - margin_utilization (already a
199 budget-used FRACTION, see options_margin_sizing.py) maps onto
200 leverage_factor/max_leverage exactly like the futures adapter's
201 margin_utilization/max_margin_utilization mapping above, since both
202 are genuinely margin-based sizing, not vega-based."""
203 direction = 1.0 if decision.legs[0].right == "call" else -1.0
204 return PositionSizingDecision(
205 base_target_weight=direction * decision.margin_utilization,
206 target_weight=direction * decision.margin_utilization,
207 rolling_volatility=0.0,
208 annualized_volatility=0.0,
209 volatility_regime=FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME,
210 volatility_multiplier=0.0,
211 confidence_multiplier=1.0,
212 topology_multiplier=1.0,
213 leverage_factor=decision.margin_utilization,
214 max_leverage=1.0,
215 sizing_reason=decision.sizing_reason,
216 topology_sizing_reason="not_applicable_options",
217 volatility_source="not_applicable",
218 rank_multiplier=1.0,
219 rank_sizing_reason="not_applicable_options",
220 )
223def route_multi_leg_option_sizing(
224 enabled_strategy_names: list[Any],
225 signal_name: str,
226 confidence: float,
227 available_chain: list[Any],
228 portfolio_value: float,
229 underlying_price: float,
230 volatility_view: str,
231 risk_tier_preference: str,
232 margin_family_enabled: bool,
233 *,
234 target_delta_at_full_confidence: float,
235 max_vega_budget_pct_of_equity: float,
236 short_leg_delta_offset: float,
237 contract_multiplier: float,
238 target_margin_utilization: float,
239 max_margin_utilization: float,
240 pct_of_underlying_value: float,
241 min_pct_of_underlying_value: float,
242 current_date: date | None = None,
243 risk_free_rate: float = 0.045,
244 arbitrage_detector_enabled: bool = False,
245 min_mispricing_bps: float = 15.0,
246 arbitrage_max_contracts_per_signal: int = 1,
247 strategy_selector_scores: dict[str, Any] | None = None,
248) -> tuple[PositionSizingDecision, dict] | None:
249 """V4.5 - the full-coverage sibling of route_position_sizing()'s
250 option branch: tries `enabled_strategy_names`, reordered by
251 order_enabled_strategies() (§9.2's priority-list semantic), stopping
252 at the FIRST candidate that actually sizes. "single_leg" has no
253 MULTI_LEG_STRATEGY_REGISTRY entry (it's not an OptionStrategies
254 factory) and is special-cased to the existing
255 build_options_position_sizing() path; every other name is looked up
256 in the registry and dispatched by risk_tier:
257 - "vega_budget" -> build_multi_leg_position_sizing() (this includes
258 bull_call_spread/bear_put_spread too when reached via this NEW
259 router - the registry-driven selector is provably identical
260 geometry to the OLD dedicated build_vertical_spread_position_sizing()
261 for those 2, see options_strategy.py's select_vertical_legs()).
262 - margin tiers -> build_margin_position_sizing(), but ONLY when
263 margin_family_enabled (§5's hard gate - main.py additionally
264 requires runtime_mode == "backtest" before ever setting this True,
265 see main.py's own gate).
266 - "covered_protective" -> skipped here entirely; main.py's
267 corrected cross-asset design sizes these separately (needs the
268 held EQUITY quantity, not available_chain alone - see
269 build_covered_protective_position_sizing()).
270 - "unreachable_arbitrage" -> always skipped, by design (§8).
272 strategy_selector_scores (V4.7, development/Problems.md #29's own
273 framing) - the learned strategy-selector model's live inference plug
274 point: when truthy (a trained model is loaded AND
275 phase_v2.strategy_selector.enabled), reranks enabled_strategy_names by
276 score (portfolio/options_strategy.py::rerank_enabled_strategies_by_score())
277 INSTEAD OF order_enabled_strategies()'s static risk-tier-preference
278 reordering. Defaults to None - the only value ever passed until both
279 conditions hold, reproducing today's exact ordered_names output
280 byte-identically. Either way, the actual per-strategy_name dispatch
281 loop below (leg construction, sizing, risk math) is completely
282 unchanged - only WHICH NAME IS TRIED FIRST can differ.
284 straddle/strangle/iron_condor/iron_butterfly shape families are
285 additionally gated to strategies_for_volatility_view(volatility_view)
286 - every other shape family (vertical, butterfly, calendar, backspread,
287 ladder, naked) is NOT volatility-gated at all, firing whenever it's
288 the enabled candidate and its own selector finds a usable chain
289 (§4's "within-bucket selection follows directly from the allowlist").
291 Returns None when nothing in the (possibly empty) enabled list sizes
292 - callers must treat that as "no option position this bar", same
293 degrade-to-absent contract as every other branch in this module."""
294 if strategy_selector_scores:
295 ordered_names = rerank_enabled_strategies_by_score(enabled_strategy_names, strategy_selector_scores)
296 else:
297 ordered_names = order_enabled_strategies(enabled_strategy_names, risk_tier_preference)
298 view_gated_families = {"straddle", "strangle", "iron_condor", "iron_butterfly"}
299 eligible_view_names = strategies_for_volatility_view(volatility_view)
301 # V4.9 Priority 3 - group the chain by expiry ONCE per routing call
302 # (not once per calendar-family candidate tried below) when at least
303 # one calendar-family strategy is actually in play this bar -
304 # group_chain_by_expiry()'s own O(n) cost is cheap, but this avoids
305 # paying it again for each calendar-family name order_enabled_strategies()/
306 # rerank_enabled_strategies_by_score() might try in the same bar.
307 # arbitrage_jelly_roll is the only OTHER shape family that would use
308 # this grouping, but it's permanently unreachable via this router's own
309 # "unreachable_arbitrage" branch below - never worth precomputing for.
310 precomputed_grouped_chain_by_expiry = None
311 if available_chain:
312 has_calendar_candidate = False
313 for name in ordered_names:
314 candidate_spec = MULTI_LEG_STRATEGY_REGISTRY.get(name)
315 if candidate_spec is not None and candidate_spec.shape_family == "calendar":
316 has_calendar_candidate = True
317 break
318 if has_calendar_candidate:
319 precomputed_grouped_chain_by_expiry = group_chain_by_expiry(available_chain)
321 for strategy_name in ordered_names:
322 if strategy_name == "single_leg":
323 decision = build_options_position_sizing(
324 signal_direction=signal_name,
325 confidence=confidence,
326 available_chain=available_chain or [],
327 portfolio_value=portfolio_value,
328 target_delta_at_full_confidence=target_delta_at_full_confidence,
329 max_vega_budget_pct_of_equity=max_vega_budget_pct_of_equity,
330 )
331 if decision is not None:
332 return (
333 _options_decision_to_position_sizing(decision, portfolio_value, max_vega_budget_pct_of_equity),
334 {"options_decision": decision},
335 )
336 continue
338 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name)
339 if spec is None or spec.risk_tier == "covered_protective":
340 continue
341 if spec.risk_tier == "unreachable_arbitrage":
342 # V4.6 (development/Problems.md #59/Roadmap) - the mispricing
343 # detector is the ONLY way one of the 6 arbitrage strategies
344 # ever becomes reachable: off by default
345 # (arbitrage_detector_enabled), and even when on, only fires
346 # for THIS bar's chain when select_arbitrage_signal() confirms
347 # a real, threshold-exceeding mispricing - never unconditionally
348 # just because the strategy_name is enabled.
349 if not arbitrage_detector_enabled:
350 continue
351 decision = build_arbitrage_position_sizing(
352 strategy_name, available_chain or [], current_date, risk_free_rate, min_mispricing_bps,
353 arbitrage_max_contracts_per_signal,
354 )
355 if decision is not None:
356 return (
357 _multi_leg_decision_to_position_sizing(decision, portfolio_value, max_vega_budget_pct_of_equity),
358 {"options_decision": decision},
359 )
360 continue
361 if spec.shape_family in view_gated_families and strategy_name not in eligible_view_names:
362 continue
364 if spec.risk_tier == "vega_budget":
365 selector_kwargs = {"short_leg_delta_offset": short_leg_delta_offset} if spec.shape_family == "vertical" else {}
366 decision = build_multi_leg_position_sizing(
367 strategy_name, signal_name, confidence, available_chain or [], portfolio_value,
368 target_delta_at_full_confidence, max_vega_budget_pct_of_equity,
369 grouped_chain_by_expiry=precomputed_grouped_chain_by_expiry, **selector_kwargs,
370 )
371 if decision is not None:
372 return (
373 _multi_leg_decision_to_position_sizing(decision, portfolio_value, max_vega_budget_pct_of_equity),
374 {"options_decision": decision},
375 )
376 continue
378 # margin tiers (margin_naked / margin_uncovered_leg / margin_bounded_backspread)
379 if not margin_family_enabled:
380 continue
381 decision = build_margin_position_sizing(
382 strategy_name, signal_name, confidence, available_chain or [], underlying_price, portfolio_value,
383 contract_multiplier, target_delta_at_full_confidence, target_margin_utilization, max_margin_utilization,
384 pct_of_underlying_value, min_pct_of_underlying_value,
385 )
386 if decision is not None:
387 return _margin_decision_to_position_sizing(decision, portfolio_value), {"options_decision": decision}
389 return None
392def _zero_position_sizing(reason: str) -> PositionSizingDecision:
393 return PositionSizingDecision(
394 base_target_weight=0.0,
395 target_weight=0.0,
396 rolling_volatility=0.0,
397 annualized_volatility=0.0,
398 volatility_regime=FUTURES_OPTIONS_SENTINEL_VOLATILITY_REGIME,
399 volatility_multiplier=0.0,
400 confidence_multiplier=0.0,
401 topology_multiplier=1.0,
402 leverage_factor=0.0,
403 max_leverage=0.0,
404 sizing_reason=reason,
405 topology_sizing_reason="not_applicable",
406 volatility_source="not_applicable",
407 rank_multiplier=1.0,
408 rank_sizing_reason="not_applicable",
409 )
412def resolve_asset_class_enabled(
413 asset_class: str | None,
414 futures_risk_enabled: bool,
415 options_risk_enabled: bool,
416 forex_risk_enabled: bool = True,
417) -> bool:
418 """True iff main.py may open/maintain a position in `asset_class`
419 right now (used by main.py's per-bar
420 _liquidate_positions_for_disabled_asset_classes() sweep).
422 Equity/crypto/bond (and any unrecognized asset_class) have NO
423 enable/disable flag anywhere in this codebase - always True for those,
424 by construction, matching route_position_sizing()'s own "fall back to
425 equity behavior for anything unrecognized" default above. future ->
426 futures_risk_enabled (phase_v2.futures_risk.enabled); option ->
427 options_risk_enabled (phase_v2.options_risk.enabled); forex ->
428 forex_risk_enabled (phase_v2.forex_risk.enabled, V4.6). Pure lookup,
429 never raises. forex_risk_enabled defaults True only to keep this
430 signature backward-compatible for any caller that hasn't been updated
431 to pass it explicitly - main.py's own call site always passes it."""
432 if asset_class == "future":
433 return futures_risk_enabled
434 if asset_class == "option":
435 return options_risk_enabled
436 if asset_class == "forex":
437 return forex_risk_enabled
438 return True
441def book_candidate_trading_eligible(
442 trading_eligible: bool,
443 asset_class: str | None,
444 futures_risk_enabled: bool,
445 options_risk_enabled: bool,
446 forex_risk_enabled: bool,
447) -> bool:
448 """Book-selection eligibility: a symbol of a disabled asset class (sizing zeroed, positions liquidated) must not
449 take a slot or neutrality weight in the long/short book it can never trade. One definition for main.py's live
450 candidates and the offline simulator's candidate metadata."""
451 return bool(trading_eligible) and resolve_asset_class_enabled(
452 asset_class, futures_risk_enabled, options_risk_enabled, forex_risk_enabled
453 )
456def should_liquidate_disabled_asset_class_position(asset_class_enabled: bool, is_invested: bool) -> bool:
457 """Pure predicate: True iff a currently-open position must be
458 liquidated purely because its asset class is disabled this bar -
459 independent of whatever buy/sell/hold signal this bar's model output
460 computed. Equity/crypto/bond positions can never satisfy this
461 (resolve_asset_class_enabled() always returns True for them, so a
462 caller never even reaches this predicate with asset_class_enabled=False
463 for those classes) - this predicate doesn't special-case class names
464 itself, it trusts asset_class_enabled as already resolved."""
465 return (not asset_class_enabled) and is_invested
468def route_position_sizing(
469 asset_class: str,
470 signal_name: str,
471 confidence: float,
472 base_target_weight: float,
473 *,
474 equity_crypto_kwargs: dict[str, Any] | None = None,
475 price: float = 0.0,
476 portfolio_value: float = 0.0,
477 contract_spec: dict[str, Any] | None = None,
478 futures_kwargs: dict[str, Any] | None = None,
479 pair_spec: dict[str, Any] | None = None,
480 forex_kwargs: dict[str, Any] | None = None,
481 available_chain: list[dict] | None = None,
482 options_kwargs: dict[str, Any] | None = None,
483) -> tuple[PositionSizingDecision, dict]:
484 """Dispatches on asset_class (falls back to "equity" behavior for any
485 unrecognized value - the existing, safest, most-tested path). Returns
486 (PositionSizingDecision, extra) - extra is {} for equity/crypto/bond,
487 {"contract_count": int} for future, {"lot_count": int} for forex
488 (V4.6),
489 {"options_decision": OptionsPositionDecision | OptionsSpreadPositionDecision}
490 for option (only when a position was actually sized; {} when the
491 asset-class-specific sizer returned no position, e.g. an empty options
492 chain because IB is disabled). options_kwargs["spread_strategy"]
493 ("single_leg" default, or "vertical") picks which sizer runs - default
494 reproduces the exact single-leg behavior every existing caller already
495 depends on, by construction."""
496 if asset_class == "future":
497 decision = build_futures_position_sizing(
498 base_target_weight=base_target_weight,
499 confidence=confidence,
500 price=price,
501 contract_spec=contract_spec,
502 portfolio_value=portfolio_value,
503 **(futures_kwargs or {}),
504 )
505 return _futures_decision_to_position_sizing(decision), {"contract_count": decision.contract_count}
507 if asset_class == "forex":
508 decision = build_forex_position_sizing(
509 base_target_weight=base_target_weight,
510 confidence=confidence,
511 price=price,
512 pair_spec=pair_spec,
513 portfolio_value=portfolio_value,
514 **(forex_kwargs or {}),
515 )
516 # Phase 4.8 - pair_spec is already resolved by the caller (main.py's
517 # self.forex_pair_specs.get(...)) and passed in above purely for
518 # build_forex_position_sizing()'s own sizing math - also surfacing
519 # it here in `extra` replaces the webui's previous raw "N forex
520 # lots" string with real pip/lot/leverage detail, at zero extra
521 # computation cost (same dict, no new lookup).
522 return _forex_decision_to_position_sizing(decision), {"lot_count": decision.lot_count, "pair_spec": pair_spec}
524 if asset_class == "option":
525 spread_strategy = (options_kwargs or {}).get("spread_strategy", "single_leg")
526 max_vega_budget = (options_kwargs or {}).get("max_vega_budget_pct_of_equity", 0.02)
528 if spread_strategy == "vertical":
529 # short_leg_delta_offset is legitimately accepted here but NOT
530 # by build_options_position_sizing() below - only
531 # spread_strategy itself is stripped, everything else passes
532 # through as-is.
533 vertical_kwargs = {k: v for k, v in (options_kwargs or {}).items() if k != "spread_strategy"}
534 spread_decision = build_vertical_spread_position_sizing(
535 signal_direction=signal_name,
536 confidence=confidence,
537 available_chain=available_chain or [],
538 portfolio_value=portfolio_value,
539 **vertical_kwargs,
540 )
541 if spread_decision is None:
542 return _zero_position_sizing("no_usable_vertical_spread_or_zero_signal"), {}
543 return (
544 _options_spread_decision_to_position_sizing(spread_decision, portfolio_value, max_vega_budget),
545 {"options_decision": spread_decision},
546 )
548 # single_leg (default): spread_strategy/short_leg_delta_offset are
549 # both stripped - build_options_position_sizing() accepts neither,
550 # and short_leg_delta_offset being present in config (e.g. for a
551 # future switch to "vertical") must never leak into this call and
552 # raise a TypeError.
553 single_leg_kwargs = {
554 k: v for k, v in (options_kwargs or {}).items() if k not in ("spread_strategy", "short_leg_delta_offset")
555 }
556 decision = build_options_position_sizing(
557 signal_direction=signal_name,
558 confidence=confidence,
559 available_chain=available_chain or [],
560 portfolio_value=portfolio_value,
561 **single_leg_kwargs,
562 )
563 if decision is None:
564 return _zero_position_sizing("no_usable_option_contract_or_zero_signal"), {}
565 return _options_decision_to_position_sizing(decision, portfolio_value, max_vega_budget), {"options_decision": decision}
567 # equity / crypto / bond / anything unrecognized: existing, unchanged path.
568 decision = build_dynamic_position_sizing(
569 base_target_weight=base_target_weight,
570 confidence=confidence,
571 **(equity_crypto_kwargs or {}),
572 )
573 return decision, {}
576def load_venue_listing_dates(path: str | Path) -> dict[str, dict]:
577 """{ticker: {"listed": "YYYY-MM-DD", "suspended": [["start", "end"], ...]}} from a JSON file
578 (data/reference/crypto_listing_dates.json, V5.8.0). Missing or unreadable file -> {} (no guard, the old behaviour)."""
579 import json
580 from pathlib import Path
582 try:
583 raw = json.loads(Path(path).read_text(encoding="utf-8"))
584 except (OSError, ValueError):
585 return {}
586 return {str(ticker): dict(entry) for ticker, entry in (raw.get("assets", raw) or {}).items() if isinstance(entry, dict)}
589def asset_listed_on_venue(ticker: str, on_date: date | datetime | str, listing_dates: dict[str, dict] | None) -> bool:
590 """False before a pair's venue listing date, from its delisting date on, or inside a suspension window (e.g. Coinbase suspended XRP from
591 2021-01-19 to 2023-07-13): a backtest must not trade a pair the exchange did not list. Tickers without an entry, and
592 an empty mapping, are always listed. `on_date` is a date/datetime or an ISO string."""
593 entry = (listing_dates or {}).get(str(ticker))
594 if not entry:
595 return True
596 day = str(on_date.isoformat() if hasattr(on_date, "isoformat") else on_date)[:10]
597 listed = entry.get("listed")
598 if listed and day < str(listed)[:10]:
599 return False
600 delisted = entry.get("delisted")
601 if delisted and day >= str(delisted)[:10]:
602 return False
603 return not any(len(window) == 2 and str(window[0])[:10] <= day < str(window[1])[:10] for window in entry.get("suspended") or ())
606def target_path_class_conflicts(
607 weight_tickers: Iterable[str],
608 class_by_ticker: Mapping[str, str],
609 *,
610 futures_enabled: bool,
611 options_enabled: bool,
612 forex_enabled: bool,
613) -> list[str]:
614 """The asset classes a weight file asks for that the per-bar disabled-class sweep would close again at once (V6.6.9, #384).
615 A weight row naming a forex pair while `phase_v2.forex_risk.enabled` is false opens it on one bar and liquidates it on the
616 next; the caller drops those names instead. Sorted, empty when nothing conflicts."""
617 conflicts = {
618 str(class_by_ticker[ticker])
619 for ticker in weight_tickers
620 if ticker in class_by_ticker
621 and not resolve_asset_class_enabled(class_by_ticker[ticker], futures_enabled, options_enabled, forex_enabled)
622 }
623 return sorted(conflicts)