Coverage for scripts/lean_smoke/main_option_scenarios.py: 100%
141 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"""Lean smoke scenarios for main.py's option paths on Lean's sample AAPL chain (V6.6.4, Problems #58, #59, #60, #61).
3Every scenario drives the real algorithm class: a subclass calls `_apply_option_multi_leg_order` (and the sweeps) with decisions built by the real sizing functions, once a chain has arrived. It
4is plumbing, not evidence: `options_risk.enabled` stays false in the shipped config, and the sample is a month of one underlying. `SMOKE_JSON {...}` lines report what happened; a step that
5raises is reported and the next step still runs, so one defect doesn't hide the rest. The sample chain is thin on its first days (most structures find no legs), so a structure is tried on
6every bar of the month until it builds, and the scenarios that need a decision wait for the first bar a vertical builds on.
8Project layout (scripts/lean_smoke/run_main_option_scenarios.sh): the repo's main.py is `aq_main.py`, this file is `main.py`, and `scenario.txt` names the scenario:
10 scale #58 sell-side scale-down, scale-up, a second position under max_positions_per_underlying = 2, rotation
11 all43 #59 every registered structure through the real order path, with the margin Lean charged beside the module's own
12 arb #60 the arbitrage detector enabled inside main.py, on the live chain payload
13 assign #61 the assignment sweep over a held short call, then the same position held to its expiry with the auto-close off
14"""
16import dataclasses
17import json
18from builtins import Exception
19from pathlib import Path
21import aq_main
22from AlgorithmImports import * # noqa: F403
24from portfolio.options_margin_sizing import build_margin_position_sizing
25from portfolio.options_strategy import MULTI_LEG_STRATEGY_REGISTRY, build_multi_leg_position_sizing, build_vertical_spread_position_sizing
27SCENARIO = (Path(__file__).with_name("scenario.txt").read_text(encoding="utf-8").strip() if Path(__file__).with_name("scenario.txt").exists() else "scale")
30class OptionScenario(aq_main.AetherQuantAlgorithm):
31 _steps_done = False
32 _probes = 0
34 def _smoke(self, **fields):
35 self.Debug("SMOKE_JSON " + json.dumps({"scenario": SCENARIO, **fields}, default=str))
37 def _attempt(self, step, function):
38 try:
39 result = function()
40 self._smoke(kind="step", step=step, result=result)
41 return result
42 except Exception as error:
43 self._smoke(kind="step_raised", step=step, error=f"{type(error).__name__}: {error}")
44 return None
46 def _chain(self):
47 for symbol in self.symbols:
48 asset = self.asset_lookup[str(symbol)]
49 if asset.get("security_type") != "option":
50 continue
51 rows = (self.latest_options_chains_payload or {}).get(str(asset["underlying_ticker"])) or []
52 if rows:
53 return symbol, str(symbol), rows
54 return None, None, []
56 def _positions(self, key):
57 return [{"kind": r.get("kind"), "strategy": r.get("strategy_name"), "contracts": r.get("contracts")} for r in self.option_positions_by_symbol.get(key, [])]
59 def _order(self, symbol, key, decision, rows, label):
60 before = self.Transactions.OrdersCount
61 result = self._apply_option_multi_leg_order(symbol, key, decision, 0.01, float(rows[0].get("underlying_price") or 0.0), True, label)
62 return {"result": result, "orders_placed": self.Transactions.OrdersCount - before, "positions": self._positions(key), "margin_used": float(self.Portfolio.TotalMarginUsed)}
64 def on_data(self, slice):
65 super().on_data(slice)
66 if self.is_warming_up:
67 return
68 symbol, key, rows = self._chain()
69 if not rows:
70 return
71 self.limit_orders_enabled = False # market branch: the thin sample leaves limits unfilled
72 nav = float(self.Portfolio.TotalPortfolioValue)
73 if SCENARIO == "all43":
74 self._all43_bar(symbol, key, rows, nav)
75 return
76 if self._steps_done:
77 return
78 if SCENARIO in ("arb", "assign"):
79 probe = build_multi_leg_position_sizing("bull_call_spread", "buy", 0.8, rows, nav, max_vega_budget_pct_of_equity=0.02)
80 else:
81 probe = build_vertical_spread_position_sizing("buy", 0.8, rows, nav, max_vega_budget_pct_of_equity=0.02)
82 if probe is None:
83 self._probes += 1
84 if self._probes <= 3:
85 self._smoke(kind="no_decision_yet", bar=str(self.Time.date()), rows=len(rows))
86 return
87 self._steps_done = True
88 self._smoke(kind="chain", bar=str(self.Time.date()), rows=len(rows), nav=nav, expiries=sorted({str(r.get("expiry")) for r in rows})[:6], bars_waited=self._probes)
89 getattr(self, f"_scenario_{SCENARIO}")(symbol, key, rows, nav)
91 # --- #58 -------------------------------------------------------------------------------------------------------------
92 def _scenario_scale(self, symbol, key, rows, nav):
93 def vertical(confidence, vega):
94 return build_vertical_spread_position_sizing("buy", confidence, rows, nav, max_vega_budget_pct_of_equity=vega)
96 first = vertical(0.8, 0.02)
97 self._attempt("enter", lambda: self._order(symbol, key, first, rows, "enter"))
98 bigger = vertical(0.8, 0.05)
99 self._attempt("scale_up", lambda: self._order(symbol, key, bigger, rows, "scale_up"))
100 smaller = vertical(0.8, 0.01)
101 self._attempt("scale_down", lambda: self._order(symbol, key, smaller, rows, "scale_down"))
102 self.options_max_positions_per_underlying = 2
103 other = build_multi_leg_position_sizing("straddle", "buy", 0.8, rows, nav, max_vega_budget_pct_of_equity=0.02)
104 self._attempt("second_position_under_cap_2", lambda: self._order(symbol, key, other, rows, "second") if other else "no straddle decision")
105 third = build_multi_leg_position_sizing("strangle", "buy", 0.8, rows, nav, max_vega_budget_pct_of_equity=0.02)
106 self._attempt("third_position_at_cap", lambda: self._order(symbol, key, third, rows, "third") if third else "no strangle decision")
107 self._smoke(kind="final", positions=self._positions(key), orders=self.Transactions.OrdersCount)
109 # --- #59 -------------------------------------------------------------------------------------------------------------
110 _remaining = None
111 _built = None
113 def _all43_bar(self, symbol, key, rows, nav):
114 if self._remaining is None:
115 self._remaining = list(MULTI_LEG_STRATEGY_REGISTRY)
116 self._built = {}
117 price = float(rows[0].get("underlying_price") or 0.0)
118 for name in list(self._remaining):
119 spec = MULTI_LEG_STRATEGY_REGISTRY[name]
121 def one(name=name, spec=spec):
122 if spec.risk_tier == "vega_budget":
123 decision = build_multi_leg_position_sizing(name, "buy", 0.8, rows, nav, max_vega_budget_pct_of_equity=0.02)
124 else:
125 decision = build_margin_position_sizing(name, "buy", 0.8, rows, price, nav)
126 if decision is None:
127 return None
128 decision = dataclasses.replace(decision, contracts=1) if hasattr(decision, "contracts") else decision
129 before_margin = float(self.Portfolio.TotalMarginUsed)
130 outcome = self._order(symbol, key, decision, rows, name)
131 outcome.update({"tier": spec.risk_tier, "own_margin_estimate": getattr(decision, "margin_requirement", None), "lean_margin_delta": outcome["margin_used"] - before_margin, "bar": str(self.Time.date())})
132 for record in list(self.option_positions_by_symbol.get(key, [])):
133 self._liquidate_option_record(key, record)
134 return outcome
136 try:
137 outcome = one()
138 except Exception as error:
139 self._smoke(kind="step_raised", step=name, error=f"{type(error).__name__}: {error}")
140 self._remaining.remove(name)
141 self._built[name] = {"raised": f"{type(error).__name__}: {error}"}
142 continue
143 if outcome is not None:
144 self._remaining.remove(name)
145 self._built[name] = outcome
146 self._smoke(kind="step", step=name, result=outcome)
148 # --- #60 -------------------------------------------------------------------------------------------------------------
149 def _scenario_arb(self, symbol, key, rows, nav):
150 from risk.asset_class_router import route_multi_leg_option_sizing
152 arbitrage = [name for name, spec in MULTI_LEG_STRATEGY_REGISTRY.items() if spec.risk_tier == "unreachable_arbitrage"]
153 self._smoke(kind="detector_flag", enabled=bool(self.options_arbitrage_detector_enabled), min_bps=self.options_arbitrage_min_mispricing_bps, rows=len(rows), arbitrage_structures=arbitrage)
154 price = float(rows[0].get("underlying_price") or 0.0)
156 def routed(enabled):
157 # the same call main.py makes in _build_dynamic_sizing_payload, with the flags read from the live algorithm object
158 result = route_multi_leg_option_sizing(
159 arbitrage, "buy", 0.8, rows, nav, price, "neutral", self.options_risk_tier_preference, False,
160 target_delta_at_full_confidence=self.options_target_delta_at_full_confidence, max_vega_budget_pct_of_equity=self.options_max_vega_budget_pct_of_equity,
161 short_leg_delta_offset=self.options_short_leg_delta_offset, contract_multiplier=100.0, target_margin_utilization=self.options_margin_target_utilization,
162 max_margin_utilization=self.options_margin_max_utilization, pct_of_underlying_value=self.options_margin_pct_of_underlying_value,
163 min_pct_of_underlying_value=self.options_margin_min_pct_of_underlying_value, current_date=self.Time.date(), risk_free_rate=self.options_risk_free_rate,
164 arbitrage_detector_enabled=enabled, min_mispricing_bps=self.options_arbitrage_min_mispricing_bps,
165 )
166 if result is None:
167 return {"routed": None}
168 decision, extra = result
169 return {"routed": decision.to_dict().get("strategy_name"), "extra": extra}
171 self._attempt("detector_on_as_configured", lambda: routed(bool(self.options_arbitrage_detector_enabled)))
172 self._attempt("detector_off_for_contrast", lambda: routed(False))
173 payload = self._build_options_chains_payload(self.CurrentSlice) if hasattr(self, "_build_options_chains_payload") else None
174 self._smoke(kind="payload", built=payload is not None, underlyings=sorted(payload) if isinstance(payload, dict) else None)
176 # --- #61 -------------------------------------------------------------------------------------------------------------
177 def _scenario_assign(self, symbol, key, rows, nav):
178 entry = build_multi_leg_position_sizing("bull_call_spread", "buy", 0.8, rows, nav, max_vega_budget_pct_of_equity=0.02)
179 self._attempt("enter_short_call_structure", lambda: self._order(symbol, key, entry, rows, "assign") if entry else "no decision")
180 self._attempt("assignment_sweep", lambda: (self._apply_option_assignment_risk_sweep(), {"latest": self.latest_assignment_risk_by_symbol, "positions": self._positions(key)})[1])
181 self.options_auto_close_days_before_expiry = -1 # hold to expiry: Lean's own exercise and assignment model acts, or the position expires
182 self._smoke(kind="held_to_expiry", positions=self._positions(key), expiries=[r.get("expiries") for r in self.option_positions_by_symbol.get(key, [])])
184 def on_end_of_algorithm(self):
185 if SCENARIO == "all43" and self._built is not None:
186 self._smoke(kind="coverage", built=sorted(self._built), never_built=sorted(self._remaining or []), total=len(MULTI_LEG_STRATEGY_REGISTRY))
187 self._smoke(kind="end", orders=self.Transactions.OrdersCount, holdings=[str(h.Symbol) for h in self.Portfolio.Values if h.Invested], cash=float(self.Portfolio.Cash))
188 if hasattr(super(), "on_end_of_algorithm"):
189 super().on_end_of_algorithm()
191 def on_order_event(self, order_event):
192 super().on_order_event(order_event)
193 if order_event.Symbol.SecurityType == SecurityType.Option: # noqa: F405
194 self._smoke(kind="option_event", symbol=str(order_event.Symbol), status=str(order_event.Status), quantity=float(order_event.FillQuantity), price=float(order_event.FillPrice), message=str(order_event.Message))