Coverage for inference/strategy_selector_inference.py: 100%
20 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"""Runtime inference for the learned multi-leg strategy-selector model
2(V4.7, development/Problems.md #29's own framing - a model that picks
3which enabled strategy to prefer, replacing/augmenting
4portfolio/options_strategy.py::order_enabled_strategies()'s static
5risk-tier-preference reordering).
7Pure Python, no numpy/sklearn at runtime - same "trained offline
8(train_strategy_selector.py), loaded as a plain JSON dict, degrades
9node-by-node (here: strategy-by-strategy) to an empty score dict when
10missing/malformed" split topology/learned_topology.py already establishes
11for the topology model. Never raises -
12risk/asset_class_router.py::route_multi_leg_option_sizing() falls back to
13today's exact order_enabled_strategies() ordering whenever this module
14returns {} (its only output when no trained model exists, which is the
15ONLY state this codebase can reach today - see train_strategy_selector.py's
16own module docstring for why: zero real option positions have ever
17traded, so there is no per-strategy realized-outcome data to train from
18yet).
19"""
21from __future__ import annotations
23FEATURE_KEYS = ("regime_risk_score", "regime_trend_score", "topology_correlation_strength")
26def build_strategy_selector_features(base_features: dict, topology: dict) -> dict[str, float]:
27 """Pure, degrade-to-0.0 feature extraction reusing values main.py
28 already computes every bar (base_features["regime_signal_risk_score"/
29 "regime_signal_trend_score"], topology["correlation_strength"]) -
30 deliberately NOT a new computation path, so this feature vector stays
31 in lockstep with whatever the main probability model itself already
32 sees, and needs no additional per-bar state. Never raises on a
33 missing key. Key names here (bare, e.g. "regime_risk_score") match
34 train_strategy_selector.py's own extraction from a persisted
35 option_strategy_outcome event's regime/topology sub-payloads (which
36 use the SAME bare key names main.py's regime_payload/topology_payload
37 dicts do, before base_features's own "regime_signal_"/"topology_"
38 prefixing) - the trainer and this runtime scorer must always agree on
39 FEATURE_KEYS; this module owns that contract for the runtime side."""
40 return {
41 "regime_risk_score": float(base_features.get("regime_signal_risk_score", 0.0) or 0.0),
42 "regime_trend_score": float(base_features.get("regime_signal_trend_score", 0.0) or 0.0),
43 "topology_correlation_strength": float((topology or {}).get("correlation_strength", 0.0) or 0.0),
44 }
47def score_strategies(model: dict | None, features: dict[str, float]) -> dict[str, float]:
48 """model is train_strategy_selector.py's own strategy_selector_model.json
49 payload: {"strategy_names": [...], "scorers": {name: {"weights":
50 {feature_key: w}, "bias": b}}, "feature_keys": [...]}. Returns {}
51 (never raises) when model is None/empty/malformed - the exact
52 byte-identical-default trigger
53 risk/asset_class_router.py::route_multi_leg_option_sizing() relies on
54 (falls back to order_enabled_strategies() whenever this is falsy).
55 Otherwise a plain linear score per strategy_name: bias + sum(weight *
56 feature_value) - deliberately simple (this is a brand-new,
57 realistically-always-under-threshold data stream, per
58 train_strategy_selector.py's own docstring - not worth a more complex
59 runtime scorer until real training data exists to justify one)."""
60 if not model:
61 return {}
62 scorers = model.get("scorers")
63 if not scorers:
64 return {}
66 scores: dict[str, float] = {}
67 for strategy_name, scorer in scorers.items():
68 try:
69 weights = scorer.get("weights", {})
70 bias = float(scorer.get("bias", 0.0))
71 score = bias + sum(float(weights.get(key, 0.0)) * float(value) for key, value in features.items())
72 except (TypeError, ValueError, AttributeError):
73 continue
74 scores[strategy_name] = score
75 return scores