Coverage for portfolio/legacy_sleeve.py: 100%
70 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"""Capped "legacy signal" sleeve for the rank book (V5.5.0, Problems.md #128).
3Background: with the portfolio book enabled, every symbol the book does NOT
4select still ran the original probability-up signal path (`_derive_signal`).
5In the 2026-08-27 backtest 121 of 155 equity entries came from that old
6long-only path and only 33 from the book, so live equity was "the old signal
7plus the book's shorts", a strategy the offline rank-book simulation never
8modeled. This module keeps that path but puts it inside an explicit,
9measurable budget instead of letting it run unbounded:
11- a gross-exposure budget shared by every sleeve position,
12- a per-name weight cap,
13- no new sleeve entries while the book is vetoed (default).
15Pure and Lean-free: main.py calls `apply_legacy_sleeve_policy()` once per
16non-book symbol, the offline simulator reads the same config.
17"""
19from __future__ import annotations
21import math
22from typing import Any
24DEFAULT_LEGACY_SLEEVE_CONFIG = {
25 "enabled": False,
26 "max_gross_exposure": 0.10,
27 "max_weight_per_name": 0.02,
28 "trade_when_book_vetoed": False,
29}
32def resolve_legacy_sleeve_config(raw: dict[str, Any] | None) -> dict[str, Any]:
33 """Normalize `phase_v2.legacy_sleeve`; any malformed value falls back to
34 the default (sleeve disabled == the pre-V5.5.0 unbounded behavior)."""
35 config = dict(DEFAULT_LEGACY_SLEEVE_CONFIG)
36 if not isinstance(raw, dict):
37 return config
38 config["enabled"] = bool(raw.get("enabled", config["enabled"]))
39 config["trade_when_book_vetoed"] = bool(raw.get("trade_when_book_vetoed", config["trade_when_book_vetoed"]))
40 for key in ("max_gross_exposure", "max_weight_per_name"):
41 try:
42 value = float(raw.get(key, config[key]))
43 except (TypeError, ValueError):
44 continue
45 if math.isfinite(value) and value >= 0.0:
46 config[key] = value
47 return config
50def compute_sleeve_gross_used(
51 held_weights_by_symbol: dict[str, float],
52 book_member_keys: set[str] | frozenset[str],
53) -> float:
54 """Gross |weight| currently held outside the book: every invested symbol
55 that is neither in this bar's book nor in the last formed book. During a
56 veto the book is empty, so remembered members still count as book (they
57 are positions the book opened), not sleeve."""
58 gross = 0.0
59 for symbol_key, weight in held_weights_by_symbol.items():
60 if symbol_key in book_member_keys:
61 continue
62 try:
63 value = abs(float(weight))
64 except (TypeError, ValueError):
65 continue
66 if math.isfinite(value):
67 gross += value
68 return gross
71def apply_legacy_sleeve_policy(
72 signal_name: str,
73 target_weight: float,
74 is_book_member: bool,
75 is_currently_invested: bool,
76 book_is_active: bool,
77 sleeve_gross_used: float,
78 sleeve_config: dict[str, Any],
79 is_book_owned: bool = False,
80) -> dict[str, Any]:
81 """Decide how much of a non-book symbol's legacy signal may trade.
83 Returns {"signal", "target_weight", "reason", "sleeve_gross_used"}.
84 - A NEW entry ("buy"/"short" on a flat, non-book symbol) is admitted only
85 inside the gross budget and the per-name cap. The returned
86 `sleeve_gross_used` includes it, so the caller threads it through the
87 rest of the bar's loop and the budget is atomic across symbols.
88 - A HELD sleeve position (invested, not book-owned) that the legacy signal
89 wants to size up is capped at the per-name weight - otherwise the 2%
90 entry would be scaled to the signal's full ~8% on the next bar.
91 - Book members, positions the BOOK opened (`is_book_owned` - during a veto
92 they are non-members too, and must not be shrunk to a sleeve weight),
93 exits ("sell") and "hold" pass through untouched.
94 """
95 passthrough = {
96 "signal": signal_name,
97 "target_weight": target_weight,
98 "reason": "legacy_sleeve_not_applicable",
99 "sleeve_gross_used": sleeve_gross_used,
100 }
101 if not sleeve_config.get("enabled"):
102 return passthrough
103 if is_book_member or is_book_owned or signal_name not in ("buy", "short"):
104 return passthrough
105 if is_currently_invested:
106 try:
107 requested_held = abs(float(target_weight))
108 except (TypeError, ValueError):
109 return passthrough
110 cap = float(sleeve_config["max_weight_per_name"])
111 if not math.isfinite(requested_held) or requested_held <= cap:
112 return passthrough
113 direction = 1.0 if float(target_weight) >= 0.0 else -1.0
114 return {
115 "signal": signal_name,
116 "target_weight": direction * cap,
117 "reason": "legacy_sleeve_held_capped",
118 "sleeve_gross_used": sleeve_gross_used,
119 }
121 def _hold(reason: str) -> dict[str, Any]:
122 return {"signal": "hold", "target_weight": 0.0, "reason": reason, "sleeve_gross_used": sleeve_gross_used}
124 if not book_is_active and not sleeve_config.get("trade_when_book_vetoed", False):
125 return _hold("legacy_sleeve_book_vetoed")
126 try:
127 requested = abs(float(target_weight))
128 except (TypeError, ValueError):
129 return _hold("legacy_sleeve_non_finite_weight")
130 if not math.isfinite(requested) or not math.isfinite(sleeve_gross_used):
131 return _hold("legacy_sleeve_non_finite_weight")
133 remaining = float(sleeve_config["max_gross_exposure"]) - sleeve_gross_used
134 if remaining <= 0.0:
135 return _hold("legacy_sleeve_budget_exhausted")
136 capped = min(requested, float(sleeve_config["max_weight_per_name"]), remaining)
137 if capped <= 0.0:
138 return _hold("legacy_sleeve_budget_exhausted")
139 direction = 1.0 if float(target_weight) >= 0.0 else -1.0
140 return {
141 "signal": signal_name,
142 "target_weight": direction * capped,
143 "reason": "legacy_sleeve_capped" if capped < requested else "legacy_sleeve_within_budget",
144 "sleeve_gross_used": sleeve_gross_used + capped,
145 }
148def resolve_legacy_signal_params(config: dict[str, Any], decision_threshold: float) -> dict[str, Any]:
149 """The probability signal's settings, read the way main.py reads them (V6.1.0: one definition for main.py and the
150 offline legacy replay): buy / sell thresholds around the baseline model's `decision_threshold`
151 (`phase5.backtest.*_threshold_offset`, clamped to [0.25, 0.75]), the adaptive sell band (`phase_v2.exits.adaptive_band_*`)
152 and the position cap the signal sizes against (`phase6.risk.max_position_weight`)."""
153 backtest = (config or {}).get("phase5", {}).get("backtest", {}) or {}
154 exits = (config or {}).get("phase_v2", {}).get("exits", {}) or {}
155 risk = (config or {}).get("phase6", {}).get("risk", {}) or {}
156 threshold = float(decision_threshold)
157 return {
158 "decision_threshold": threshold,
159 "buy_threshold": min(0.75, threshold + float(backtest.get("buy_threshold_offset", 0.08))),
160 "sell_threshold": max(0.25, threshold - float(backtest.get("sell_threshold_offset", 0.08))),
161 "band_enabled": bool(exits.get("adaptive_band_enabled", True)),
162 "band_window": int(exits.get("adaptive_band_window_bars", 60)),
163 "band_min_observations": int(exits.get("adaptive_band_min_observations", 20)),
164 "band_percentile": float(exits.get("adaptive_band_percentile", 0.25)),
165 "max_position_weight": float(risk.get("max_position_weight", 0.25)),
166 }