Coverage for risk_controls.py: 100%
115 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"""Pure risk-control helpers shared by tests and the Lean algorithm."""
3from __future__ import annotations
5import math
6from typing import TYPE_CHECKING, Any
8if TYPE_CHECKING:
9 from collections.abc import Iterable
12def assess_drawdown_lock(
13 daily_drawdown: float,
14 total_drawdown: float,
15 max_daily_drawdown_pct: float,
16 max_total_drawdown_pct: float,
17) -> tuple[bool, str | None]:
18 """Whether the daily or total drawdown has reached its limit, and which (total first): the sticky trade lock's test."""
19 if total_drawdown <= -max_total_drawdown_pct:
20 return True, "total_drawdown_limit_breached"
21 if daily_drawdown <= -max_daily_drawdown_pct:
22 return True, "daily_drawdown_limit_breached"
23 return False, None
26def is_backtest_safety_bypass_active(runtime_mode: str, bypass_flag: bool) -> bool:
27 """True only when a backtest is running with
28 phase_v2.backtest.bypass_safety_gates explicitly set to true - any
29 non-backtest runtime_mode always returns False regardless of the flag,
30 and the flag defaults to False (gates active, honest/deployable-
31 representative) so this is opt-in, not implicit. Deliberately
32 independent of aq trade-lock's on/off/auto override, which keeps its
33 existing, separately-documented meaning unchanged in every runtime
34 mode.
36 V5.2.7 (development/Problems.md) - CORRECTED docstring: this used to
37 claim "scoped narrowly to the sticky total-drawdown lock and the
38 regime risk_off drawdown branch," but that was never accurate once
39 V5.1 Phase 6 extended main.py's session-rollover sticky-clear branch
40 to ALSO cover any kill_switch_* trade_lock_reason, not just
41 total_drawdown_limit_breached - this flag's real effect was always
42 broader than its own docstring said. This is now the LEGACY combined
43 flag, kept only for backward compatibility (still fully functional,
44 still bundles both behaviors exactly as before) - new callers should
45 use is_sticky_trade_lock_bypass_active()/is_regime_drawdown_bypass_active()
46 below instead, which split the same two behaviors into independently
47 configurable flags while still OR-ing this legacy flag in so nobody's
48 existing config silently stops working."""
49 return runtime_mode == "backtest" and bypass_flag
52def is_sticky_trade_lock_bypass_active(
53 runtime_mode: str,
54 sticky_bypass_flag: bool,
55 legacy_bypass_flag: bool,
56) -> bool:
57 """V5.2.7 (development/Problems.md) - True when a backtest is running
58 with EITHER phase_v2.backtest.bypass_sticky_trade_lock OR the legacy
59 phase_v2.backtest.bypass_safety_gates explicitly true. Controls ONLY
60 main.py's session-rollover total_drawdown_limit_breached/kill_switch_*
61 sticky-lock clear - never the regime risk_off drawdown branch (see
62 is_regime_drawdown_bypass_active() for that, now a genuinely
63 independent flag instead of the two being bundled together under one
64 name). Any non-backtest runtime_mode always returns False regardless
65 of either flag.
67 Bug this closes: a real backtest showed a kill-switch trip on
68 2020-02-27 stay locked for the remaining 13 months of a ~2.2-year
69 backtest (336/336 book-member decisions forced to reduce_risk in that
70 window, vs. 16% before the trip) - kill_switch_* reasons are
71 deliberately exempt from the normal daily auto-clear (a real, correct
72 safety choice for live/paper trading, where a human should decide
73 when to resume after a genuine circuit-breaker trip), but an
74 unattended historical backtest has no human to ever clear it, so a
75 single trip event silently darkens the rest of the evaluation window
76 regardless of whether the underlying conditions later recover."""
77 return runtime_mode == "backtest" and (sticky_bypass_flag or legacy_bypass_flag)
80def is_regime_drawdown_bypass_active(
81 runtime_mode: str,
82 regime_bypass_flag: bool,
83 legacy_bypass_flag: bool,
84) -> bool:
85 """V5.2.7 (development/Problems.md) - True when a backtest is running
86 with EITHER phase_v2.backtest.bypass_regime_drawdown_gate OR the
87 legacy phase_v2.backtest.bypass_safety_gates explicitly true.
88 Controls ONLY main.py::_build_regime_payload()'s
89 risk_off_drawdown_threshold override (set to infinity when active,
90 disabling just the drawdown-driven branch of classify_risk_regime -
91 the bearish-trend/high-vol and composite-risk-score branches stay
92 active regardless) - never the sticky trade-lock clear (see
93 is_sticky_trade_lock_bypass_active() for that). Any non-backtest
94 runtime_mode always returns False regardless of either flag.
96 Deliberately a SEPARATE flag from the sticky-lock bypass above, even
97 though both were previously bundled under the single
98 bypass_safety_gates flag - a user who wants a stuck kill-switch lock
99 to be able to clear should not be forced to also disable this
100 unrelated regime-level protection as a side effect."""
101 return runtime_mode == "backtest" and (regime_bypass_flag or legacy_bypass_flag)
104def active_position_limit_reached(
105 active_positions: int,
106 max_active_positions: int,
107 is_currently_invested: bool,
108) -> bool:
109 """Whether a new position would exceed the active-position limit (a name already held never counts against it)."""
110 return not is_currently_invested and active_positions >= max_active_positions
113def cap_target_weight(
114 target_weight: float,
115 current_exposure: float,
116 exposure_cap: float,
117) -> tuple[float, bool]:
118 """(weight, blocked): the target clipped to the exposure left under the cap, sign preserved. A non-finite target is
119 blocked (V6.4.3: `nan >= 0.0` is False, so a NaN target came out as a full short of the remaining capacity)."""
120 if not math.isfinite(target_weight):
121 return 0.0, True
122 remaining_exposure = max(0.0, exposure_cap - current_exposure)
123 requested_exposure = abs(target_weight)
124 if requested_exposure <= remaining_exposure:
125 return target_weight, False
127 if remaining_exposure <= 0.0:
128 return 0.0, True
130 direction = 1.0 if target_weight >= 0.0 else -1.0
131 return direction * remaining_exposure, False
134def should_scale_position(
135 current_weight: float,
136 target_weight: float,
137 rebalance_threshold_weight: float,
138) -> bool:
139 """True iff an already-open, same-direction position's target has moved
140 far enough (>= threshold) to warrant resubmitting an order, rather than
141 treating trivial confidence wiggle as churn. Direction-agnostic (abs) -
142 callers only invoke this once a same-direction hold is already
143 established via the unchanged previous_signal gate."""
144 return abs(target_weight - current_weight) >= rebalance_threshold_weight
147def compute_held_weight(holdings_value: float, total_portfolio_value: float) -> float:
148 """The current_weight formula _apply_signal()'s scaling branches already
149 compute inline (twice, once per direction) - extracted so every caller
150 reads one shared formula instead of maintaining duplicate copies that
151 could silently drift if one is ever edited without the other. Floors
152 total_portfolio_value at 1.0 (never divide by zero/negative)."""
153 return holdings_value / max(total_portfolio_value, 1.0)
156def is_position_resize_permitted(
157 position_scaling_enabled: bool,
158 is_book_selected: bool,
159 is_rebalance_bar: bool,
160) -> bool:
161 """V5.2.1 (development/Problems.md) - a book-selected symbol's SIZE may
162 only resize on a rebalance bar; every other symbol (an individual-
163 signal trade, or every symbol when the book is disabled entirely) is
164 completely unaffected by this gate.
166 Bug this closes: should_scale_position() was being re-evaluated every
167 single bar for book members too, entirely independent of the book's
168 own is_rebalance_bar cadence - a book member's base weight is frozen
169 between rebalances, but the downstream sizing pipeline (confidence/
170 volatility/liquidity/cost multipliers) reinterprets that same frozen
171 weight differently bar to bar from live noise, tripping
172 rebalance_threshold_weight and firing real resize orders on non-
173 rebalance bars. That noise-churn is what this gates out.
175 Deliberately does NOT touch full exits (signal_name == "sell") or the
176 V4.3.0 futures/options incremental-quantity protection
177 (compute_incremental_order_quantity()) - both are unconditional,
178 separate code paths, never gated by this function."""
179 return position_scaling_enabled and (not is_book_selected or is_rebalance_bar)
182def is_cooldown_exempt(signal_name: str, is_currently_invested: bool, is_forced_exit: bool = False) -> bool:
183 """V5.5.0 (Problems.md #128/#133) - a FORCED exit of an open position (the
184 book's rotation exit, or the max-holding / trailing-stop backstops) is
185 never blocked by trade_cooldown_bars: the cooldown exists to stop entry
186 whipsaw, and applied to those it held rotated-out book names ~14 days.
188 A plain legacy "sell" SIGNAL is NOT exempt. The first version exempted
189 every sell, and the legacy probability signal then flipped book and
190 sleeve positions out within a day: 230 of 355 trades in the 2026-10-07
191 backtest closed within 2 days (mean hold 5.8 days vs 39 before), 6-7 bps
192 of fees each way for nothing. The cooldown is what rate-limits that
193 noisy signal, so it keeps doing so."""
194 return signal_name == "sell" and bool(is_currently_invested) and bool(is_forced_exit)
197def projected_signed_quantity(held_quantity: float, open_order_quantity: float) -> float:
198 """V5.5.0 (Problems.md #128) - the position size AFTER every in-flight
199 order fills: held + open (signed, remaining) order quantity. Sizing off
200 held quantity alone re-submitted the same target on every tick until
201 the first order filled (forex is evaluated on both the equity-session
202 and the forex-session tick), stacking up to 60% short. Non-finite
203 inputs count as 0.0."""
204 def _finite(value: float) -> float:
205 try:
206 number = float(value)
207 except (TypeError, ValueError):
208 return 0.0
209 return number if number == number and abs(number) != float("inf") else 0.0
211 return _finite(held_quantity) + _finite(open_order_quantity)
214def should_lock_in_duration_beta(
215 window_length: int,
216 treasury_window_length: int,
217 target_window_length: int,
218) -> bool:
219 """V5.2.5 (development/Problems.md #91-continuation) - whether enough
220 history has accumulated to compute bond_empirical_duration_beta ONCE
221 and cache it, rather than re-rolling a fresh (and therefore drifting)
222 estimate every bar.
224 Bug this closes: main.py::_bond_empirical_duration_beta_for_symbol()
225 used to recompute this OLS slope from a ROLLING window every single
226 bar for the life of the backtest, while train.py::build_bond_features_by_date()
227 (the offline path that produced the model's OWN training data) computes
228 it ONCE per ticker - a single slope over that asset's entire available
229 history - and broadcasts that unchanged value to every row. The model
230 was trained on a stable, whole-history characteristic per bond asset;
231 live was feeding it a noisy, continuously-drifting value instead - an
232 out-of-training-distribution input for every bond-tagged symbol, every
233 bar, confirmed directly correlated with the bond-ETF-heavy live-vs-
234 offline selection mismatch pattern found in the V5.2.4 reconciliation.
236 True once BOTH the price window and the treasury-yield window have
237 reached `target_window_length` (main.py's own `self.long_bar_history_size`,
238 260 - the deque's own maxlen, the most history practically available to
239 a live algorithm that can never see future data the way an offline
240 batch process can) - mirrors train.py's own "compute once per ticker,
241 broadcast unchanged" semantic as closely as a real-time algorithm's
242 inherent lack of future history allows. Both windows must independently
243 clear the bar (AND, not OR) - a symbol with plenty of price history but
244 a still-filling treasury-yield history (or vice versa) isn't ready yet."""
245 return window_length >= target_window_length and treasury_window_length >= target_window_length
248def compute_forex_order_units(target_weight: float, close_price: float, portfolio_value: float) -> int:
249 """V5.2.7 (development/Problems.md) - converts a target portfolio
250 weight into whole base-currency UNITS for a Forex MarketOrder - NOT a
251 lot count. QuantConnect Lean's MarketOrder() for SecurityType.Forex
252 takes raw base-currency units (e.g. MarketOrder("EURUSD", 10000) =
253 10,000 EUR), matching Portfolio[symbol].Quantity's own reporting
254 convention - standard, documented Lean/IB behavior, but UNVERIFIED
255 empirically in this repo/Lean image as of this fix. See
256 build_forex_order_sizing_record()'s notional_ratio field for the
257 direct, human-checkable confirmation this assumption needs from a
258 real backtest.
260 Bug this closes: main.py::_forex_lot_count_for_weight() used to
261 divide notional by (lot_size * close_price) - a full 100,000-unit
262 standard lot - which on a $100k backtest account with a realistic
263 book-member position weight (4-12%) produces a notional ($4,000-
264 $12,000) far smaller than even one lot ($67,000-$130,000+), so the
265 division always rounded to 0. Confirmed directly: forex allocations
266 that cleared every other risk/liquidity/confidence gate and reached
267 a real "trade" decision still silently produced zero Lean orders.
269 Deliberately does NOT round to a whole lot_size multiple either -
270 that would silently reproduce the exact same always-zero-orders bug
271 under a new name, since the same realistic position sizes are still
272 far below one full lot. Rounds to the nearest whole UNIT instead
273 (IB/Lean forex orders must be whole units, never fractional
274 currency). Returns 0 (never raises) when close_price or
275 portfolio_value is non-positive."""
276 if close_price <= 0.0 or portfolio_value <= 0.0:
277 return 0
278 notional = target_weight * portfolio_value
279 return int(round(notional / close_price))
282def build_forex_order_sizing_record(
283 date_str: str,
284 symbol: str,
285 direction: str,
286 target_weight: float,
287 portfolio_value: float,
288 close_price: float,
289 order_units: int,
290) -> dict[str, Any]:
291 """V5.2.7 (development/Problems.md) - a diagnostic snapshot of one
292 forex order-sizing decision, for main.py's optional (config-gated,
293 off by default, backtest-only) forex-order-sizing log. Exists
294 because compute_forex_order_units()'s "Lean forex MarketOrder takes
295 raw units" assumption cannot be verified from this Python codebase
296 alone - notional_ratio is the direct, human-checkable confirmation a
297 real backtest's log can provide instead: it should sit very close to
298 1.0 for correct sizing (only whole-unit rounding slop); a value
299 wildly off (e.g. 100x or 0.01x) is the exact, unambiguous symptom of
300 a wrong units assumption, and should be treated as disqualifying for
301 that backtest's other results until investigated.
303 Pure: no I/O, no `self`, never raises on well-formed inputs.
304 intended_notional == 0.0 (target_weight == 0.0) returns
305 notional_ratio=None rather than dividing by zero - a symbol with no
306 real order to place has nothing to sanity-check."""
307 intended_notional = target_weight * portfolio_value
308 implied_notional = order_units * close_price
309 return {
310 "date": date_str,
311 "symbol": symbol,
312 "direction": direction,
313 "target_weight": target_weight,
314 "portfolio_value": portfolio_value,
315 "close_price": close_price,
316 "order_units": order_units,
317 "intended_notional": intended_notional,
318 "implied_notional": implied_notional,
319 "notional_ratio": (implied_notional / intended_notional) if intended_notional != 0.0 else None,
320 }
323def compute_incremental_order_quantity(
324 target_quantity: float,
325 current_quantity: float,
326) -> float:
327 """target_quantity is an ABSOLUTE, already-signed sizing target
328 (futures contract count, or a matched option contract's/spread's
329 target quantity), recomputed fresh every bar; current_quantity is
330 whatever is actually held right now. Returns the signed delta an
331 incremental order primitive (MarketOrder/Buy) must submit to converge
332 toward target_quantity, instead of firing the absolute target every
333 bar and silently overshooting it. Pure arithmetic, never raises -
334 callers round/zero-check the result themselves."""
335 return target_quantity - current_quantity
338def evaluate_non_model_exit(
339 bar_index: int,
340 exits_enabled: bool,
341 exits_max_holding_bars: int,
342 exits_trailing_stop_pct: float,
343 entry_bar_index: int | None,
344 peak_price_since_entry: float | None,
345 direction: str,
346 close_price: float,
347) -> str | None:
348 """V4.10 - pure extraction of main.py::_check_non_model_exit(),
349 asset-class-agnostic (same trailing-stop/max-age math for equity,
350 crypto, futures, options, forex alike). Two checks, first match wins:
352 1. Max holding age: fires once bar_index - entry_bar_index reaches
353 exits_max_holding_bars, regardless of price.
354 2. Trailing stop: fires once price has drawn down
355 exits_trailing_stop_pct from its best price since entry
356 (direction-aware: "best" is the highest close for a long, lowest
357 for a short).
359 exits_enabled=False restores pre-fix behavior byte-for-byte - no
360 non-model exit ever fires. Caller resolves the per-symbol dict
361 lookups (entry_bar_index/peak_price_since_entry/direction) before
362 calling - this function itself touches no dicts, no self."""
363 if not exits_enabled:
364 return None
366 if entry_bar_index is None:
367 return None
369 if bar_index - entry_bar_index >= exits_max_holding_bars:
370 return "max_holding_age_exceeded"
372 if peak_price_since_entry is not None and peak_price_since_entry > 0.0:
373 if direction == "long":
374 drawdown_from_peak = (peak_price_since_entry - close_price) / peak_price_since_entry
375 else:
376 drawdown_from_peak = (close_price - peak_price_since_entry) / peak_price_since_entry
377 if drawdown_from_peak >= exits_trailing_stop_pct:
378 return "trailing_stop_triggered"
380 return None
383def compute_position_exit_tracking_update(
384 was_invested: bool,
385 is_invested: bool,
386 close_price: float,
387 signal_name: str,
388 peak_price_since_entry: float | None,
389 direction: str | None,
390 bar_index: int,
391 has_entry_state: bool = True,
392 held_quantity: float | None = None,
393 average_entry_price: float | None = None,
394 clear_stale_state: bool = False,
395) -> dict[str, Any]:
396 """V4.10 - pure extraction of main.py::_update_position_exit_tracking().
398 V5.5.0 (Problems.md #134): the closing fill also lands on the NEXT bar, so
399 the invested -> flat transition is likewise never observed here and the
400 entry state of a closed position stayed behind. The symbol's next entry
401 was then ADOPTED never (state "exists"), inherited the old entry bar and
402 peak, and was force-sold for `max_holding_age_exceeded` / the trailing stop
403 the day after it filled: 154 of the 196 re-entries in the 2026-10-07
404 backtest lasted under 2 days (all 44 first entries were fine). With
405 `clear_stale_state=True`, a flat symbol that is still carrying entry state
406 returns {"action": "clear"}. Default False keeps the pre-fix behavior.
408 V5.5.0 (Problems.md #128): a daily market/limit order fills on the NEXT
409 bar, so the was-flat -> is-invested transition this function keys on is
410 never observed inside a single Pass 2 iteration - the position just
411 appears already-held one bar later. Without adoption, no entry state was
412 ever recorded: max_holding_bars never fired, shorts defaulted to a
413 "long" trailing stop (inverted), and peaks never reset between holdings.
414 With `has_entry_state=False` and an invested+was_invested symbol, the
415 position is ADOPTED as a fresh entry here, direction taken from the real
416 held_quantity sign and entry price from average_entry_price when given.
417 Defaults (has_entry_state=True) reproduce the pre-V5.5.0 behavior.
418 Observes the net invested/not-invested transition (was_invested vs.
419 is_invested) rather than hooking into any asset-class-specific
420 routing - robust to every routing path by construction, since it only
421 cares about the outcome.
423 Returns the NEW state as a dict rather than mutating dicts in place,
424 so this stays pure/testable - the caller applies the result to its
425 own tracking dicts:
426 - {"action": "enter", "entry_bar_index":, "entry_price":,
427 "peak_price_since_entry":, "direction":} on a fresh entry.
428 - {"action": "hold", "peak_price_since_entry":} while an existing
429 position is held (entry_bar_index/entry_price are untouched by
430 design - not present in this dict).
431 - {"action": "clear"} once a held position is closed.
432 - {"action": "noop"} otherwise (was never invested and still isn't -
433 matches the original method's implicit no-op branch)."""
434 if is_invested and not was_invested:
435 return {
436 "action": "enter",
437 "entry_bar_index": bar_index,
438 "entry_price": close_price,
439 "peak_price_since_entry": close_price,
440 "direction": "short" if signal_name == "short" else "long",
441 }
443 if is_invested and was_invested and not has_entry_state:
444 if held_quantity is not None and held_quantity < 0:
445 adopted_direction = "short"
446 elif held_quantity is not None and held_quantity > 0:
447 adopted_direction = "long"
448 else:
449 adopted_direction = "short" if signal_name == "short" else "long"
450 adopted_price = (
451 float(average_entry_price)
452 if average_entry_price is not None and average_entry_price == average_entry_price and average_entry_price > 0
453 else close_price
454 )
455 return {
456 "action": "enter",
457 "entry_bar_index": bar_index,
458 "entry_price": adopted_price,
459 "peak_price_since_entry": adopted_price,
460 "direction": adopted_direction,
461 }
463 if is_invested and was_invested:
464 resolved_direction = direction or "long"
465 peak_price = peak_price_since_entry if peak_price_since_entry is not None else close_price
466 if resolved_direction == "long":
467 new_peak_price = max(peak_price, close_price)
468 else:
469 new_peak_price = min(peak_price, close_price)
470 return {"action": "hold", "peak_price_since_entry": new_peak_price}
472 if not is_invested and (was_invested or (clear_stale_state and has_entry_state)):
473 return {"action": "clear"}
475 return {"action": "noop"}
478def resolve_lean_window(runtime: dict[str, Any] | None, windows: dict[str, Any]) -> tuple[tuple[int, int, int], tuple[int, int, int]]:
479 """((start y, m, d), (end y, m, d)) of the Lean run: `runtime.lean_window_override` {"start", "end"} when both are
480 ISO dates, else `phase1.windows.backtest`. The override exists so a Lean run can cover the holdout period (V5.8.0 BT2)
481 without editing `phase1.windows`, which also defines the dataset split the models were trained and judged on."""
482 override = (runtime or {}).get("lean_window_override") or {}
483 window = windows["backtest"]
484 start, end = override.get("start") or window["start"], override.get("end") or window["end"]
486 def _parts(text: str) -> tuple[int, int, int]:
487 year, month, day = (int(part) for part in str(text).split("-"))
488 return year, month, day
490 return _parts(start), _parts(end)
493def resolve_benchmark_ticker(runtime: dict[str, Any] | None, universe_tickers: Iterable[str]) -> str | None:
494 """Ticker Lean's benchmark should follow (`runtime.benchmark_ticker`), or None to keep Lean's default.
496 Lean's default benchmark is an internal HOUR SPY feed; the local hourly zip is Lean's sample file and ends 2021-03-31,
497 so every later run charted a constant benchmark. Pointing the benchmark at the daily universe subscription fixes that
498 without a second feed; a ticker outside the universe falls back to the default rather than adding a subscription."""
499 ticker = (runtime or {}).get("benchmark_ticker")
500 if not ticker:
501 return None
502 wanted = str(ticker).upper()
503 return next((str(t) for t in universe_tickers if str(t).upper() == wanted), None)
506def resolve_trading_days_per_year(runtime: dict[str, Any] | None) -> int | None:
507 """`runtime.trading_days_per_year` for Lean's statistics (V6.2.0), or None to keep Lean's default (252 under the
508 default brokerage model). The equity curve holds a point for every calendar day once crypto trades on weekends, so
509 365 annualises it the way Lean itself does for a crypto brokerage. Only Lean's reported statistics change."""
510 value = (runtime or {}).get("trading_days_per_year")
511 if value is None:
512 return None
513 try:
514 days = int(value)
515 except (TypeError, ValueError):
516 return None
517 return days if 200 <= days <= 366 else None