Coverage for portfolio/options_strategy.py: 100%

572 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Greeks-aware single-leg options position sizing. 

2 

3Satisfies "options need a fundamentally different model output" WITHOUT a 

4new model architecture or training target: the EXISTING direction + 

5confidence (+ magnitude, unused here) prediction every model in this 

6codebase already produces becomes the *input* to a deterministic, non-ML 

7greeks-sizing function. Target delta scales linearly with confidence 

8(0 confidence -> 0 delta -> no position; full confidence -> 

9target_delta_at_full_confidence), and contract count is capped by a vega 

10risk budget (percent of portfolio equity), not a plain notional/weight cap 

11- vega, not price exposure, is the right risk unit for an options position. 

12 

13Deliberately single-leg only (long calls or long puts, never short options 

14or multi-leg spreads/verticals/straddles/condors) - automatic multi-leg 

15spread SELECTION via ML is an explicit non-goal of this pass (see 

16development/Problems.md); this module is the sizing/selection layer for 

17the single-leg case only. 

18 

19Its own package (not risk/ - options_strategy.py needs the whole option 

20chain, not just a scalar signal; not features/ - this is a decision layer, 

21not a feature) - same "new package, off by default, explicit safety-tier 

22extension" precedent portfolio/book_construction.py already established 

23for this codebase's newest decision-layer additions. 

24""" 

25 

26from __future__ import annotations 

27 

28import math 

29from dataclasses import dataclass 

30from typing import TYPE_CHECKING, Any 

31 

32if TYPE_CHECKING: 

33 from datetime import date 

34 

35 

36@dataclass(frozen=True) 

37class OptionsPositionDecision: 

38 """One option order: contracts, right, strike, expiry and the reasons for it.""" 

39 contracts: int 

40 right: str 

41 strike: float 

42 expiry: str 

43 target_delta: float 

44 actual_delta: float 

45 vega_budget_used: float 

46 sizing_reason: str 

47 # The actual Lean contract Symbol (from the selected chain row's 

48 # "symbol" key, see main.py::_build_options_chains_payload()) - needed 

49 # by main.py::_apply_signal() to place an order on the SPECIFIC 

50 # contract, not the canonical option chain Symbol. None whenever the 

51 # chain row didn't carry one (e.g. a synthetic test fixture) - callers 

52 # must treat that as "no order can be placed", never a crash. 

53 contract_symbol: object = None 

54 

55 def to_dict(self) -> dict[str, Any]: 

56 """Deliberately NOT dataclasses.asdict(self) - asdict() deep-copies 

57 every field, and a raw Lean Symbol (a C#/.NET interop object) isn't 

58 guaranteed deepcopy-safe. Manual field access avoids that risk 

59 entirely and stringifies contract_symbol so the result is always 

60 JSON-serializable - required for main.py's dashboard state writer 

61 (see main.py::on_data()'s "dynamic_sizing_for_state" sanitization, 

62 which calls this before signals[...] ever reaches json.dumps()).""" 

63 return { 

64 "contracts": self.contracts, 

65 "right": self.right, 

66 "strike": self.strike, 

67 "expiry": self.expiry, 

68 "target_delta": self.target_delta, 

69 "actual_delta": self.actual_delta, 

70 "vega_budget_used": self.vega_budget_used, 

71 "sizing_reason": self.sizing_reason, 

72 "contract_symbol": str(self.contract_symbol) if self.contract_symbol is not None else None, 

73 } 

74 

75 

76def select_single_leg_contract(available_chain: list[dict], target_delta: float, right: str) -> dict[str, Any] | None: 

77 """Picks the chain entry of the requested `right` ("call"/"put") whose 

78 |delta| is closest to |target_delta| - nearest-strike-by-delta 

79 selection, no ML, no spread construction. Each entry in 

80 available_chain must already carry a computed "delta" key (see 

81 features/options_greeks.py::compute_greeks() - this function does no 

82 pricing itself, purely a selection over already-priced rows). 

83 

84 Returns None when available_chain is empty or has no entry of the 

85 requested right (e.g. IB disabled -> empty chain, or a chain with only 

86 calls when a put was requested) - degrade-to-absent, never a crash.""" 

87 right_normalized = right.lower() 

88 candidates = [ 

89 row for row in available_chain 

90 if str(row.get("right", "")).lower() == right_normalized and row.get("delta") is not None 

91 ] 

92 if not candidates: 

93 return None 

94 return min(candidates, key=lambda row: abs(abs(row["delta"]) - abs(target_delta))) 

95 

96 

97MAX_DEBIT_SHARE_OF_EQUITY = 0.9 

98OPTION_CONTRACT_MULTIPLIER = 100.0 

99 

100 

101def _affordable_contracts(contracts: int, debit_per_share, portfolio_value: float) -> int: 

102 """A vega budget says nothing about premium: 2% of $100k bought 708 contracts of a $1.70 spread, $120k, which Lean refused whole. A credit, or a price 

103 that is missing, leaves the count alone (margin is the broker's check).""" 

104 debit = float(debit_per_share or 0.0) 

105 if debit <= 0.0: 

106 return contracts 

107 return min(contracts, int(portfolio_value * MAX_DEBIT_SHARE_OF_EQUITY // (debit * OPTION_CONTRACT_MULTIPLIER))) 

108 

109 

110def _size_single_leg_contract( 

111 contract: dict[str, Any], 

112 right: str, 

113 target_delta: float, 

114 portfolio_value: float, 

115 max_vega_budget_pct_of_equity: float, 

116 sizing_reason: str, 

117) -> OptionsPositionDecision | None: 

118 """Shared vega-budget arithmetic for a single ALREADY-RESOLVED contract 

119 row - factored out of build_options_position_sizing() so 

120 build_options_position_sizing_for_contract() (V4.4, sizes an 

121 already-HELD contract on its own greeks instead of re-selecting one) 

122 reuses the identical budget math rather than duplicating it. Returns 

123 None when the contract's vega is non-positive or the budget rounds 

124 down to zero contracts - never raises.""" 

125 contract_vega = float(contract.get("vega", 0.0) or 0.0) 

126 if contract_vega <= 0.0: 

127 return None 

128 

129 vega_budget = max_vega_budget_pct_of_equity * portfolio_value 

130 contracts = _affordable_contracts(int(vega_budget // contract_vega), contract.get("ask"), portfolio_value) 

131 if contracts <= 0: 

132 return None 

133 

134 return OptionsPositionDecision( 

135 contracts=contracts, 

136 right=right, 

137 strike=float(contract["strike"]), 

138 expiry=str(contract["expiry"]), 

139 target_delta=target_delta, 

140 actual_delta=float(contract["delta"]), 

141 vega_budget_used=(contracts * contract_vega) / portfolio_value, 

142 sizing_reason=sizing_reason, 

143 contract_symbol=contract.get("symbol"), 

144 ) 

145 

146 

147def build_options_position_sizing( 

148 signal_direction: str, 

149 confidence: float, 

150 available_chain: list[dict], 

151 portfolio_value: float, 

152 target_delta_at_full_confidence: float = 0.60, 

153 max_vega_budget_pct_of_equity: float = 0.02, 

154) -> OptionsPositionDecision | None: 

155 """Translates the existing direction+confidence prediction into ONE 

156 single-leg options position. signal_direction == "buy" selects calls; 

157 {"sell", "short"} select puts (matches 

158 portfolio/book_construction.py's own "buy"/"short" role vocabulary and 

159 main.py::_apply_signal()'s signal_name values). 

160 

161 target_delta scales linearly with confidence: 

162 target_delta_at_full_confidence * confidence. contract count is capped 

163 so total position vega stays under 

164 max_vega_budget_pct_of_equity * portfolio_value / contract_vega - 

165 vega (not notional) is the risk unit an options book should budget 

166 against, since a small-notional far-OTM option can carry 

167 disproportionate vega risk relative to its price. 

168 

169 Returns None when: confidence is 0, signal_direction doesn't map to a 

170 right, available_chain has no usable contract for that right (e.g. IB 

171 disabled -> empty chain, or select_single_leg_contract() found no 

172 match), the selected contract's vega is non-positive, or 

173 portfolio_value is non-positive - degrade-to-absent, never a crash, 

174 matching risk/futures_risk.py::build_futures_position_sizing()'s 

175 "no active signal -> None/zero" convention.""" 

176 confidence = max(0.0, min(float(confidence), 1.0)) 

177 portfolio_value = max(float(portfolio_value), 0.0) 

178 

179 if signal_direction == "buy": 

180 right = "call" 

181 elif signal_direction in ("sell", "short"): 

182 right = "put" 

183 else: 

184 return None 

185 

186 if confidence == 0.0 or portfolio_value <= 0.0: 

187 return None 

188 

189 target_delta = target_delta_at_full_confidence * confidence 

190 contract = select_single_leg_contract(available_chain, target_delta, right) 

191 if contract is None: 

192 return None 

193 

194 return _size_single_leg_contract( 

195 contract, right, target_delta, portfolio_value, max_vega_budget_pct_of_equity, 

196 "delta_targeted_vega_budgeted_sizing", 

197 ) 

198 

199 

200def build_options_position_sizing_for_contract( 

201 held_contract: dict[str, Any], 

202 portfolio_value: float, 

203 max_vega_budget_pct_of_equity: float = 0.02, 

204) -> OptionsPositionDecision | None: 

205 """V4.4 - sizes the EXACT held contract on its own current greeks, 

206 skipping select_single_leg_contract() entirely (no re-selection). 

207 

208 Closes a real architectural gap: without this, a position whose ideal 

209 strike has drifted away from what main.py is currently holding could 

210 only ever be handled by RE-SELECTING a contract (which picks a 

211 DIFFERENT one, forcing a binary rotate-or-freeze choice) - this lets 

212 the held position keep being managed - scaled up or down - on its own 

213 delta/vega, on bars where main.py chooses not to rotate. 

214 

215 held_contract is a live chain row for the currently-held contract - 

216 same shape select_single_leg_contract() returns (must carry 

217 right/strike/expiry/delta/vega/symbol, e.g. found by matching the 

218 held contract_symbol against this bar's available_chain). There is no 

219 fresh confidence-scaled target here - the position already exists - 

220 so target_delta/actual_delta are both just the held contract's own 

221 current delta. 

222 

223 Same degrade-to-None contract as build_options_position_sizing(): 

224 non-positive portfolio_value, missing/non-positive vega, or a budget 

225 that rounds to zero contracts all return None, never raise.""" 

226 portfolio_value = max(float(portfolio_value), 0.0) 

227 if portfolio_value <= 0.0: 

228 return None 

229 

230 right = str(held_contract.get("right", "")).lower() 

231 held_delta = float(held_contract.get("delta", 0.0) or 0.0) 

232 return _size_single_leg_contract( 

233 held_contract, right, held_delta, portfolio_value, max_vega_budget_pct_of_equity, 

234 "held_contract_own_greeks_sizing", 

235 ) 

236 

237 

238# --------------------------------------------------------------------------- 

239# 2-leg vertical spreads (call vertical / bull_call_spread, put vertical / 

240# bear_put_spread) - a deliberately minimal, explicit scope-in of the 

241# "multi-leg spread selection is a non-goal" note above. Straddles/ 

242# strangles/iron condors/butterflies remain out of scope (see 

243# development/Problems.md #29/#38). OptionsPositionDecision/ 

244# select_single_leg_contract()/build_options_position_sizing() above are 

245# completely untouched - these are new, parallel additions, not a 

246# generalization of the single-leg path. 

247# --------------------------------------------------------------------------- 

248 

249 

250@dataclass(frozen=True) 

251class OptionsSpreadLeg: 

252 """One leg of a 2-leg vertical spread. side is "long"/"short" (never a 

253 signed quantity) - keeps this symmetric with how Lean's own 

254 OptionStrategies/Leg model a spread: a strike, a side, a contract.""" 

255 

256 strike: float 

257 right: str # "call" | "put" - both legs of a vertical share this 

258 side: str # "long" | "short" 

259 # Same None-safe contract as OptionsPositionDecision.contract_symbol 

260 # above - a synthetic test fixture with no "symbol" key degrades to 

261 # None, never a crash. 

262 contract_symbol: object = None 

263 

264 

265@dataclass(frozen=True) 

266class OptionsSpreadPositionDecision: 

267 """2-leg vertical spread sibling of OptionsPositionDecision - a 

268 SEPARATE dataclass, not a generalization of it (OptionsPositionDecision 

269 stays single-leg-shaped, every existing caller untouched).""" 

270 

271 strategy_name: str # "bull_call_spread" | "bear_put_spread" - matches Lean's OptionStrategies factory name exactly, main.py uses this to pick which one to call 

272 legs: tuple[OptionsSpreadLeg, OptionsSpreadLeg] # (long, short), exactly 2 for this pass's scope 

273 expiry: str 

274 contracts: int # spread QUANTITY (number of spread units), not a per-leg contract count 

275 # Best-effort diagnostic only (mid/bid-ask based, per spread unit) - 

276 # 0.0 when bid/ask are absent from the chain rows. NEVER gates sizing, 

277 # matching this module's existing "never crash on missing chain 

278 # fields" contract. 

279 net_debit_or_credit: float 

280 net_delta: float # long leg's delta minus short leg's delta, per spread unit 

281 net_vega: float # fraction of portfolio_value the sized position's net vega consumes - same "budget used" semantic as OptionsPositionDecision.vega_budget_used, not a raw per-unit vega number 

282 sizing_reason: str 

283 

284 def to_dict(self) -> dict[str, Any]: 

285 """Same manual-field-access convention as OptionsPositionDecision.to_dict() 

286 above - never dataclasses.asdict(), the legs' contract_symbol 

287 fields are real Lean Symbol objects, not deepcopy-safe.""" 

288 return { 

289 "strategy_name": self.strategy_name, 

290 "legs": [ 

291 { 

292 "strike": leg.strike, 

293 "right": leg.right, 

294 "side": leg.side, 

295 "contract_symbol": str(leg.contract_symbol) if leg.contract_symbol is not None else None, 

296 } 

297 for leg in self.legs 

298 ], 

299 "expiry": self.expiry, 

300 "contracts": self.contracts, 

301 "net_debit_or_credit": self.net_debit_or_credit, 

302 "net_delta": self.net_delta, 

303 "net_vega": self.net_vega, 

304 "sizing_reason": self.sizing_reason, 

305 } 

306 

307 

308def select_vertical_spread_legs( 

309 available_chain: list[dict], 

310 target_delta: float, 

311 right: str, 

312 short_leg_delta_offset: float, 

313) -> tuple[dict, dict] | None: 

314 """Picks two same-expiry, same-right chain rows for a vertical spread: 

315 the long leg via the EXACT same nearest-|delta| selection 

316 select_single_leg_contract() already uses (no new selection logic 

317 duplicated for it), and the short leg as the nearest-|delta| match to 

318 (target_delta - short_leg_delta_offset) among rows of the SAME expiry 

319 as the long leg, filtered to the side that caps risk (strike > long 

320 strike for a call vertical, strike < long strike for a put vertical - 

321 enforced explicitly by filtering on strike, not inferred from delta 

322 ordering, since assuming monotonic real-market delta-vs-strike 

323 ordering shouldn't be load-bearing here). 

324 

325 Returns None when: no usable long leg (same degrade-to-absent 

326 condition as select_single_leg_contract()), or no candidate short leg 

327 exists at the long leg's expiry on the risk-capping side - a chain 

328 with only one usable strike degrades to "no spread", never a crash.""" 

329 long_leg = select_single_leg_contract(available_chain, target_delta, right) 

330 if long_leg is None: 

331 return None 

332 

333 long_strike = float(long_leg["strike"]) 

334 long_expiry = long_leg["expiry"] 

335 right_normalized = right.lower() 

336 short_target_delta = target_delta - short_leg_delta_offset 

337 

338 def _is_risk_capping_side(strike: float) -> bool: 

339 return strike > long_strike if right_normalized == "call" else strike < long_strike 

340 

341 short_candidates = [ 

342 row 

343 for row in available_chain 

344 if str(row.get("right", "")).lower() == right_normalized 

345 and row.get("delta") is not None 

346 and row.get("expiry") == long_expiry 

347 and _is_risk_capping_side(float(row["strike"])) 

348 ] 

349 if not short_candidates: 

350 return None 

351 

352 short_leg = min(short_candidates, key=lambda row: abs(abs(row["delta"]) - abs(short_target_delta))) 

353 return long_leg, short_leg 

354 

355 

356def _size_vertical_spread( 

357 long_row: dict[str, Any], 

358 short_row: dict[str, Any], 

359 right: str, 

360 strategy_name: str, 

361 portfolio_value: float, 

362 max_vega_budget_pct_of_equity: float, 

363 sizing_reason: str, 

364) -> OptionsSpreadPositionDecision | None: 

365 """Shared net-vega-budget arithmetic for an already-resolved leg pair - 

366 factored out of build_vertical_spread_position_sizing() so 

367 build_vertical_spread_position_sizing_for_legs() (V4.4, sizes an 

368 already-HELD spread on its own greeks instead of re-selecting legs) 

369 reuses the identical budget math. Returns None when net_vega is 

370 non-positive or the budget rounds down to zero spread units.""" 

371 long_vega = float(long_row.get("vega", 0.0) or 0.0) 

372 short_vega = float(short_row.get("vega", 0.0) or 0.0) 

373 net_vega_per_spread = long_vega - short_vega 

374 if net_vega_per_spread <= 0.0: 

375 return None 

376 

377 long_ask = long_row.get("ask") 

378 short_bid = short_row.get("bid") 

379 net_debit_or_credit = ( 

380 float(long_ask) - float(short_bid) if long_ask is not None and short_bid is not None else 0.0 

381 ) 

382 vega_budget = max_vega_budget_pct_of_equity * portfolio_value 

383 contracts = _affordable_contracts(int(vega_budget // net_vega_per_spread), net_debit_or_credit, portfolio_value) 

384 if contracts <= 0: 

385 return None 

386 

387 net_delta = float(long_row.get("delta", 0.0) or 0.0) - float(short_row.get("delta", 0.0) or 0.0) 

388 

389 return OptionsSpreadPositionDecision( 

390 strategy_name=strategy_name, 

391 legs=( 

392 OptionsSpreadLeg(strike=float(long_row["strike"]), right=right, side="long", contract_symbol=long_row.get("symbol")), 

393 OptionsSpreadLeg(strike=float(short_row["strike"]), right=right, side="short", contract_symbol=short_row.get("symbol")), 

394 ), 

395 expiry=str(long_row["expiry"]), 

396 contracts=contracts, 

397 net_debit_or_credit=net_debit_or_credit, 

398 net_delta=net_delta, 

399 net_vega=(contracts * net_vega_per_spread) / portfolio_value, 

400 sizing_reason=sizing_reason, 

401 ) 

402 

403 

404def build_vertical_spread_position_sizing( 

405 signal_direction: str, 

406 confidence: float, 

407 available_chain: list[dict], 

408 portfolio_value: float, 

409 target_delta_at_full_confidence: float = 0.60, 

410 short_leg_delta_offset: float = 0.20, 

411 max_vega_budget_pct_of_equity: float = 0.02, 

412) -> OptionsSpreadPositionDecision | None: 

413 """Vertical-spread sibling of build_options_position_sizing() above - 

414 same signal_direction -> right mapping ("buy" -> call vertical/ 

415 bull_call_spread, "sell"/"short" -> put vertical/bear_put_spread), 

416 same confidence-scaled target_delta for the long leg. 

417 

418 Sizes by NET vega (long leg vega minus short leg vega) rather than 

419 the long leg's vega alone - a vertical's defining risk reduction 

420 versus a single leg, and the correct risk unit to budget a spread 

421 position against. Returns None on the same degrade-to-absent 

422 conditions build_options_position_sizing() already documents, plus: 

423 no usable short leg found (select_vertical_spread_legs() returned 

424 None), or net_vega is non-positive (a spread with ~zero or negative 

425 net vega is unsizeable by this budget, not an error).""" 

426 confidence = max(0.0, min(float(confidence), 1.0)) 

427 portfolio_value = max(float(portfolio_value), 0.0) 

428 

429 if signal_direction == "buy": 

430 right, strategy_name = "call", "bull_call_spread" 

431 elif signal_direction in ("sell", "short"): 

432 right, strategy_name = "put", "bear_put_spread" 

433 else: 

434 return None 

435 

436 if confidence == 0.0 or portfolio_value <= 0.0: 

437 return None 

438 

439 target_delta = target_delta_at_full_confidence * confidence 

440 legs = select_vertical_spread_legs(available_chain, target_delta, right, short_leg_delta_offset) 

441 if legs is None: 

442 return None 

443 long_row, short_row = legs 

444 

445 return _size_vertical_spread( 

446 long_row, short_row, right, strategy_name, portfolio_value, max_vega_budget_pct_of_equity, 

447 "delta_targeted_net_vega_budgeted_vertical_spread_sizing", 

448 ) 

449 

450 

451def build_vertical_spread_position_sizing_for_legs( 

452 held_long: dict[str, Any], 

453 held_short: dict[str, Any], 

454 portfolio_value: float, 

455 max_vega_budget_pct_of_equity: float = 0.02, 

456) -> OptionsSpreadPositionDecision | None: 

457 """V4.4 - net-vega sibling of build_options_position_sizing_for_contract() 

458 for a held 2-leg vertical spread: sizes the EXACT held long/short legs 

459 on their own current greeks, skipping select_vertical_spread_legs() 

460 entirely. held_long/held_short are live chain rows for the currently- 

461 held legs (same shape select_vertical_spread_legs() returns each of 

462 its pair). strategy_name/right are derived from held_long's own 

463 "right" field rather than passed in - there is no fresh signal here, 

464 the spread already exists. Same degrade-to-None contract as 

465 build_vertical_spread_position_sizing().""" 

466 portfolio_value = max(float(portfolio_value), 0.0) 

467 if portfolio_value <= 0.0: 

468 return None 

469 

470 right = str(held_long.get("right", "")).lower() 

471 strategy_name = "bull_call_spread" if right == "call" else "bear_put_spread" 

472 return _size_vertical_spread( 

473 held_long, held_short, right, strategy_name, portfolio_value, max_vega_budget_pct_of_equity, 

474 "held_legs_own_greeks_sizing", 

475 ) 

476 

477 

478# --------------------------------------------------------------------------- 

479# V4.5 - full OptionStrategies coverage (41 additional factories beyond the 

480# 2-leg verticals above). Everything above this line is UNTOUCHED - existing 

481# callers (single-leg, bull_call_spread/bear_put_spread) keep working 

482# byte-identically; this section is purely additive. 

483# 

484# Design: one small MULTI_LEG_STRATEGY_REGISTRY data table (one StrategySpec 

485# per factory, sourced directly from QuantConnect.Securities.Option. 

486# OptionStrategies.cs - the real Lean C# leg quantities, not guessed from 

487# the factory's positional strike names) replaces what would otherwise be 

488# 41 near-duplicate selection/sizing functions. A handful of shared 

489# shape-family selectors (vertical/straddle/strangle/butterfly/iron/ 

490# calendar/backspread/ladder/naked/covered-protective) dispatch off each 

491# StrategySpec's `shape_family` tag, parameterized by its `legs` (each 

492# already carrying the correct long/short side and call/put right straight 

493# from the registry) - so e.g. all 4 ladder variants or all 4 calendar 

494# variants share ONE selector implementation apiece, not four. 

495# 

496# Two real risk-tier corrections were found while transcribing the ACTUAL 

497# Lean leg quantities (not assumed from strike-name positions alone) - 

498# recorded here since they contradict this feature's own initial plan text: 

499# - Of the 4 ladder strategies, only bull_call_ladder/bear_put_ladder are 

500# genuinely net-short (one extra uncovered leg beyond a 1:1 hedge) and 

501# unbounded-risk; bear_call_ladder/bull_put_ladder are net-long (an 

502# extra long leg only adds cost, never risk) and belong in the SAME 

503# vega-budget tier as verticals/butterflies, not the margin family. 

504# - Of the 4 backspread strategies, short_call_backspread/ 

505# short_put_backspread are the genuinely unbounded ones (inverting a 

506# backspread turns its 1:2 long-heavy ratio into a 1:2 SHORT-heavy 

507# ratio) - naked-style margin, not the bounded-max-loss formula; 

508# call_backspread/put_backspread (the un-inverted, long-heavy originals) 

509# really are bounded and keep the bounded-max-loss treatment. 

510# See development/Problems.md for the full writeup. 

511# --------------------------------------------------------------------------- 

512 

513 

514 

515@dataclass(frozen=True) 

516class MultiLegSpec: 

517 """One leg of a multi-leg OptionStrategy factory result. `side`/`ratio` 

518 are transcribed directly from OptionStrategies.cs's actual Quantity 

519 field for that leg (e.g. a butterfly's body leg is ratio=2, side= 

520 "short" for a long butterfly) - never inferred from the factory's 

521 positional strike-name alone (a real bug this pass found and fixed, 

522 see the module-level note above). `is_anchor` marks a leg selected 

523 FIRST, by confidence-scaled target delta; every other leg in the same 

524 strategy is selected as a strike/expiry offset from an anchor leg. 

525 Iron condor/butterfly have TWO anchor legs (short_put, short_call) - 

526 one per composed vertical selection.""" 

527 

528 role: str # unique per leg within one strategy, e.g. "short_call" 

529 right: str # "call" | "put" 

530 side: str # "long" | "short" - the real Lean leg direction 

531 ratio: int # contracts per spread unit (1, or 2 for a butterfly body / backspread's heavy leg) 

532 strike_role: str # key into the strikes-by-role dict this leg's strike is selected/passed under 

533 expiry_role: str = "single" # "single" | "near" | "far" 

534 is_anchor: bool = False 

535 

536 

537@dataclass(frozen=True) 

538class StrategySpec: 

539 """One registry entry - everything main.py's generic order-placement 

540 layer needs to resolve and call the real OptionStrategies factory, plus 

541 everything the shape-family selectors below need to pick strikes/ 

542 expiries for it. factory_name is resolved via 

543 getattr(OptionStrategies, factory_name) at the main.py call site (never 

544 imported per-strategy here - this module must not import Lean's 

545 AlgorithmImports, matching every other pure function in this file).""" 

546 

547 factory_name: str 

548 arg_order: tuple[str, ...] # exact positional strike-role order the real factory expects 

549 has_expiry_pair: bool 

550 legs: tuple[MultiLegSpec, ...] 

551 shape_family: str # dispatch key for the shared selectors below 

552 risk_tier: str # "vega_budget" | "margin_naked" | "margin_uncovered_leg" | "margin_bounded_backspread" | "covered_protective" | "unreachable_arbitrage" 

553 covering_equity_side: str | None = None # "long" | "short" - only set for risk_tier == "covered_protective" 

554 

555 

556def _leg(role, right, side, ratio, strike_role, expiry_role="single", is_anchor=False): 

557 return MultiLegSpec(role, right, side, ratio, strike_role, expiry_role, is_anchor) 

558 

559 

560MULTI_LEG_STRATEGY_REGISTRY: dict[str, StrategySpec] = { 

561 # -- existing 2-leg verticals (registry entries needed so main.py's 

562 # generic order-placement/liquidation/bookkeeping can treat these 

563 # uniformly with the other 41; their SIZING decision stays the 

564 # dedicated build_vertical_spread_position_sizing() above, untouched) -- 

565 "bull_call_spread": StrategySpec( 

566 "bull_call_spread", ("long", "short"), False, 

567 (_leg("long", "call", "long", 1, "long", is_anchor=True), _leg("short", "call", "short", 1, "short")), 

568 "vertical", "vega_budget", 

569 ), 

570 "bear_put_spread": StrategySpec( 

571 "bear_put_spread", ("long", "short"), False, 

572 (_leg("long", "put", "long", 1, "long", is_anchor=True), _leg("short", "put", "short", 1, "short")), 

573 "vertical", "vega_budget", 

574 ), 

575 # -- credit verticals -- 

576 "bear_call_spread": StrategySpec( 

577 "bear_call_spread", ("short", "long"), False, 

578 (_leg("short", "call", "short", 1, "short", is_anchor=True), _leg("long", "call", "long", 1, "long")), 

579 "vertical", "vega_budget", 

580 ), 

581 "bull_put_spread": StrategySpec( 

582 "bull_put_spread", ("short", "long"), False, 

583 (_leg("short", "put", "short", 1, "short", is_anchor=True), _leg("long", "put", "long", 1, "long")), 

584 "vertical", "vega_budget", 

585 ), 

586 # -- straddles -- 

587 "straddle": StrategySpec( 

588 "straddle", ("strike",), False, 

589 (_leg("call", "call", "long", 1, "strike", is_anchor=True), _leg("put", "put", "long", 1, "strike")), 

590 "straddle", "vega_budget", 

591 ), 

592 "short_straddle": StrategySpec( 

593 "short_straddle", ("strike",), False, 

594 (_leg("call", "call", "short", 1, "strike", is_anchor=True), _leg("put", "put", "short", 1, "strike")), 

595 "straddle", "margin_naked", 

596 ), 

597 # -- strangles -- 

598 "strangle": StrategySpec( 

599 "strangle", ("call", "put"), False, 

600 (_leg("call", "call", "long", 1, "call", is_anchor=True), _leg("put", "put", "long", 1, "put")), 

601 "strangle", "vega_budget", 

602 ), 

603 "short_strangle": StrategySpec( 

604 "short_strangle", ("call", "put"), False, 

605 (_leg("call", "call", "short", 1, "call", is_anchor=True), _leg("put", "put", "short", 1, "put")), 

606 "strangle", "margin_naked", 

607 ), 

608 # -- call butterflies (butterfly_call/call_butterfly are real, separate 

609 # aliased factory attrs on OptionStrategies - both registered) -- 

610 "butterfly_call": StrategySpec( 

611 "butterfly_call", ("higher", "middle", "lower"), False, 

612 ( 

613 _leg("higher", "call", "long", 1, "higher"), 

614 _leg("middle", "call", "short", 2, "middle", is_anchor=True), 

615 _leg("lower", "call", "long", 1, "lower"), 

616 ), 

617 "butterfly", "vega_budget", 

618 ), 

619 "call_butterfly": StrategySpec( 

620 "call_butterfly", ("higher", "middle", "lower"), False, 

621 ( 

622 _leg("higher", "call", "long", 1, "higher"), 

623 _leg("middle", "call", "short", 2, "middle", is_anchor=True), 

624 _leg("lower", "call", "long", 1, "lower"), 

625 ), 

626 "butterfly", "vega_budget", 

627 ), 

628 "short_butterfly_call": StrategySpec( 

629 "short_butterfly_call", ("higher", "middle", "lower"), False, 

630 ( 

631 _leg("higher", "call", "short", 1, "higher"), 

632 _leg("middle", "call", "long", 2, "middle", is_anchor=True), 

633 _leg("lower", "call", "short", 1, "lower"), 

634 ), 

635 "butterfly", "vega_budget", 

636 ), 

637 # -- put butterflies -- 

638 "butterfly_put": StrategySpec( 

639 "butterfly_put", ("higher", "middle", "lower"), False, 

640 ( 

641 _leg("higher", "put", "long", 1, "higher"), 

642 _leg("middle", "put", "short", 2, "middle", is_anchor=True), 

643 _leg("lower", "put", "long", 1, "lower"), 

644 ), 

645 "butterfly", "vega_budget", 

646 ), 

647 "put_butterfly": StrategySpec( 

648 "put_butterfly", ("higher", "middle", "lower"), False, 

649 ( 

650 _leg("higher", "put", "long", 1, "higher"), 

651 _leg("middle", "put", "short", 2, "middle", is_anchor=True), 

652 _leg("lower", "put", "long", 1, "lower"), 

653 ), 

654 "butterfly", "vega_budget", 

655 ), 

656 "short_butterfly_put": StrategySpec( 

657 "short_butterfly_put", ("higher", "middle", "lower"), False, 

658 ( 

659 _leg("higher", "put", "short", 1, "higher"), 

660 _leg("middle", "put", "long", 2, "middle", is_anchor=True), 

661 _leg("lower", "put", "short", 1, "lower"), 

662 ), 

663 "butterfly", "vega_budget", 

664 ), 

665 # -- calendar spreads (2 distinct expiries, 1 strike role shared by both legs) -- 

666 "call_calendar_spread": StrategySpec( 

667 "call_calendar_spread", ("strike",), True, 

668 ( 

669 _leg("near", "call", "short", 1, "strike", "near", is_anchor=True), 

670 _leg("far", "call", "long", 1, "strike", "far"), 

671 ), 

672 "calendar", "vega_budget", 

673 ), 

674 "short_call_calendar_spread": StrategySpec( 

675 "short_call_calendar_spread", ("strike",), True, 

676 ( 

677 _leg("near", "call", "long", 1, "strike", "near", is_anchor=True), 

678 _leg("far", "call", "short", 1, "strike", "far"), 

679 ), 

680 "calendar", "vega_budget", 

681 ), 

682 "put_calendar_spread": StrategySpec( 

683 "put_calendar_spread", ("strike",), True, 

684 ( 

685 _leg("near", "put", "short", 1, "strike", "near", is_anchor=True), 

686 _leg("far", "put", "long", 1, "strike", "far"), 

687 ), 

688 "calendar", "vega_budget", 

689 ), 

690 "short_put_calendar_spread": StrategySpec( 

691 "short_put_calendar_spread", ("strike",), True, 

692 ( 

693 _leg("near", "put", "long", 1, "strike", "near", is_anchor=True), 

694 _leg("far", "put", "short", 1, "strike", "far"), 

695 ), 

696 "calendar", "vega_budget", 

697 ), 

698 # -- iron condors (composed from 2 independent credit verticals) -- 

699 "iron_condor": StrategySpec( 

700 "iron_condor", ("long_put", "short_put", "short_call", "long_call"), False, 

701 ( 

702 _leg("long_put", "put", "long", 1, "long_put"), 

703 _leg("short_put", "put", "short", 1, "short_put", is_anchor=True), 

704 _leg("short_call", "call", "short", 1, "short_call", is_anchor=True), 

705 _leg("long_call", "call", "long", 1, "long_call"), 

706 ), 

707 "iron_condor", "vega_budget", 

708 ), 

709 "short_iron_condor": StrategySpec( 

710 "short_iron_condor", ("short_put", "long_put", "long_call", "short_call"), False, 

711 ( 

712 _leg("short_put", "put", "short", 1, "short_put"), 

713 _leg("long_put", "put", "long", 1, "long_put", is_anchor=True), 

714 _leg("long_call", "call", "long", 1, "long_call", is_anchor=True), 

715 _leg("short_call", "call", "short", 1, "short_call"), 

716 ), 

717 "iron_condor", "vega_budget", 

718 ), 

719 # -- iron butterflies (shared ATM strike between the 2 short/long-middle legs) -- 

720 "iron_butterfly": StrategySpec( 

721 "iron_butterfly", ("otm_put", "atm", "otm_call"), False, 

722 ( 

723 _leg("long_put", "put", "long", 1, "otm_put"), 

724 _leg("short_put", "put", "short", 1, "atm", is_anchor=True), 

725 _leg("short_call", "call", "short", 1, "atm", is_anchor=True), 

726 _leg("long_call", "call", "long", 1, "otm_call"), 

727 ), 

728 "iron_butterfly", "vega_budget", 

729 ), 

730 "short_iron_butterfly": StrategySpec( 

731 "short_iron_butterfly", ("otm_put", "atm", "otm_call"), False, 

732 ( 

733 _leg("short_put", "put", "short", 1, "otm_put", is_anchor=True), 

734 _leg("long_put", "put", "long", 1, "atm"), 

735 _leg("long_call", "call", "long", 1, "atm"), 

736 _leg("short_call", "call", "short", 1, "otm_call", is_anchor=True), 

737 ), 

738 "iron_butterfly", "vega_budget", 

739 ), 

740 # -- backspreads (1:2 ratio; call_backspread/put_backspread are the 

741 # genuinely bounded, long-heavy originals; short_* are the inverted, 

742 # genuinely unbounded, short-heavy variants - see module note) -- 

743 "call_backspread": StrategySpec( 

744 "call_backspread", ("lower", "higher"), False, 

745 ( 

746 _leg("lower", "call", "short", 1, "lower", is_anchor=True), 

747 _leg("higher", "call", "long", 2, "higher"), 

748 ), 

749 "backspread", "margin_bounded_backspread", 

750 ), 

751 "short_call_backspread": StrategySpec( 

752 "short_call_backspread", ("lower", "higher"), False, 

753 ( 

754 _leg("lower", "call", "long", 1, "lower", is_anchor=True), 

755 _leg("higher", "call", "short", 2, "higher"), 

756 ), 

757 "backspread", "margin_naked", 

758 ), 

759 "put_backspread": StrategySpec( 

760 "put_backspread", ("higher", "lower"), False, 

761 ( 

762 _leg("higher", "put", "short", 1, "higher", is_anchor=True), 

763 _leg("lower", "put", "long", 2, "lower"), 

764 ), 

765 "backspread", "margin_bounded_backspread", 

766 ), 

767 "short_put_backspread": StrategySpec( 

768 "short_put_backspread", ("higher", "lower"), False, 

769 ( 

770 _leg("higher", "put", "long", 1, "higher", is_anchor=True), 

771 _leg("lower", "put", "short", 2, "lower"), 

772 ), 

773 "backspread", "margin_naked", 

774 ), 

775 # -- ladders (1:1:1; bear_call_ladder/bull_put_ladder are net-long and 

776 # bounded; bull_call_ladder/bear_put_ladder are net-short and 

777 # unbounded - see module note) -- 

778 "bear_call_ladder": StrategySpec( 

779 "bear_call_ladder", ("lower", "middle", "higher"), False, 

780 ( 

781 _leg("lower", "call", "short", 1, "lower", is_anchor=True), 

782 _leg("middle", "call", "long", 1, "middle"), 

783 _leg("higher", "call", "long", 1, "higher"), 

784 ), 

785 "ladder", "vega_budget", 

786 ), 

787 "bull_call_ladder": StrategySpec( 

788 "bull_call_ladder", ("lower", "middle", "higher"), False, 

789 ( 

790 _leg("lower", "call", "long", 1, "lower", is_anchor=True), 

791 _leg("middle", "call", "short", 1, "middle"), 

792 _leg("higher", "call", "short", 1, "higher"), 

793 ), 

794 "ladder", "margin_uncovered_leg", 

795 ), 

796 "bear_put_ladder": StrategySpec( 

797 "bear_put_ladder", ("higher", "middle", "lower"), False, 

798 ( 

799 _leg("higher", "put", "long", 1, "higher", is_anchor=True), 

800 _leg("middle", "put", "short", 1, "middle"), 

801 _leg("lower", "put", "short", 1, "lower"), 

802 ), 

803 "ladder", "margin_uncovered_leg", 

804 ), 

805 "bull_put_ladder": StrategySpec( 

806 "bull_put_ladder", ("higher", "middle", "lower"), False, 

807 ( 

808 _leg("higher", "put", "short", 1, "higher", is_anchor=True), 

809 _leg("middle", "put", "long", 1, "middle"), 

810 _leg("lower", "put", "long", 1, "lower"), 

811 ), 

812 "ladder", "vega_budget", 

813 ), 

814 # -- naked single-leg shorts -- 

815 "naked_call": StrategySpec( 

816 "naked_call", ("strike",), False, (_leg("call", "call", "short", 1, "strike", is_anchor=True),), 

817 "naked", "margin_naked", 

818 ), 

819 "naked_put": StrategySpec( 

820 "naked_put", ("strike",), False, (_leg("put", "put", "short", 1, "strike", is_anchor=True),), 

821 "naked", "margin_naked", 

822 ), 

823 # -- covered/protective/collar (equity leg tracked separately, see 

824 # main.py's corrected cross-asset design - never the bundled factory) -- 

825 "covered_call": StrategySpec( 

826 "covered_call", ("strike",), False, (_leg("call", "call", "short", 1, "strike", is_anchor=True),), 

827 "covered_protective", "covered_protective", covering_equity_side="long", 

828 ), 

829 "covered_put": StrategySpec( 

830 "covered_put", ("strike",), False, (_leg("put", "put", "short", 1, "strike", is_anchor=True),), 

831 "covered_protective", "covered_protective", covering_equity_side="short", 

832 ), 

833 "protective_call": StrategySpec( 

834 "protective_call", ("strike",), False, (_leg("call", "call", "long", 1, "strike", is_anchor=True),), 

835 "covered_protective", "covered_protective", covering_equity_side="short", 

836 ), 

837 "protective_put": StrategySpec( 

838 "protective_put", ("strike",), False, (_leg("put", "put", "long", 1, "strike", is_anchor=True),), 

839 "covered_protective", "covered_protective", covering_equity_side="long", 

840 ), 

841 "protective_collar": StrategySpec( 

842 "protective_collar", ("call", "put"), False, 

843 ( 

844 _leg("call", "call", "short", 1, "call", is_anchor=True), 

845 _leg("put", "put", "long", 1, "put", is_anchor=True), 

846 ), 

847 "collar", "covered_protective", covering_equity_side="long", 

848 ), 

849 # -- arbitrage (stubbed - registry/selector/tests exist; never in the 

850 # default enabled_strategy_names, and no signal source ever produces 

851 # these strategy_name values, see development/Problems.md) -- 

852 "box_spread": StrategySpec( 

853 "box_spread", ("higher", "lower"), False, 

854 ( 

855 _leg("long_put", "put", "long", 1, "higher", is_anchor=True), 

856 _leg("short_put", "put", "short", 1, "lower"), 

857 _leg("long_call", "call", "long", 1, "lower"), 

858 _leg("short_call", "call", "short", 1, "higher"), 

859 ), 

860 "arbitrage_box", "unreachable_arbitrage", 

861 ), 

862 "short_box_spread": StrategySpec( 

863 "short_box_spread", ("higher", "lower"), False, 

864 ( 

865 _leg("short_put", "put", "short", 1, "higher", is_anchor=True), 

866 _leg("long_put", "put", "long", 1, "lower"), 

867 _leg("short_call", "call", "short", 1, "lower"), 

868 _leg("long_call", "call", "long", 1, "higher"), 

869 ), 

870 "arbitrage_box", "unreachable_arbitrage", 

871 ), 

872 "conversion": StrategySpec( 

873 "conversion", ("strike",), False, 

874 ( 

875 _leg("short_call", "call", "short", 1, "strike", is_anchor=True), 

876 _leg("long_put", "put", "long", 1, "strike"), 

877 ), 

878 "arbitrage_conversion", "unreachable_arbitrage", covering_equity_side="long", 

879 ), 

880 "reverse_conversion": StrategySpec( 

881 "reverse_conversion", ("strike",), False, 

882 ( 

883 _leg("long_call", "call", "long", 1, "strike", is_anchor=True), 

884 _leg("short_put", "put", "short", 1, "strike"), 

885 ), 

886 "arbitrage_conversion", "unreachable_arbitrage", covering_equity_side="short", 

887 ), 

888 "jelly_roll": StrategySpec( 

889 "jelly_roll", ("strike",), True, 

890 ( 

891 _leg("near_call", "call", "short", 1, "strike", "near", is_anchor=True), 

892 _leg("far_call", "call", "long", 1, "strike", "far"), 

893 _leg("near_put", "put", "long", 1, "strike", "near"), 

894 _leg("far_put", "put", "short", 1, "strike", "far"), 

895 ), 

896 "arbitrage_jelly_roll", "unreachable_arbitrage", 

897 ), 

898 "short_jelly_roll": StrategySpec( 

899 "short_jelly_roll", ("strike",), True, 

900 ( 

901 _leg("near_call", "call", "long", 1, "strike", "near", is_anchor=True), 

902 _leg("far_call", "call", "short", 1, "strike", "far"), 

903 _leg("near_put", "put", "short", 1, "strike", "near"), 

904 _leg("far_put", "put", "long", 1, "strike", "far"), 

905 ), 

906 "arbitrage_jelly_roll", "unreachable_arbitrage", 

907 ), 

908} 

909 

910 

911def group_chain_by_expiry(available_chain: list[dict]) -> dict[str, list[dict]]: 

912 """Single O(n) pass grouping chain rows by expiry - built ONCE per 

913 selector call and reused for every leg lookup within it, rather than 

914 re-scanning the full chain per leg (this is the "latency-efficient" 

915 requirement for a function that runs every bar, per candidate 

916 strategy, per symbol). Also the mechanism that makes expiry-anchoring 

917 possible: every leg after the anchor is selected ONLY from 

918 grouped[anchor_expiry], never re-scanning the other expiries. 

919 

920 Public (V4.9 Priority 3, renamed from the original _group_chain_by_expiry) 

921 since risk/asset_class_router.py::route_multi_leg_option_sizing() now 

922 calls this ONCE per routing call (not per selector call) when the 

923 calendar shape family is in play, avoiding a repeated regroup of the 

924 same chain across multiple candidate strategies tried in the same 

925 bar - see select_calendar_legs()'s/select_arbitrage_jelly_roll_legs()'s 

926 own grouped_chain_by_expiry parameter.""" 

927 grouped: dict[str, list[dict]] = {} 

928 for row in available_chain: 

929 grouped.setdefault(row.get("expiry"), []).append(row) 

930 return grouped 

931 

932 

933def _nearest_by_delta(rows: list[dict], right: str, target_delta: float) -> dict[str, Any] | None: 

934 candidates = [r for r in rows if str(r.get("right", "")).lower() == right and r.get("delta") is not None] 

935 if not candidates: 

936 return None 

937 return min(candidates, key=lambda r: abs(abs(r["delta"]) - abs(target_delta))) 

938 

939 

940def _nearest_by_strike(rows: list[dict], right: str, target_strike: float) -> dict[str, Any] | None: 

941 candidates = [r for r in rows if str(r.get("right", "")).lower() == right and r.get("strike") is not None] 

942 if not candidates: 

943 return None 

944 return min(candidates, key=lambda r: abs(float(r["strike"]) - target_strike)) 

945 

946 

947def _outer_strike_predicate(right: str, anchor_strike: float): 

948 """True for a strike further OTM than anchor_strike, for `right` - 

949 higher for calls, lower for puts. Pure geometry, independent of which 

950 leg is long/short (the fix for the debit/credit leg-role inversion 

951 bug: the OLD select_vertical_spread_legs() baked "outer == short" in 

952 by always returning long=anchor - this predicate is direction-neutral, 

953 role assignment happens separately in select_vertical_legs() below).""" 

954 if right == "call": 

955 return lambda strike: strike > anchor_strike 

956 return lambda strike: strike < anchor_strike 

957 

958 

959def select_vertical_legs( 

960 spec: StrategySpec, available_chain: list[dict], target_delta: float, short_leg_delta_offset: float = 0.20, 

961) -> dict[str, dict] | None: 

962 """Shared 2-leg vertical selector for shape_family == "vertical" - 

963 covers debit (bull_call_spread/bear_put_spread) AND credit 

964 (bear_call_spread/bull_put_spread) verticals identically: the ANCHOR 

965 leg (spec's is_anchor=True role) is picked by nearest-|delta| exactly 

966 like the existing single-leg selector; the OUTER leg is the 

967 nearest-|delta - short_leg_delta_offset| match among the SAME expiry's 

968 rows on the further-OTM side (_outer_strike_predicate). Which role 

969 ends up "long" vs "short" is irrelevant to this SELECTION geometry - 

970 that's already fixed by the registry (spec.legs[*].side) - so the same 

971 function is correct for both debit and credit shapes, closing the 

972 debit/credit leg-role-inversion bug without needing 2 separate 

973 selection algorithms.""" 

974 anchor_leg = next(leg for leg in spec.legs if leg.is_anchor) 

975 outer_leg = next(leg for leg in spec.legs if not leg.is_anchor) 

976 

977 anchor_row = _nearest_by_delta(available_chain, anchor_leg.right, target_delta) 

978 if anchor_row is None: 

979 return None 

980 anchor_expiry = anchor_row.get("expiry") 

981 anchor_strike = float(anchor_row["strike"]) 

982 

983 same_expiry_rows = [r for r in available_chain if r.get("expiry") == anchor_expiry] 

984 is_outer = _outer_strike_predicate(outer_leg.right, anchor_strike) 

985 outer_candidates = [ 

986 r for r in same_expiry_rows 

987 if str(r.get("right", "")).lower() == outer_leg.right and r.get("delta") is not None 

988 and is_outer(float(r["strike"])) 

989 ] 

990 if not outer_candidates: 

991 return None 

992 outer_target_delta = target_delta - short_leg_delta_offset 

993 outer_row = min(outer_candidates, key=lambda r: abs(abs(r["delta"]) - abs(outer_target_delta))) 

994 return {anchor_leg.role: anchor_row, outer_leg.role: outer_row} 

995 

996 

997def select_straddle_legs(spec: StrategySpec, available_chain: list[dict], target_delta: float) -> dict[str, dict] | None: 

998 """shape_family == "straddle" (straddle/short_straddle) - same-strike, 

999 same-expiry call+put pair. Anchors on the call leg by delta, then 

1000 requires a put at the EXACT same strike/expiry (never a nearest-delta 

1001 put pick - a straddle's defining property is one shared strike).""" 

1002 call_leg = next(leg for leg in spec.legs if leg.right == "call") 

1003 put_leg = next(leg for leg in spec.legs if leg.right == "put") 

1004 

1005 call_row = _nearest_by_delta(available_chain, "call", target_delta) 

1006 if call_row is None: 

1007 return None 

1008 same_expiry_rows = [r for r in available_chain if r.get("expiry") == call_row.get("expiry")] 

1009 put_row = next( 

1010 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == "put" and float(r.get("strike", -1)) == float(call_row["strike"])), 

1011 None, 

1012 ) 

1013 if put_row is None: 

1014 return None 

1015 return {call_leg.role: call_row, put_leg.role: put_row} 

1016 

1017 

1018def select_strangle_legs( 

1019 spec: StrategySpec, available_chain: list[dict], target_delta: float, strangle_delta_offset: float = 0.15, 

1020) -> dict[str, dict] | None: 

1021 """shape_family == "strangle" (strangle/short_strangle) - offset-strike, 

1022 same-expiry call+put pair (call strike above put strike, enforced by 

1023 _outer_strike_predicate-style filtering anchored on the call leg's 

1024 expiry, so both legs land on the same expiry by construction).""" 

1025 call_leg = next(leg for leg in spec.legs if leg.right == "call") 

1026 put_leg = next(leg for leg in spec.legs if leg.right == "put") 

1027 

1028 call_row = _nearest_by_delta(available_chain, "call", target_delta) 

1029 if call_row is None: 

1030 return None 

1031 call_strike = float(call_row["strike"]) 

1032 same_expiry_rows = [r for r in available_chain if r.get("expiry") == call_row.get("expiry")] 

1033 put_candidates = [ 

1034 r for r in same_expiry_rows 

1035 if str(r.get("right", "")).lower() == "put" and r.get("delta") is not None and float(r["strike"]) < call_strike 

1036 ] 

1037 if not put_candidates: 

1038 return None 

1039 put_target_delta = target_delta - strangle_delta_offset 

1040 put_row = min(put_candidates, key=lambda r: abs(abs(r["delta"]) - abs(put_target_delta))) 

1041 return {call_leg.role: call_row, put_leg.role: put_row} 

1042 

1043 

1044def select_butterfly_legs( 

1045 spec: StrategySpec, 

1046 available_chain: list[dict], 

1047 target_delta: float, 

1048 wing_width_delta_offset: float = 0.20, 

1049 max_strike_asymmetry_tolerance: float = 0.15, 

1050) -> dict[str, dict] | None: 

1051 """shape_family == "butterfly" - middle strike anchored by delta (the 

1052 2x-ratio body leg), then wings picked as the nearest available strikes 

1053 ABOVE/BELOW it within the same expiry, degrading to None (never a 

1054 forced/asymmetric fill) when the two wing strikes aren't within 

1055 max_strike_asymmetry_tolerance of being equidistant from the middle - 

1056 real discrete strike ladders widen away from spot, so "best-effort 

1057 near-symmetric" is documented here as the honest contract, not exact 

1058 equidistance.""" 

1059 middle_leg = next(leg for leg in spec.legs if leg.is_anchor) 

1060 higher_leg = next(leg for leg in spec.legs if leg.strike_role == "higher") 

1061 lower_leg = next(leg for leg in spec.legs if leg.strike_role == "lower") 

1062 right = middle_leg.right 

1063 

1064 middle_row = _nearest_by_delta(available_chain, right, target_delta) 

1065 if middle_row is None: 

1066 return None 

1067 middle_strike = float(middle_row["strike"]) 

1068 same_expiry_rows = [r for r in available_chain if r.get("expiry") == middle_row.get("expiry")] 

1069 

1070 higher_candidates = sorted( 

1071 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == right and float(r.get("strike", middle_strike)) > middle_strike), 

1072 key=lambda r: float(r["strike"]), 

1073 ) 

1074 lower_candidates = sorted( 

1075 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == right and float(r.get("strike", middle_strike)) < middle_strike), 

1076 key=lambda r: float(r["strike"]), 

1077 reverse=True, 

1078 ) 

1079 if not higher_candidates or not lower_candidates: 

1080 return None 

1081 higher_row = higher_candidates[0] 

1082 lower_row = lower_candidates[0] 

1083 

1084 higher_width = float(higher_row["strike"]) - middle_strike 

1085 lower_width = middle_strike - float(lower_row["strike"]) 

1086 wider, narrower = max(higher_width, lower_width), min(higher_width, lower_width) 

1087 if wider <= 0 or abs(wider - narrower) / wider > max_strike_asymmetry_tolerance: 

1088 return None 

1089 

1090 return {middle_leg.role: middle_row, higher_leg.role: higher_row, lower_leg.role: lower_row} 

1091 

1092 

1093def select_iron_condor_legs( 

1094 spec: StrategySpec, 

1095 available_chain: list[dict], 

1096 target_delta: float, 

1097 short_leg_delta_offset: float = 0.20, 

1098 wing_delta_offset: float = 0.10, 

1099) -> dict[str, dict] | None: 

1100 """shape_family == "iron_condor" - composed from 2 independent 

1101 credit-vertical-style selections (put side, call side), both anchored 

1102 to the SAME expiry (the put side's anchor expiry is picked first and 

1103 passed down to the call side, closing the same expiry-drift risk 

1104 select_vertical_legs() closes for a plain 2-leg vertical). The inner legs are the registry's anchors: the shorts of an 

1105 iron condor, the longs of a short iron condor, whose short legs are the outer wings. Lean's factory rejects anything 

1106 but ascending strikes.""" 

1107 inner_put_leg = next(leg for leg in spec.legs if leg.right == "put" and leg.is_anchor) 

1108 outer_put_leg = next(leg for leg in spec.legs if leg.right == "put" and not leg.is_anchor) 

1109 inner_call_leg = next(leg for leg in spec.legs if leg.right == "call" and leg.is_anchor) 

1110 outer_call_leg = next(leg for leg in spec.legs if leg.right == "call" and not leg.is_anchor) 

1111 

1112 inner_put_row = _nearest_by_delta(available_chain, "put", target_delta) 

1113 if inner_put_row is None: 

1114 return None 

1115 anchor_expiry = inner_put_row.get("expiry") 

1116 same_expiry_rows = [r for r in available_chain if r.get("expiry") == anchor_expiry] 

1117 inner_put_strike = float(inner_put_row["strike"]) 

1118 

1119 outer_put_candidates = [ 

1120 r for r in same_expiry_rows 

1121 if str(r.get("right", "")).lower() == "put" and r.get("delta") is not None and float(r["strike"]) < inner_put_strike 

1122 ] 

1123 if not outer_put_candidates: 

1124 return None 

1125 outer_put_row = min(outer_put_candidates, key=lambda r: abs(abs(r["delta"]) - abs(target_delta - wing_delta_offset))) 

1126 

1127 inner_call_row = _nearest_by_delta(same_expiry_rows, "call", target_delta - short_leg_delta_offset) 

1128 if inner_call_row is None: 

1129 return None 

1130 inner_call_strike = float(inner_call_row["strike"]) 

1131 outer_call_candidates = [ 

1132 r for r in same_expiry_rows 

1133 if str(r.get("right", "")).lower() == "call" and r.get("delta") is not None and float(r["strike"]) > inner_call_strike 

1134 ] 

1135 if not outer_call_candidates: 

1136 return None 

1137 outer_call_row = min(outer_call_candidates, key=lambda r: abs(abs(r["delta"]) - abs(target_delta - short_leg_delta_offset - wing_delta_offset))) 

1138 

1139 return { 

1140 inner_put_leg.role: inner_put_row, outer_put_leg.role: outer_put_row, 

1141 inner_call_leg.role: inner_call_row, outer_call_leg.role: outer_call_row, 

1142 } 

1143 

1144 

1145def select_iron_butterfly_legs( 

1146 spec: StrategySpec, 

1147 available_chain: list[dict], 

1148 target_delta: float, 

1149 wing_delta_offset: float = 0.20, 

1150 max_strike_asymmetry_tolerance: float = 0.15, 

1151) -> dict[str, dict] | None: 

1152 """shape_family == "iron_butterfly" - the ATM strike is shared by BOTH 

1153 middle legs (short_put and short_call both sit at the same strike, per 

1154 OptionStrategies.cs's IronButterfly == IronCondor with its 2 middle 

1155 strikes collapsed together), with the OTM wings picked equidistant 

1156 (tolerance-based, same contract as select_butterfly_legs()) rather than 

1157 independently re-selected by delta on each side.""" 

1158 call_middle_leg = next(leg for leg in spec.legs if leg.right == "call" and leg.strike_role == "atm") 

1159 put_middle_leg = next(leg for leg in spec.legs if leg.right == "put" and leg.strike_role == "atm") 

1160 otm_call_leg = next(leg for leg in spec.legs if leg.strike_role == "otm_call") 

1161 otm_put_leg = next(leg for leg in spec.legs if leg.strike_role == "otm_put") 

1162 

1163 atm_call_row = _nearest_by_delta(available_chain, "call", target_delta) 

1164 if atm_call_row is None: 

1165 return None 

1166 atm_strike = float(atm_call_row["strike"]) 

1167 same_expiry_rows = [r for r in available_chain if r.get("expiry") == atm_call_row.get("expiry")] 

1168 atm_put_row = next( 

1169 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == "put" and float(r.get("strike", -1)) == atm_strike), 

1170 None, 

1171 ) 

1172 if atm_put_row is None: 

1173 return None 

1174 

1175 otm_call_candidates = sorted( 

1176 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == "call" and float(r.get("strike", atm_strike)) > atm_strike), 

1177 key=lambda r: float(r["strike"]), 

1178 ) 

1179 otm_put_candidates = sorted( 

1180 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == "put" and float(r.get("strike", atm_strike)) < atm_strike), 

1181 key=lambda r: float(r["strike"]), 

1182 reverse=True, 

1183 ) 

1184 if not otm_call_candidates or not otm_put_candidates: 

1185 return None 

1186 otm_call_row = otm_call_candidates[0] 

1187 otm_put_row = otm_put_candidates[0] 

1188 

1189 call_wing_width = float(otm_call_row["strike"]) - atm_strike 

1190 put_wing_width = atm_strike - float(otm_put_row["strike"]) 

1191 wider, narrower = max(call_wing_width, put_wing_width), min(call_wing_width, put_wing_width) 

1192 if wider <= 0 or abs(wider - narrower) / wider > max_strike_asymmetry_tolerance: 

1193 return None 

1194 

1195 return { 

1196 call_middle_leg.role: atm_call_row, put_middle_leg.role: atm_put_row, 

1197 otm_call_leg.role: otm_call_row, otm_put_leg.role: otm_put_row, 

1198 } 

1199 

1200 

1201def select_calendar_legs( 

1202 spec: StrategySpec, 

1203 available_chain: list[dict], 

1204 target_delta: float, 

1205 grouped_chain_by_expiry: dict[str, list[dict]] | None = None, 

1206) -> dict[str, dict] | None: 

1207 """shape_family == "calendar" - a genuinely new primitive (nothing 

1208 before this pass compares two DIFFERENT expiries): groups the chain by 

1209 expiry first (group_chain_by_expiry(), O(n) once), requires at least 

1210 2 distinct expiries, picks the near leg's strike by delta within the 

1211 nearest expiry, then requires the SAME strike be present in every 

1212 LATER expiry group - the far leg uses the closest-dated expiry that 

1213 has it. Returns None for a chain with fewer than 2 expiries (routine 

1214 for a thinly configured universe, never a crash). 

1215 

1216 `grouped_chain_by_expiry` (V4.9 Priority 3), when given, is used 

1217 INSTEAD OF recomputing group_chain_by_expiry(available_chain) here - 

1218 lets a caller trying several calendar-family candidates against the 

1219 SAME chain in one bar (risk/asset_class_router.py:: 

1220 route_multi_leg_option_sizing()) group it once and reuse it. Default 

1221 None reproduces the exact original per-call regroup behavior.""" 

1222 near_leg = next(leg for leg in spec.legs if leg.expiry_role == "near") 

1223 far_leg = next(leg for leg in spec.legs if leg.expiry_role == "far") 

1224 right = near_leg.right 

1225 

1226 grouped = grouped_chain_by_expiry if grouped_chain_by_expiry is not None else group_chain_by_expiry(available_chain) 

1227 expiries = sorted(e for e in grouped if e is not None) 

1228 if len(expiries) < 2: 

1229 return None 

1230 

1231 near_expiry = expiries[0] 

1232 near_row = _nearest_by_delta(grouped[near_expiry], right, target_delta) 

1233 if near_row is None: 

1234 return None 

1235 strike = float(near_row["strike"]) 

1236 

1237 for far_expiry in expiries[1:]: 

1238 far_row = _nearest_by_strike(grouped[far_expiry], right, strike) 

1239 if far_row is not None and float(far_row["strike"]) == strike: 

1240 return {near_leg.role: near_row, far_leg.role: far_row} 

1241 return None 

1242 

1243 

1244def select_backspread_legs( 

1245 spec: StrategySpec, available_chain: list[dict], target_delta: float, backspread_delta_offset: float = 0.20, 

1246) -> dict[str, dict] | None: 

1247 """shape_family == "backspread" - 1:2-ratio 2-leg selector shared by 

1248 all 4 variants (call_backspread/short_call_backspread/put_backspread/ 

1249 short_put_backspread); which strike_role ("lower"/"higher") is the 

1250 anchor and which side each role maps to both come from the registry, 

1251 so this one function is correct for every variant without branching 

1252 on strategy_name.""" 

1253 anchor_leg = next(leg for leg in spec.legs if leg.is_anchor) 

1254 other_leg = next(leg for leg in spec.legs if not leg.is_anchor) 

1255 right = anchor_leg.right 

1256 

1257 anchor_row = _nearest_by_delta(available_chain, right, target_delta) 

1258 if anchor_row is None: 

1259 return None 

1260 anchor_strike = float(anchor_row["strike"]) 

1261 same_expiry_rows = [r for r in available_chain if r.get("expiry") == anchor_row.get("expiry")] 

1262 is_outer = _outer_strike_predicate(right, anchor_strike) if anchor_leg.strike_role == "lower" else ( 

1263 lambda strike: strike < anchor_strike 

1264 ) 

1265 other_candidates = [ 

1266 r for r in same_expiry_rows 

1267 if str(r.get("right", "")).lower() == right and r.get("delta") is not None and is_outer(float(r["strike"])) 

1268 ] 

1269 if not other_candidates: 

1270 return None 

1271 other_target_delta = target_delta - backspread_delta_offset 

1272 other_row = min(other_candidates, key=lambda r: abs(abs(r["delta"]) - abs(other_target_delta))) 

1273 return {anchor_leg.role: anchor_row, other_leg.role: other_row} 

1274 

1275 

1276def select_ladder_legs( 

1277 spec: StrategySpec, available_chain: list[dict], target_delta: float, ladder_wing_delta_offset: float = 0.15, 

1278) -> dict[str, dict] | None: 

1279 """shape_family == "ladder" - 3-strike, 1:1:1-ratio selector shared by 

1280 all 4 variants (bear_call_ladder/bull_call_ladder/bear_put_ladder/ 

1281 bull_put_ladder). Anchors on the spec's anchor leg by delta, then picks 

1282 the other 2 legs as the nearest available strikes further from the 

1283 anchor in the direction _outer_strike_predicate defines for this 

1284 right - same expiry-anchoring guarantee as every other selector here.""" 

1285 anchor_leg = next(leg for leg in spec.legs if leg.is_anchor) 

1286 other_legs = [leg for leg in spec.legs if not leg.is_anchor] 

1287 right = anchor_leg.right 

1288 

1289 anchor_row = _nearest_by_delta(available_chain, right, target_delta) 

1290 if anchor_row is None: 

1291 return None 

1292 anchor_strike = float(anchor_row["strike"]) 

1293 same_expiry_rows = [r for r in available_chain if r.get("expiry") == anchor_row.get("expiry")] 

1294 is_outer = _outer_strike_predicate(right, anchor_strike) 

1295 outer_candidates = sorted( 

1296 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == right and is_outer(float(r.get("strike", anchor_strike)))), 

1297 key=lambda r: abs(float(r["strike"]) - anchor_strike), 

1298 ) 

1299 if len(outer_candidates) < 2: 

1300 return None 

1301 

1302 result = {anchor_leg.role: anchor_row} 

1303 # other_legs is exactly 2 roles (registry order matches increasing 

1304 # distance from the anchor strike, e.g. "middle" then "higher" for 

1305 # bear_call_ladder) - zip against the 2 nearest outer candidates by 

1306 # strike distance, honoring that ordering. 

1307 for leg, row in zip(other_legs, outer_candidates[:2], strict=False): 

1308 result[leg.role] = row 

1309 return result 

1310 

1311 

1312def select_naked_leg(spec: StrategySpec, available_chain: list[dict], target_delta: float) -> dict[str, dict] | None: 

1313 """shape_family == "naked" (naked_call/naked_put) - a single short leg, 

1314 nearest-|delta| selection, no expiry-anchoring needed (only 1 leg).""" 

1315 leg = spec.legs[0] 

1316 row = _nearest_by_delta(available_chain, leg.right, target_delta) 

1317 if row is None: 

1318 return None 

1319 return {leg.role: row} 

1320 

1321 

1322def select_covered_protective_leg(spec: StrategySpec, available_chain: list[dict], target_delta: float) -> dict[str, dict] | None: 

1323 """shape_family in {"covered_protective", "collar"} - the OPTION leg(s) 

1324 only (never the equity side - see main.py's corrected cross-asset 

1325 design, the equity leg is read from the currently-held quantity, not 

1326 selected from a chain). protective_collar has 2 anchor legs (call and 

1327 put), each selected independently by delta since a collar's call/put 

1328 strikes are deliberately NOT required to be equidistant from spot 

1329 (call_strike > put_strike is the only real constraint, enforced 

1330 upstream by OptionStrategies.ProtectiveCollar itself).""" 

1331 result = {} 

1332 for leg in spec.legs: 

1333 row = _nearest_by_delta(available_chain, leg.right, target_delta) 

1334 if row is None: 

1335 return None 

1336 result[leg.role] = row 

1337 if spec.shape_family == "collar" and len(result) == 2: 

1338 rows = list(result.values()) 

1339 if float(rows[0]["strike"]) == float(rows[1]["strike"]): 

1340 # ProtectiveCollar requires call_strike > put_strike strictly - 

1341 # degrade to None rather than let main.py hand Lean's factory 

1342 # two equal strikes it will itself reject with an exception. 

1343 return None 

1344 return result 

1345 

1346 

1347def select_arbitrage_box_legs(spec: StrategySpec, available_chain: list[dict], target_delta: float) -> dict[str, dict] | None: 

1348 """shape_family == "arbitrage_box" (box_spread/short_box_spread) - 

1349 wired-but-unreachable (development/Problems.md): registry/selector 

1350 exist and are unit-tested, but no signal source in this codebase ever 

1351 calls this - a real box spread requires a mispricing detector (rich/ 

1352 cheap vs. the risk-free-rate-implied fair value), a separate future 

1353 project. Reuses select_vertical_legs()-style same-expiry anchoring: 

1354 the "higher"-strike-role legs (long_put, short_call) anchor by delta, 

1355 the "lower"-strike-role legs (short_put, long_call) share the SAME 

1356 strike as one of the anchor legs by construction (a box spread is a 

1357 single strike pair, not 4 independent strikes).""" 

1358 long_put_leg = next(leg for leg in spec.legs if leg.role == "long_put") 

1359 short_put_leg = next(leg for leg in spec.legs if leg.role == "short_put") 

1360 long_call_leg = next(leg for leg in spec.legs if leg.role == "long_call") 

1361 short_call_leg = next(leg for leg in spec.legs if leg.role == "short_call") 

1362 

1363 put_anchor_row = _nearest_by_delta(available_chain, "put", target_delta) 

1364 if put_anchor_row is None: 

1365 return None 

1366 higher_strike = float(put_anchor_row["strike"]) 

1367 same_expiry_rows = [r for r in available_chain if r.get("expiry") == put_anchor_row.get("expiry")] 

1368 lower_candidates = sorted( 

1369 (r for r in same_expiry_rows if str(r.get("right", "")).lower() == "put" and float(r.get("strike", higher_strike)) < higher_strike), 

1370 key=lambda r: float(r["strike"]), 

1371 reverse=True, 

1372 ) 

1373 if not lower_candidates: 

1374 return None 

1375 lower_strike = float(lower_candidates[0]["strike"]) 

1376 

1377 put_rows = {"higher": put_anchor_row, "lower": lower_candidates[0]} 

1378 call_higher_row = _nearest_by_strike(same_expiry_rows, "call", higher_strike) 

1379 call_lower_row = _nearest_by_strike(same_expiry_rows, "call", lower_strike) 

1380 if call_higher_row is None or call_lower_row is None: 

1381 return None 

1382 call_rows = {"higher": call_higher_row, "lower": call_lower_row} 

1383 

1384 return { 

1385 long_put_leg.role: put_rows[long_put_leg.strike_role], 

1386 short_put_leg.role: put_rows[short_put_leg.strike_role], 

1387 long_call_leg.role: call_rows[long_call_leg.strike_role], 

1388 short_call_leg.role: call_rows[short_call_leg.strike_role], 

1389 } 

1390 

1391 

1392def select_arbitrage_conversion_legs(spec: StrategySpec, available_chain: list[dict], target_delta: float) -> dict[str, dict] | None: 

1393 """shape_family == "arbitrage_conversion" (conversion/reverse_conversion) 

1394 - wired-but-unreachable, same caveat as select_arbitrage_box_legs() 

1395 above. Single shared strike for both legs (same-expiry, same-strike 

1396 call+put pair - identical selection shape to select_straddle_legs()).""" 

1397 call_leg = next(leg for leg in spec.legs if leg.right == "call") 

1398 put_leg = next(leg for leg in spec.legs if leg.right == "put") 

1399 anchor_leg, other_leg = (call_leg, put_leg) if call_leg.is_anchor else (put_leg, call_leg) 

1400 

1401 anchor_row = _nearest_by_delta(available_chain, anchor_leg.right, target_delta) 

1402 if anchor_row is None: 

1403 return None 

1404 same_expiry_rows = [r for r in available_chain if r.get("expiry") == anchor_row.get("expiry")] 

1405 other_row = next( 

1406 ( 

1407 r for r in same_expiry_rows 

1408 if str(r.get("right", "")).lower() == other_leg.right and float(r.get("strike", -1)) == float(anchor_row["strike"]) 

1409 ), 

1410 None, 

1411 ) 

1412 if other_row is None: 

1413 return None 

1414 return {anchor_leg.role: anchor_row, other_leg.role: other_row} 

1415 

1416 

1417def select_arbitrage_jelly_roll_legs( 

1418 spec: StrategySpec, 

1419 available_chain: list[dict], 

1420 target_delta: float, 

1421 grouped_chain_by_expiry: dict[str, list[dict]] | None = None, 

1422) -> dict[str, dict] | None: 

1423 """shape_family == "arbitrage_jelly_roll" (jelly_roll/short_jelly_roll) 

1424 - wired-but-unreachable, same caveat as the other 2 arbitrage selectors 

1425 above. Same expiry-grouping primitive as select_calendar_legs(), but 

1426 requires all 4 legs (near call, far call, near put, far put) to share 

1427 ONE strike across both expiries. 

1428 

1429 `grouped_chain_by_expiry` (V4.9 Priority 3) - same optional 

1430 precomputed-grouping parameter as select_calendar_legs(), same default- 

1431 None-reproduces-original-behavior contract. In practice never actually 

1432 passed today (this shape family is permanently unreachable via 

1433 route_multi_leg_option_sizing()'s own risk_tier routing - see its 

1434 "unreachable_arbitrage" branch), kept for interface symmetry with 

1435 select_calendar_legs() and in case a future caller reaches it directly.""" 

1436 near_call_leg = next(leg for leg in spec.legs if leg.role == "near_call") 

1437 far_call_leg = next(leg for leg in spec.legs if leg.role == "far_call") 

1438 near_put_leg = next(leg for leg in spec.legs if leg.role == "near_put") 

1439 far_put_leg = next(leg for leg in spec.legs if leg.role == "far_put") 

1440 

1441 grouped = grouped_chain_by_expiry if grouped_chain_by_expiry is not None else group_chain_by_expiry(available_chain) 

1442 expiries = sorted(e for e in grouped if e is not None) 

1443 if len(expiries) < 2: 

1444 return None 

1445 near_expiry = expiries[0] 

1446 near_call_row = _nearest_by_delta(grouped[near_expiry], "call", target_delta) 

1447 if near_call_row is None: 

1448 return None 

1449 strike = float(near_call_row["strike"]) 

1450 

1451 for far_expiry in expiries[1:]: 

1452 far_call_row = _nearest_by_strike(grouped[far_expiry], "call", strike) 

1453 near_put_row = _nearest_by_strike(grouped[near_expiry], "put", strike) 

1454 far_put_row = _nearest_by_strike(grouped[far_expiry], "put", strike) 

1455 if ( 

1456 far_call_row is not None and float(far_call_row["strike"]) == strike 

1457 and near_put_row is not None and float(near_put_row["strike"]) == strike 

1458 and far_put_row is not None and float(far_put_row["strike"]) == strike 

1459 ): 

1460 return { 

1461 near_call_leg.role: near_call_row, far_call_leg.role: far_call_row, 

1462 near_put_leg.role: near_put_row, far_put_leg.role: far_put_row, 

1463 } 

1464 return None 

1465 

1466 

1467_SHAPE_FAMILY_SELECTORS = { 

1468 "straddle": select_straddle_legs, 

1469 "strangle": select_strangle_legs, 

1470 "butterfly": select_butterfly_legs, 

1471 "iron_condor": select_iron_condor_legs, 

1472 "iron_butterfly": select_iron_butterfly_legs, 

1473 "calendar": select_calendar_legs, 

1474 "backspread": select_backspread_legs, 

1475 "ladder": select_ladder_legs, 

1476 "naked": select_naked_leg, 

1477 "covered_protective": select_covered_protective_leg, 

1478 "collar": select_covered_protective_leg, 

1479 "arbitrage_box": select_arbitrage_box_legs, 

1480 "arbitrage_conversion": select_arbitrage_conversion_legs, 

1481 "arbitrage_jelly_roll": select_arbitrage_jelly_roll_legs, 

1482} 

1483 

1484 

1485_GROUPED_CHAIN_SHAPE_FAMILIES = {"calendar", "arbitrage_jelly_roll"} 

1486 

1487 

1488def select_strategy_legs( 

1489 strategy_name: str, 

1490 available_chain: list[dict], 

1491 target_delta: float, 

1492 grouped_chain_by_expiry: dict[str, list[dict]] | None = None, 

1493 **tuning_kwargs: Any, 

1494) -> dict[str, dict] | None: 

1495 """Single dispatch point every caller (main.py, tests) should use 

1496 instead of calling a shape-family selector directly - looks up 

1497 strategy_name's StrategySpec then its shape_family's selector, a plain 

1498 dict lookup (O(1)) rather than an if/elif chain over 43 names, matching 

1499 this module's "registry, not 41 near-duplicate functions" design goal. 

1500 "vertical" strategies use select_vertical_legs() directly (not in the 

1501 dispatch dict above, since it takes the full spec + is reused by 4 

1502 strategy_names identically). tuning_kwargs passes through to whichever 

1503 selector is chosen (e.g. short_leg_delta_offset, wing_width_delta_offset) 

1504 - unrecognized kwargs for a given selector are simply not in its 

1505 signature and would raise, exactly like any other Python call; callers 

1506 should only pass kwargs relevant to the strategy family they're 

1507 invoking, or none at all to accept every selector's own defaults. 

1508 

1509 `grouped_chain_by_expiry` (V4.9 Priority 3) is a DEDICATED top-level 

1510 parameter, not folded into tuning_kwargs - it's only meaningful for the 

1511 2 shape families in _GROUPED_CHAIN_SHAPE_FAMILIES (calendar, 

1512 arbitrage_jelly_roll) and is deliberately swallowed (never forwarded) 

1513 for every other strategy_name, since blindly passing it through 

1514 tuning_kwargs would raise a TypeError for the 12 selectors that don't 

1515 accept it. Default None reproduces the exact original per-call regroup 

1516 behavior for every strategy_name, unchanged.""" 

1517 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name) 

1518 if spec is None: 

1519 return None 

1520 if spec.shape_family == "vertical": 

1521 return select_vertical_legs(spec, available_chain, target_delta, **tuning_kwargs) 

1522 selector = _SHAPE_FAMILY_SELECTORS.get(spec.shape_family) 

1523 if selector is None: 

1524 return None 

1525 if spec.shape_family in _GROUPED_CHAIN_SHAPE_FAMILIES: 

1526 return selector( 

1527 spec, available_chain, target_delta, grouped_chain_by_expiry=grouped_chain_by_expiry, **tuning_kwargs 

1528 ) 

1529 return selector(spec, available_chain, target_delta, **tuning_kwargs) 

1530 

1531 

1532@dataclass(frozen=True) 

1533class OptionsMultiLegPositionDecision: 

1534 """N-leg sibling of OptionsSpreadPositionDecision - generalized to any 

1535 leg count/ratio and to 1 OR 2 distinct expiries (the calendar family), 

1536 rather than OptionsSpreadPositionDecision's fixed 2-leg/1-expiry shape. 

1537 A SEPARATE dataclass, not a generalization of it - every existing 

1538 caller of OptionsSpreadPositionDecision (bull_call_spread/ 

1539 bear_put_spread's own dedicated sizing path) is completely untouched.""" 

1540 

1541 strategy_name: str 

1542 legs: tuple[OptionsSpreadLeg, ...] # one per StrategySpec.legs entry, in registry order 

1543 expiries: tuple[str, ...] # 1 entry for every family except calendar/jelly-roll (2: near, far) 

1544 contracts: int # spread-unit quantity, NOT a per-leg contract count (ratio legs bake their own multiple in via main.py's factory call, same convention the 2-leg vertical already established) 

1545 net_debit_or_credit: float # best-effort diagnostic only, 0.0 when bid/ask are absent 

1546 net_delta: float # sum of side-signed, ratio-weighted per-leg deltas 

1547 net_vega: float # fraction of portfolio_value the sized position's net vega consumes 

1548 sizing_reason: str 

1549 

1550 def to_dict(self) -> dict[str, Any]: 

1551 """Same manual-field-access convention as every other decision 

1552 dataclass in this module - never dataclasses.asdict().""" 

1553 return { 

1554 "strategy_name": self.strategy_name, 

1555 "legs": [ 

1556 { 

1557 "strike": leg.strike, 

1558 "right": leg.right, 

1559 "side": leg.side, 

1560 "contract_symbol": str(leg.contract_symbol) if leg.contract_symbol is not None else None, 

1561 } 

1562 for leg in self.legs 

1563 ], 

1564 "expiries": list(self.expiries), 

1565 "contracts": self.contracts, 

1566 "net_debit_or_credit": self.net_debit_or_credit, 

1567 "net_delta": self.net_delta, 

1568 "net_vega": self.net_vega, 

1569 "sizing_reason": self.sizing_reason, 

1570 } 

1571 

1572 

1573def _legs_tuple_from_roles(spec: StrategySpec, legs_by_role: dict[str, dict]) -> tuple[OptionsSpreadLeg, ...]: 

1574 """Shared OptionsSpreadLeg-tuple builder - every multi-leg sizing path 

1575 (vega-budget, margin, covered/protective) produces the exact same leg 

1576 shape from a role->chain-row dict, so this is written once.""" 

1577 return tuple( 

1578 OptionsSpreadLeg( 

1579 strike=float(legs_by_role[leg_spec.role]["strike"]), 

1580 right=leg_spec.right, 

1581 side=leg_spec.side, 

1582 contract_symbol=legs_by_role[leg_spec.role].get("symbol"), 

1583 ) 

1584 for leg_spec in spec.legs 

1585 ) 

1586 

1587 

1588def _expiries_tuple_from_roles(spec: StrategySpec, legs_by_role: dict[str, dict]) -> tuple[str, ...]: 

1589 """1-entry tuple for every family except the 2 calendar-shaped ones 

1590 (near, far) - shared by every multi-leg sizing path, same rationale as 

1591 _legs_tuple_from_roles() above.""" 

1592 if spec.has_expiry_pair: 

1593 near_role = next(leg.role for leg in spec.legs if leg.expiry_role == "near") 

1594 far_role = next(leg.role for leg in spec.legs if leg.expiry_role == "far") 

1595 return (str(legs_by_role[near_role]["expiry"]), str(legs_by_role[far_role]["expiry"])) 

1596 any_row = next(iter(legs_by_role.values())) 

1597 return (str(any_row["expiry"]),) 

1598 

1599 

1600def _net_vega_and_delta_per_unit(spec: StrategySpec, legs_by_role: dict[str, dict]) -> tuple[float, float]: 

1601 """Signed, ratio-weighted sum of vega/delta across every leg - the 

1602 generalization of the 2-leg vertical's `long_vega - short_vega` to N 

1603 legs at arbitrary ratios (a butterfly's body leg contributes 

1604 side_sign * 2 * its own vega, not 1x).""" 

1605 net_vega = 0.0 

1606 net_delta = 0.0 

1607 for leg_spec in spec.legs: 

1608 row = legs_by_role.get(leg_spec.role) 

1609 if row is None: 

1610 continue 

1611 side_sign = 1.0 if leg_spec.side == "long" else -1.0 

1612 net_vega += side_sign * leg_spec.ratio * float(row.get("vega", 0.0) or 0.0) 

1613 net_delta += side_sign * leg_spec.ratio * float(row.get("delta", 0.0) or 0.0) 

1614 return net_vega, net_delta 

1615 

1616 

1617def net_debit_or_credit_for_legs(spec: StrategySpec, legs_by_role: dict[str, dict]) -> float | None: 

1618 """Signed net premium to trade every leg in spec.legs at 

1619 legs_by_role's current bid/ask - long legs value at ask, short legs 

1620 at bid (the conservative/executable-price convention _size_multi_leg() 

1621 below already uses, and options_arbitrage_detector.py's own 

1622 _actual_net_cost() also uses independently). Positive = net DEBIT 

1623 (paying more for long legs than received for short legs), negative = 

1624 net CREDIT - same sign convention as OptionsMultiLegPositionDecision's 

1625 own net_debit_or_credit field. 

1626 

1627 Returns None (not 0.0) when any leg's role is missing a bid/ask row - 

1628 "cannot compute this bar" must not be indistinguishable from "computed 

1629 a genuine 0.0 premium", the same None-vs-neutral-default distinction 

1630 features/bond_features.py's module docstring and 

1631 features/options_greeks.py::implied_volatility() already draw. 

1632 _size_multi_leg() below deliberately keeps ITS OWN reset-to-0.0-on- 

1633 missing-price behavior (a documented best-effort SIZING diagnostic, 

1634 unchanged) by coercing this function's None to 0.0 at its own call 

1635 site - this function is the stricter sibling, extracted for a caller 

1636 (main.py's per-strategy realized-outcome computation, V4.7) where 

1637 "unknown" must never silently look like "breakeven".""" 

1638 net = 0.0 

1639 for leg_spec in spec.legs: 

1640 row = legs_by_role.get(leg_spec.role, {}) 

1641 price = row.get("ask") if leg_spec.side == "long" else row.get("bid") 

1642 if price is None: 

1643 return None 

1644 side_sign = 1.0 if leg_spec.side == "long" else -1.0 

1645 net += side_sign * leg_spec.ratio * float(price) 

1646 return net 

1647 

1648 

1649def _size_multi_leg( 

1650 strategy_name: str, 

1651 legs_by_role: dict[str, dict], 

1652 portfolio_value: float, 

1653 max_vega_budget_pct_of_equity: float, 

1654 sizing_reason: str, 

1655) -> OptionsMultiLegPositionDecision | None: 

1656 """Shared net-vega-budget arithmetic for an already-resolved leg set - 

1657 the N-leg generalization of _size_vertical_spread() above. Only used 

1658 for risk_tier == "vega_budget" strategies (margin-tier strategies are 

1659 sized by portfolio/options_margin_sizing.py instead - kept OUT of this 

1660 function, matching the plan's hard separation between the two sizing 

1661 paradigms). Returns None when net_vega is non-positive or the budget 

1662 rounds down to zero spread units - never raises.""" 

1663 spec = MULTI_LEG_STRATEGY_REGISTRY[strategy_name] 

1664 net_vega, net_delta = _net_vega_and_delta_per_unit(spec, legs_by_role) 

1665 # UNLIKE the 2-leg debit vertical's long_vega - short_vega (always 

1666 # positive by construction there - the anchor/long leg is always 

1667 # nearer money, hence higher-vega, than the short leg), a credit 

1668 # vertical or iron condor/butterfly's anchor leg is the SHORT 

1669 # (near-money, higher-vega) one - net_vega is structurally NEGATIVE 

1670 # for those, by design (a short-vol structure IS a net-short-vega 

1671 # position). Budget by magnitude, not sign - only a truly flat (zero) 

1672 # net vega is unsizeable. 

1673 abs_net_vega = abs(net_vega) 

1674 if abs_net_vega == 0.0: 

1675 return None 

1676 

1677 computed_net_debit_or_credit = net_debit_or_credit_for_legs(spec, legs_by_role) 

1678 net_debit_or_credit = computed_net_debit_or_credit if computed_net_debit_or_credit is not None else 0.0 

1679 vega_budget = max_vega_budget_pct_of_equity * portfolio_value 

1680 contracts = _affordable_contracts(int(vega_budget // abs_net_vega), net_debit_or_credit, portfolio_value) 

1681 if contracts <= 0: 

1682 return None 

1683 

1684 legs = _legs_tuple_from_roles(spec, legs_by_role) 

1685 expiries = _expiries_tuple_from_roles(spec, legs_by_role) 

1686 

1687 return OptionsMultiLegPositionDecision( 

1688 strategy_name=strategy_name, 

1689 legs=legs, 

1690 expiries=expiries, 

1691 contracts=contracts, 

1692 net_debit_or_credit=net_debit_or_credit, 

1693 net_delta=net_delta, 

1694 net_vega=(contracts * abs_net_vega) / portfolio_value, 

1695 sizing_reason=sizing_reason, 

1696 ) 

1697 

1698 

1699def build_multi_leg_position_sizing( 

1700 strategy_name: str, 

1701 signal_direction: str, 

1702 confidence: float, 

1703 available_chain: list[dict], 

1704 portfolio_value: float, 

1705 target_delta_at_full_confidence: float = 0.60, 

1706 max_vega_budget_pct_of_equity: float = 0.02, 

1707 grouped_chain_by_expiry: dict[str, list[dict]] | None = None, 

1708 **selector_tuning_kwargs: Any, 

1709) -> OptionsMultiLegPositionDecision | None: 

1710 """The single public entry point for every NEW (V4.5) vega-budget-tier 

1711 strategy - dispatches leg selection via select_strategy_legs(), then 

1712 sizes via _size_multi_leg(). Returns None for any margin-tier or 

1713 unreachable-arbitrage strategy_name (those are sized by 

1714 portfolio/options_margin_sizing.py, or never sized at all, 

1715 respectively) - a caller passing the wrong tier's strategy_name here 

1716 gets a clean None, not a wrong/unsafe budget calculation. 

1717 

1718 `grouped_chain_by_expiry` (V4.9 Priority 3) passes straight through to 

1719 select_strategy_legs() - see its own docstring. Default None 

1720 reproduces the exact original per-call regroup behavior.""" 

1721 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name) 

1722 if spec is None or spec.risk_tier != "vega_budget": 

1723 return None 

1724 

1725 confidence = max(0.0, min(float(confidence), 1.0)) 

1726 portfolio_value = max(float(portfolio_value), 0.0) 

1727 if confidence == 0.0 or portfolio_value <= 0.0: 

1728 return None 

1729 if signal_direction not in ("buy", "sell", "short"): 

1730 return None 

1731 

1732 target_delta = target_delta_at_full_confidence * confidence 

1733 legs_by_role = select_strategy_legs( 

1734 strategy_name, available_chain, target_delta, 

1735 grouped_chain_by_expiry=grouped_chain_by_expiry, **selector_tuning_kwargs, 

1736 ) 

1737 if legs_by_role is None: 

1738 return None 

1739 

1740 return _size_multi_leg( 

1741 strategy_name, legs_by_role, portfolio_value, max_vega_budget_pct_of_equity, 

1742 "delta_targeted_net_vega_budgeted_multi_leg_sizing", 

1743 ) 

1744 

1745 

1746def build_multi_leg_position_sizing_for_legs( 

1747 strategy_name: str, 

1748 held_rows_by_role: dict[str, dict], 

1749 portfolio_value: float, 

1750 max_vega_budget_pct_of_equity: float = 0.02, 

1751) -> OptionsMultiLegPositionDecision | None: 

1752 """Resize-in-place sibling of build_multi_leg_position_sizing() - sizes 

1753 an ALREADY-HELD position on its legs' own current greeks, skipping 

1754 selection entirely. held_rows_by_role must carry an entry for every 

1755 role in MULTI_LEG_STRATEGY_REGISTRY[strategy_name].legs (same shape 

1756 select_strategy_legs() returns) - same degrade-to-None contract as 

1757 build_multi_leg_position_sizing() for non-positive portfolio_value or 

1758 non-positive net vega.""" 

1759 portfolio_value = max(float(portfolio_value), 0.0) 

1760 if portfolio_value <= 0.0: 

1761 return None 

1762 if strategy_name not in MULTI_LEG_STRATEGY_REGISTRY: 

1763 return None 

1764 return _size_multi_leg( 

1765 strategy_name, held_rows_by_role, portfolio_value, max_vega_budget_pct_of_equity, 

1766 "held_legs_own_greeks_multi_leg_sizing", 

1767 ) 

1768 

1769 

1770# --------------------------------------------------------------------------- 

1771# Volatility-view signal (drives straddle/strangle/iron condor/butterfly/ 

1772# credit-vs-debit selection within the enabled_strategy_names allowlist). 

1773# --------------------------------------------------------------------------- 

1774 

1775ANNUALIZATION_FACTOR_DAILY_TO_ANNUAL = math.sqrt(252) 

1776 

1777 

1778def atm_implied_volatility(available_chain: list[dict], expiry: str) -> float | None: 

1779 """Nearest-to-spot call+put average IV for one expiry - "nearest to 

1780 spot" approximated here as the LOWEST |delta - 0.5| call combined with 

1781 its same-strike put (a call delta near 0.50 is the standard ATM proxy 

1782 when a real spot/strike distance isn't threaded through this function). 

1783 Returns None when the expiry has no usable call (chain empty, IB 

1784 disabled, or no "iv"/"implied_volatility" field present) - never a 

1785 crash, matching this module's degrade-to-absent convention.""" 

1786 rows = [r for r in available_chain if r.get("expiry") == expiry] 

1787 calls = [r for r in rows if str(r.get("right", "")).lower() == "call" and r.get("delta") is not None] 

1788 if not calls: 

1789 return None 

1790 atm_call = min(calls, key=lambda r: abs(abs(r["delta"]) - 0.50)) 

1791 call_iv = atm_call.get("iv", atm_call.get("implied_volatility")) 

1792 put_row = next( 

1793 (r for r in rows if str(r.get("right", "")).lower() == "put" and float(r.get("strike", -1)) == float(atm_call["strike"])), 

1794 None, 

1795 ) 

1796 put_iv = put_row.get("iv", put_row.get("implied_volatility")) if put_row is not None else None 

1797 ivs = [float(v) for v in (call_iv, put_iv) if v is not None] 

1798 if not ivs: 

1799 return None 

1800 return sum(ivs) / len(ivs) 

1801 

1802 

1803def classify_volatility_view(predicted_volatility_annualized: float, atm_iv: float, margin: float = 0.05) -> str: 

1804 """Pure, unit-agnostic classifier: "long_vol" when the model's own 

1805 annualized volatility forecast exceeds the chain's current ATM implied 

1806 vol by more than `margin`, "short_vol" when it's below by more than 

1807 `margin`, else "neutral". The annualization (predicted_volatility * 

1808 ANNUALIZATION_FACTOR_DAILY_TO_ANNUAL) MUST happen at the call site, 

1809 never inside this function - train.py's target_volatility_next_day is 

1810 a raw daily high-low-range proxy, not annualized, and comparing it 

1811 against chain IV (always annualized) unit-mismatched would produce an 

1812 almost-always-false signal. Documented approximation regardless of 

1813 units: a range-based estimator and a lognormal-return-implied vol 

1814 aren't the same statistical object even after unit-matching.""" 

1815 if predicted_volatility_annualized > atm_iv + margin: 

1816 return "long_vol" 

1817 if predicted_volatility_annualized < atm_iv - margin: 

1818 return "short_vol" 

1819 return "neutral" 

1820 

1821 

1822# Which strategy_names are eligible for each volatility_view bucket - 

1823# purely a lookup over shape_family/risk_tier, no chain/confidence 

1824# involved (main.py tries each eligible, ENABLED name in priority order 

1825# via build_multi_leg_position_sizing()/margin sizing until one actually 

1826# sizes - see order_enabled_strategies() below for the ordering itself). 

1827_LONG_VOL_SHAPE_FAMILIES = frozenset({"straddle_long", "strangle_long"}) 

1828_SHORT_VOL_SHAPE_FAMILIES = frozenset({"straddle_short", "strangle_short", "iron_condor", "iron_butterfly"}) 

1829 

1830 

1831def strategies_for_volatility_view(volatility_view: str) -> frozenset[str]: 

1832 """Pure lookup: which registered strategy_names express `volatility_view` 

1833 ("long_vol" -> long straddle/strangle; "short_vol" -> short straddle/ 

1834 strangle + iron condor/butterfly, both defined- and unbounded-risk 

1835 variants included so risk_tier_preference below can choose between 

1836 them; "neutral" -> empty, no strategy actively expresses a neutral 

1837 view here). Iron condor/butterfly are "short_vol" regardless of the 

1838 long/short spelling of their own name (short_iron_condor is itself 

1839 already the credit/short-vol side; there is no long_iron_condor 

1840 concept in this shape family).""" 

1841 if volatility_view == "long_vol": 

1842 return frozenset({"straddle", "strangle"}) 

1843 if volatility_view == "short_vol": 

1844 return frozenset({ 

1845 "short_straddle", "short_strangle", 

1846 "iron_condor", "short_iron_condor", "iron_butterfly", "short_iron_butterfly", 

1847 }) 

1848 return frozenset() 

1849 

1850 

1851_DEFINED_RISK_STRATEGY_NAMES = frozenset({"iron_condor", "short_iron_condor", "iron_butterfly", "short_iron_butterfly"}) 

1852_UNBOUNDED_RISK_STRATEGY_NAMES = frozenset({"short_straddle", "short_strangle"}) 

1853 

1854 

1855def order_enabled_strategies(enabled_strategy_names: list[str], risk_tier_preference: str = "defined_risk_first") -> list[str]: 

1856 """Pure reordering (§9.2): enabled_strategy_names is a PRIORITY list, 

1857 not just a membership set - the first enabled name (in the returned 

1858 order) that matches the current bucket and successfully sizes wins. 

1859 "defined_risk_first" (the safe default) stable-sorts every 

1860 defined-risk name (iron condor/butterfly variants) ahead of every 

1861 unbounded-risk name (short straddle/strangle), preserving the 

1862 caller's own relative order within each group; 

1863 "premium_maximizing_first" inverts that. Names outside both known sets 

1864 (every other strategy) keep their original relative position, 

1865 interleaved after the reordered ones - this function only ever 

1866 reorders, never drops or adds a name.""" 

1867 if risk_tier_preference == "premium_maximizing_first": 

1868 primary, secondary = _UNBOUNDED_RISK_STRATEGY_NAMES, _DEFINED_RISK_STRATEGY_NAMES 

1869 else: 

1870 primary, secondary = _DEFINED_RISK_STRATEGY_NAMES, _UNBOUNDED_RISK_STRATEGY_NAMES 

1871 

1872 primary_names = [name for name in enabled_strategy_names if name in primary] 

1873 secondary_names = [name for name in enabled_strategy_names if name in secondary] 

1874 other_names = [name for name in enabled_strategy_names if name not in primary and name not in secondary] 

1875 return primary_names + secondary_names + other_names 

1876 

1877 

1878def rerank_enabled_strategies_by_score( 

1879 enabled_strategy_names: list[str], strategy_selector_scores: dict[str, float] 

1880) -> list[str]: 

1881 """V4.7 (development/Problems.md #29's own framing) - the learned 

1882 strategy-selector model's live inference plug point: a drop-in 

1883 ALTERNATIVE to order_enabled_strategies()'s static reordering above, 

1884 not a replacement for it. Stable-sorts enabled_strategy_names 

1885 descending by strategy_selector_scores.get(name, float("-inf")) - 

1886 names with no score (the model hasn't seen that strategy_name yet, or 

1887 strategy_selector_scores is a stale/partial version) sink to the end 

1888 in their ORIGINAL relative order, never dropped - same "only ever 

1889 reorders, never drops or adds a name" contract 

1890 order_enabled_strategies() itself keeps. 

1891 

1892 Callers must only invoke this when strategy_selector_scores is 

1893 truthy (non-empty) - risk/asset_class_router.py::route_multi_leg_option_sizing() 

1894 falls back to order_enabled_strategies() itself whenever no trained 

1895 model's scores are available, so this function has no fallback path 

1896 of its own; it is never the byte-identical default.""" 

1897 return sorted( 

1898 enabled_strategy_names, 

1899 key=lambda name: strategy_selector_scores.get(name, float("-inf")), 

1900 reverse=True, 

1901 ) 

1902 

1903 

1904def resolve_enabled_strategy_names(asset: dict[str, Any], global_default: list[str]) -> list[str]: 

1905 """V4.6 (development/Problems.md #59's own deferred item) - per-asset 

1906 `enabled_strategy_names` override: an option asset's `phase1.universe. 

1907 assets` entry may carry an optional 

1908 `"options_strategy_override": {"enabled_strategy_names": [...]}` key 

1909 to trade a DIFFERENT strategy set than the global default (e.g. one 

1910 ticker trades iron condors, another trades covered calls). Returns 

1911 the override when present and non-empty, else `global_default` 

1912 unchanged - byte-identical to every asset with no override key at 

1913 all, which is every asset today (V4.6 adds no default overrides). 

1914 Never raises on a malformed override (falls back to global_default).""" 

1915 override = (asset.get("options_strategy_override") or {}).get("enabled_strategy_names") 

1916 if isinstance(override, list) and override: 

1917 return override 

1918 return global_default 

1919 

1920 

1921# --------------------------------------------------------------------------- 

1922# Covered/protective/collar sizing (§6/§9.3/§9.6) - a THIRD sizing paradigm 

1923# alongside vega-budget and margin: the option leg(s) are sized as a ratio 

1924# against the EQUITY leg's currently-held quantity, never against a 

1925# confidence-scaled vega/margin budget of their own. main.py never submits 

1926# the bundled OptionStrategies.covered_call/etc. factory as an order (it 

1927# would bundle an independent equity trade into the combo, fighting the 

1928# standalone equity asset's own signal) - only this sizing decision's 

1929# option leg(s) are ever placed, via the existing single-leg order 

1930# machinery, see main.py's own corrected design note. 

1931# --------------------------------------------------------------------------- 

1932 

1933 

1934def build_covered_protective_position_sizing( 

1935 strategy_name: str, 

1936 confidence: float, 

1937 available_chain: list[dict], 

1938 equity_quantity: float, 

1939 contract_multiplier: float = 100.0, 

1940 target_delta_at_full_confidence: float = 0.30, 

1941) -> OptionsMultiLegPositionDecision | None: 

1942 """Sizes covered_call/covered_put/protective_call/protective_put/ 

1943 protective_collar's option leg(s) purely as floor(|equity_quantity| / 

1944 contract_multiplier) - the number of contracts the CURRENTLY HELD 

1945 equity position actually covers, never a vega/confidence-scaled 

1946 target of its own (§9.3's floor-rounding: any fractional remainder is 

1947 carried as plain uncovered equity, never partially hedged). 

1948 

1949 equity_quantity must carry the correct SIGN for this strategy's 

1950 covering_equity_side (positive/long for covered_call, protective_put, 

1951 protective_collar; negative/short for covered_put, protective_call) - 

1952 a mismatched sign (e.g. a short equity holding passed for 

1953 covered_call, which needs a LONG holding) returns None rather than 

1954 sizing against the wrong side of the book. Returns None for any 

1955 strategy_name whose risk_tier isn't "covered_protective", for 

1956 confidence <= 0, or when floor rounding or leg selection yields 

1957 nothing - never raises.""" 

1958 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name) 

1959 if spec is None or spec.risk_tier != "covered_protective": 

1960 return None 

1961 

1962 confidence = max(0.0, min(float(confidence), 1.0)) 

1963 if confidence == 0.0 or contract_multiplier <= 0.0: 

1964 return None 

1965 if spec.covering_equity_side == "long" and equity_quantity <= 0.0: 

1966 return None 

1967 if spec.covering_equity_side == "short" and equity_quantity >= 0.0: 

1968 return None 

1969 

1970 contracts = int(math.floor(abs(equity_quantity) / contract_multiplier)) 

1971 if contracts <= 0: 

1972 return None 

1973 

1974 target_delta = target_delta_at_full_confidence * confidence 

1975 legs_by_role = select_strategy_legs(strategy_name, available_chain, target_delta) 

1976 if legs_by_role is None: 

1977 return None 

1978 

1979 return OptionsMultiLegPositionDecision( 

1980 strategy_name=strategy_name, 

1981 legs=_legs_tuple_from_roles(spec, legs_by_role), 

1982 expiries=_expiries_tuple_from_roles(spec, legs_by_role), 

1983 contracts=contracts, 

1984 net_debit_or_credit=0.0, 

1985 net_delta=0.0, 

1986 net_vega=0.0, 

1987 sizing_reason="equity_ratio_covered_protective_sizing", 

1988 ) 

1989 

1990 

1991def option_auto_close_due(current_date: date, expiry_date: date, auto_close_days_before_expiry: int = 2) -> bool: 

1992 """§9.5 - the narrow expiry-day safety net: True once `expiry_date` is 

1993 within auto_close_days_before_expiry calendar days of current_date. 

1994 Pure date comparison, mirroring risk/futures_risk.py::rollover_due()'s 

1995 own pattern exactly (generalized from futures rollover to options 

1996 expiry) - a diagnostic/trigger signal only, main.py's own force- 

1997 liquidate call is what actually acts on it. Returns False when 

1998 expiry_date is unparseable/unknown - never raises, matching every 

1999 other pure predicate in this module's degrade-to-absent convention.""" 

2000 if current_date is None or expiry_date is None: 

2001 return False 

2002 return (expiry_date - current_date).days <= auto_close_days_before_expiry 

2003 

2004 

2005def rotation_cooldown_active(current_bar_index: int, last_rotation_bar: int | None, cooldown_bars: int) -> bool: 

2006 """V4.6 (development/Problems.md #57/#58/#59) - anti-thrashing guard 

2007 for options rotation: True while `current_bar_index` is within 

2008 `cooldown_bars` of the last bar a rotation (liquidate + re-enter) 

2009 actually executed for this symbol_key. Pure bar-index arithmetic, 

2010 mirroring option_auto_close_due()'s own pure-predicate-only pattern - 

2011 main.py's rotate_on_drift branch is what actually degrades to the 

2012 "manage nearest position in place" fallback when this returns True, 

2013 never a hard block. Returns False (cooldown never active) when 

2014 `last_rotation_bar` is None - no rotation has ever fired for this 

2015 symbol_key yet, never a crash on the first-ever rotation.""" 

2016 if last_rotation_bar is None: 

2017 return False 

2018 return (current_bar_index - last_rotation_bar) < cooldown_bars