Coverage for portfolio/sleeve_guard.py: 100%
47 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"""Per-sleeve loss guard (V5.8.0).
3V5.8.0 enables sleeves the evidence may not fully support (owner decision: forex, bonds, newly eligible crypto and RL
4sizing trade even without a proven edge, at a minimal cap). The cap bounds the exposure; this guard bounds the damage.
5Each sleeve's mark-to-market P&L is tracked per bar; when its drawdown from the running peak over the trailing
6`lookback_bars` exceeds `max_loss_fraction_nav` of NAV, the sleeve is suspended for `cooldown_bars`: no new entries, its
7positions are closed. The portfolio-level kill switch stays the control for the whole book; this one only switches a
8sleeve off.
10Pure, no I/O. `main.py` and `evaluation/rank_book_simulator.py` call the same function (parity contract).
11"""
13from __future__ import annotations
15import math
16from collections.abc import Sequence
17from dataclasses import dataclass
18from typing import Any
21@dataclass(frozen=True)
22class SleeveGuardConfig:
23 """Settings of a sleeve's loss guard: on or off, the loss limit as a share of NAV and the lookback."""
24 enabled: bool = False
25 max_loss_fraction_nav: float = 0.01
26 lookback_bars: int = 60
27 cooldown_bars: int = 60
30def resolve_sleeve_guard_config(raw: dict[str, Any] | None) -> SleeveGuardConfig:
31 """Config block -> SleeveGuardConfig; absent or malformed keys fall back to the defaults (disabled)."""
32 raw = raw or {}
34 def _number(key: str, default: float) -> float:
35 try:
36 value = float(raw.get(key, default))
37 except (TypeError, ValueError):
38 return default
39 return value if math.isfinite(value) else default
41 return SleeveGuardConfig(
42 enabled=bool(raw.get("enabled", False)),
43 max_loss_fraction_nav=max(0.0, _number("max_loss_fraction_nav", 0.01)),
44 lookback_bars=max(1, int(_number("lookback_bars", 60))),
45 cooldown_bars=max(0, int(_number("cooldown_bars", 60))),
46 )
49def trailing_drawdown(pnl_increments: Sequence[float], lookback_bars: int) -> float:
50 """The current drawdown at the latest bar (a positive number, same unit as the increments): the cumulative P&L's
51 running peak over the last `lookback_bars` increments minus where it ends, not the largest fall inside the window
52 (formal/AetherFormal/SleeveGuard.lean). Non-finite increments count as 0. A non-positive
53 lookback reads no window (V6.4.3: `xs[-0:]` is the whole history)."""
54 if lookback_bars <= 0:
55 return 0.0
56 window = [float(value) if value is not None and math.isfinite(float(value)) else 0.0 for value in pnl_increments[-lookback_bars:]]
57 peak = 0.0
58 level = 0.0
59 for value in window:
60 level += value
61 peak = max(peak, level)
62 return max(0.0, peak - level)
65def evaluate_sleeve_guard(
66 pnl_increments: Sequence[float],
67 nav: float,
68 config: SleeveGuardConfig,
69 *,
70 current_bar: int,
71 suspended_until_bar: int | None = None,
72) -> dict[str, Any]:
73 """Decides whether the sleeve may trade on `current_bar`.
75 `pnl_increments` is the sleeve's per-bar P&L history (dollars, or NAV fractions with `nav=1.0`), oldest first.
76 Returns {"active": bool, "reason": str, "suspended_until_bar": int | None, "drawdown": float, "limit": float}.
77 A suspension started earlier holds until `suspended_until_bar` (exclusive); a fresh breach starts a new one. The
78 history is NOT reset by the caller: after the cooldown the trailing window usually no longer contains the loss, and
79 if it still does the sleeve stays off - a loss that has not healed is not a reason to resume."""
80 limit = max(0.0, float(nav)) * config.max_loss_fraction_nav if math.isfinite(float(nav)) else 0.0
81 if not config.enabled:
82 return {"active": True, "reason": "sleeve_guard_disabled", "suspended_until_bar": None, "drawdown": 0.0, "limit": limit}
83 drawdown = trailing_drawdown(pnl_increments, config.lookback_bars)
84 if suspended_until_bar is not None and current_bar < suspended_until_bar:
85 return {"active": False, "reason": "sleeve_guard_cooldown", "suspended_until_bar": suspended_until_bar,
86 "drawdown": drawdown, "limit": limit}
87 if limit > 0.0 and drawdown > limit:
88 return {"active": False, "reason": "sleeve_guard_loss_limit", "suspended_until_bar": current_bar + config.cooldown_bars,
89 "drawdown": drawdown, "limit": limit}
90 return {"active": True, "reason": "sleeve_guard_ok", "suspended_until_bar": None, "drawdown": drawdown, "limit": limit}
93def sleeve_pnl_increment(previous_values: dict[str, float], current_values: dict[str, float], cash_flows: dict[str, float]) -> float:
94 """Mark-to-market P&L of a sleeve between two bars: change in its positions' market value minus the cash put in
95 (buys positive, sells negative, fees positive). Symbols missing on one side count as 0."""
96 symbols = set(previous_values) | set(current_values) | set(cash_flows)
97 total = 0.0
98 for symbol in symbols:
99 change = float(current_values.get(symbol, 0.0)) - float(previous_values.get(symbol, 0.0))
100 total += change - float(cash_flows.get(symbol, 0.0))
101 return total if math.isfinite(total) else 0.0