Coverage for portfolio/cash_sweep.py: 100%
59 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"""Idle cash held in a T-bill ETF (V6.2.0, `phase_v2.cash_sweep`, default off).
3The book is market neutral and mostly vetoed, so 70-95% of the NAV sits as cash Lean pays no interest on, while Lean's
4Sharpe subtracts the full risk-free rate. A market-neutral fund holds that cash in T-bills; this sizes such a holding
5(BIL by default, a ticker outside the universe: never scored, ranked, gated or capped) under two hard limits:
7 * **no borrowing**: cash after the sweep and everything the strategy may still buy by the next session stays at or
8 above `cash_buffer`. Lean charges no margin interest, so a sweep bought on margin would be free carry;
9 * **margin**: Lean's buying-power check runs when an order is submitted and does not net sells that have not filled,
10 so the sweep leaves room for the whole next session's orders (a fresh book on a rebalance attempt) inside
11 `1 - margin_buffer` of the margin Lean's default brokerage model allows (equity 2x, crypto 1x, forex 50x).
13The kill switch, the drawdown velocity and the drawdown lock read the strategy's own value (`advance_strategy_value`):
14T-bill carry must not mask a failing strategy, and the book's decisions stay its own.
15main.py and the offline simulator call the same functions. Pure, NaN-safe.
16"""
18from __future__ import annotations
20import math
21from typing import Any
23# Lean DefaultBrokerageModel.GetLeverage for a margin account (main.py sets no brokerage model)
24LEAN_DEFAULT_LEVERAGE = {"equity": 2.0, "crypto": 1.0, "forex": 50.0, "cfd": 50.0}
26DEFAULTS = {
27 "enabled": False,
28 "ticker": "BIL",
29 "data_path": "data/equity/usa/daily/bil.zip",
30 "max_weight": 0.9,
31 "margin_leverage": 2.0,
32 "margin_buffer": 0.1,
33 "cash_buffer": 0.02,
34 "min_trade_weight": 0.05,
35 "cost_bps_per_side": 1.0,
36 "exclude_from_risk_controls": True,
37}
40def _finite(value, default: float) -> float:
41 try:
42 number = float(value)
43 except (TypeError, ValueError):
44 return default
45 return number if math.isfinite(number) else default
48def resolve_cash_sweep_config(raw: dict[str, Any] | None) -> dict[str, Any]:
49 """`phase_v2.cash_sweep` with defaults; out-of-range numbers fall back to the default rather than raise."""
50 raw = raw or {}
51 config = {
52 "enabled": bool(raw.get("enabled", DEFAULTS["enabled"])),
53 "ticker": str(raw.get("ticker") or DEFAULTS["ticker"]).upper(),
54 "data_path": str(raw.get("data_path") or DEFAULTS["data_path"]),
55 "exclude_from_risk_controls": bool(raw.get("exclude_from_risk_controls", DEFAULTS["exclude_from_risk_controls"])),
56 }
57 bounds = {
58 "max_weight": (0.0, 1.0), "margin_leverage": (1.0, 50.0), "margin_buffer": (0.0, 0.9),
59 "cash_buffer": (0.0, 0.5), "min_trade_weight": (0.0, 1.0), "cost_bps_per_side": (0.0, 100.0),
60 }
61 for key, (low, high) in bounds.items():
62 value = _finite(raw.get(key, DEFAULTS[key]), DEFAULTS[key])
63 config[key] = value if low <= value <= high else DEFAULTS[key]
64 return config
67def margin_fraction(weights: list[tuple[str, float]]) -> float:
68 """Margin Lean's default model holds for these (security type, signed weight) positions, as a fraction of NAV."""
69 total = 0.0
70 for security_type, weight in weights:
71 leverage = LEAN_DEFAULT_LEVERAGE.get(str(security_type).lower(), 1.0)
72 total += abs(_finite(weight, 0.0)) / leverage
73 return total
76def strategy_reserve(
77 *,
78 rebalance_next: bool,
79 book_gross_cap: float,
80 max_short_exposure: float,
81 formed_long: float,
82 formed_short: float,
83 book_long: float,
84 book_short: float,
85 other_budget_remaining: float,
86 neutral_budget: float = 0.0,
87) -> dict[str, Any]:
88 """Gross the strategy may add by the next session, by side, and the margin it would hold. On a rebalance attempt a
89 whole new book can be ordered (long up to half the cap, short up to half the cap and `max_short_exposure`) while the
90 current one is still held, since sells free nothing until they fill; otherwise only the formed book's unfilled part.
91 `other_budget_remaining` (the legacy signal) is counted as long at leverage 1, the worst case for both limits;
92 `neutral_budget` (the class sleeves, dollar-neutral by construction: `build_class_sleeve_weights`) as half long and
93 half short at equity leverage."""
94 cap = max(0.0, _finite(book_gross_cap, 0.0))
95 if rebalance_next:
96 add_long = cap / 2.0
97 add_short = min(cap / 2.0, max(0.0, _finite(max_short_exposure, cap / 2.0)))
98 else:
99 add_long = max(0.0, _finite(formed_long, 0.0) - _finite(book_long, 0.0))
100 add_short = max(0.0, _finite(formed_short, 0.0) - _finite(book_short, 0.0))
101 other = max(0.0, _finite(other_budget_remaining, 0.0))
102 neutral = max(0.0, _finite(neutral_budget, 0.0))
103 return {
104 "long": add_long + other + neutral / 2.0,
105 "short": add_short + neutral / 2.0,
106 "margin": (add_long + add_short + neutral) / LEAN_DEFAULT_LEVERAGE["equity"] + other,
107 }
110def cash_sweep_target_weight(
111 *, long_weight: float, short_weight: float, margin_used: float, reserve: dict[str, Any], config: dict[str, Any]
112) -> float:
113 """Sweep weight (fraction of NAV) inside both limits and `max_weight`; 0.0 for any non-finite input."""
114 values = [long_weight, short_weight, margin_used, reserve.get("long"), reserve.get("short"), reserve.get("margin")]
115 if any(not math.isfinite(_finite(value, float("nan"))) for value in values):
116 return 0.0
117 long_weight, short_weight, margin_used = abs(float(long_weight)), abs(float(short_weight)), float(margin_used)
118 by_margin = config["margin_leverage"] * (1.0 - config["margin_buffer"] - margin_used - float(reserve["margin"]))
119 # an unfilled short's proceeds fund only the longs ordered with it: a short that never fills (a cap, a lock) must not
120 # leave the sweep bought on credit
121 credit = min(float(reserve["short"]), float(reserve["long"]))
122 by_cash = 1.0 - long_weight + short_weight - float(reserve["long"]) + credit - config["cash_buffer"]
123 return max(0.0, min(config["max_weight"], by_margin, by_cash))
126def sweep_order_needed(current_weight: float, target_weight: float, min_trade_weight: float) -> bool:
127 """Trade when the gap is at least `min_trade_weight`, or whenever the sweep is above its target (a cut for the
128 limits is never deferred)."""
129 current, target = _finite(current_weight, 0.0), _finite(target_weight, 0.0)
130 return current > target + 1e-9 or abs(target - current) >= float(min_trade_weight)
133def advance_strategy_value(state: dict[str, Any] | None, total_value: float, sweep_profit: float) -> tuple[dict, float]:
134 """The value the risk controls read: an index that compounds the strategy's own P&L (the portfolio's change minus the
135 sweep's) over the TOTAL value the strategy is sized on, starting at the first total value seen. Subtracting the
136 cumulative carry from the total instead (V6.2.0's first BT1) divides the strategy's dollar P&L by a smaller base than
137 it was sized on: ~8% inflated returns and drawdown speed by mid-2024, enough to trip the kill switch on a day V6.1
138 did not. The offline simulator's kill switch reads the same quantity (book + legacy return as a fraction of NAV).
139 Returns (new state, value); a non-finite or non-positive input keeps the previous value."""
140 total = _finite(total_value, float("nan"))
141 sweep = _finite(sweep_profit, 0.0)
142 if state is None:
143 if not math.isfinite(total) or total <= 0.0:
144 return None, total_value
145 return {"total": total, "sweep": sweep, "value": total}, total
146 if not math.isfinite(total) or total <= 0.0 or state["total"] <= 0.0:
147 return state, state["value"]
148 strategy_return = ((total - state["total"]) - (sweep - state["sweep"])) / state["total"]
149 # V6.6.7 (#374, formal/AetherFormal/CashSweep.lean): a session that loses more than the strategy holds (a large sweep
150 # profit while the total falls) gave strategy_return < -1 and a negative value; the floor is zero, a 100% drawdown
151 value = max(0.0, state["value"] * (1.0 + strategy_return))
152 return {"total": total, "sweep": sweep, "value": value}, value