Coverage for portfolio/options_margin_sizing.py: 100%

106 statements  

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

1"""Margin-based sizing for the options strategies whose risk profile a 

2vega budget cannot safely represent - genuinely unbounded-risk shorts 

3(naked calls/puts, short straddles/strangles, and the two backspread 

4variants that invert into a net-short position) and bounded-but- 

5asymmetric-ratio structures (ladders' uncovered excess leg, backspreads' 

6defined max loss). portfolio/options_strategy.py's build_multi_leg_ 

7position_sizing() explicitly refuses every strategy_name whose 

8StrategySpec.risk_tier isn't "vega_budget" - this module is where those 

9refused strategies get sized instead, mirroring risk/futures_risk.py's 

10own margin-utilization-targeted (soft target, hard ceiling) shape rather 

11than risk/position_sizing.py's volatility-of-notional model. 

12 

13Every formula here is an explicitly documented FIRST APPROXIMATION, not 

14broker-accurate margin (development/Problems.md) - IB's real margin 

15engine (SPAN/Reg-T with portfolio margining nuances) is not modeled. 

16This entire family is hard-gated in main.py to runtime_mode == "backtest" 

17as a code-level invariant, not just a config flag a user could flip - see 

18main.py's own gate for why. 

19 

20Two real corrections to this feature's own initial plan were found while 

21transcribing the ACTUAL Lean leg quantities in options_strategy.py (see 

22that module's own note): only bull_call_ladder/bear_put_ladder are 

23genuinely uncovered (bear_call_ladder/bull_put_ladder are net-long and 

24belong in the vega_budget tier instead), and only short_call_backspread/ 

25short_put_backspread are genuinely unbounded (call_backspread/ 

26put_backspread are net-long and bounded, staying in this module's 

27bounded-max-loss sub-model, not the naked one). 

28""" 

29 

30from __future__ import annotations 

31 

32from dataclasses import dataclass 

33from typing import Any 

34 

35from portfolio.options_strategy import ( 

36 MULTI_LEG_STRATEGY_REGISTRY, 

37 OptionsSpreadLeg, 

38 _expiries_tuple_from_roles, 

39 _legs_tuple_from_roles, 

40 select_strategy_legs, 

41) 

42 

43 

44@dataclass(frozen=True) 

45class MarginSizingDecision: 

46 """Margin-tier sibling of OptionsMultiLegPositionDecision - same 

47 legs/expiries/contracts/strategy_name/sizing_reason shape (so 

48 main.py's record-building code can treat either decision type 

49 identically via duck typing), plus margin_required/margin_utilization 

50 in place of net_debit_or_credit/net_delta/net_vega (a margin-tier 

51 position's defining risk unit is margin consumed, not vega).""" 

52 

53 strategy_name: str 

54 legs: tuple[OptionsSpreadLeg, ...] 

55 expiries: tuple[str, ...] 

56 contracts: int 

57 margin_required: float # total $ margin consumed by `contracts` spread units 

58 margin_utilization: float # margin_required / portfolio_value 

59 sizing_reason: str 

60 

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

62 return { 

63 "strategy_name": self.strategy_name, 

64 "legs": [ 

65 { 

66 "strike": leg.strike, 

67 "right": leg.right, 

68 "side": leg.side, 

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

70 } 

71 for leg in self.legs 

72 ], 

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

74 "contracts": self.contracts, 

75 "margin_required": self.margin_required, 

76 "margin_utilization": self.margin_utilization, 

77 "sizing_reason": self.sizing_reason, 

78 } 

79 

80 

81def _naked_margin_per_contract( 

82 underlying_price: float, 

83 strike: float, 

84 right: str, 

85 contract_multiplier: float, 

86 pct_of_underlying_value: float, 

87 min_pct_of_underlying_value: float, 

88) -> float: 

89 """Simplified Reg-T-style naked margin for ONE short contract: 

90 max(pct_of_underlying_value * underlying_price - otm_amount, 

91 min_pct_of_underlying_value * underlying_price) * contract_multiplier. 

92 otm_amount is strike-price for a short call (OTM when strike > price) 

93 or price-strike for a short put (OTM when price > strike), floored at 

94 0 (an ITM short option gets no OTM discount). Explicitly NOT 

95 broker-accurate - see module docstring.""" 

96 if underlying_price <= 0.0 or contract_multiplier <= 0.0: 

97 return 0.0 

98 otm_amount = max(strike - underlying_price, 0.0) if right == "call" else max(underlying_price - strike, 0.0) 

99 per_contract = max( 

100 pct_of_underlying_value * underlying_price - otm_amount, 

101 min_pct_of_underlying_value * underlying_price, 

102 ) 

103 return per_contract * contract_multiplier 

104 

105 

106def _contracts_from_margin_budget( 

107 margin_per_spread_unit: float, confidence: float, portfolio_value: float, 

108 target_margin_utilization: float, max_margin_utilization: float, 

109) -> int: 

110 """Same soft-target/hard-ceiling shape as 

111 risk/futures_risk.py::build_futures_position_sizing() - scales toward 

112 target_margin_utilization by confidence, never exceeding the hard 

113 max_margin_utilization ceiling regardless of confidence.""" 

114 if margin_per_spread_unit <= 0.0: 

115 return 0 

116 confidence_multiplier = 0.5 + 0.5 * confidence 

117 max_affordable = int(portfolio_value * max_margin_utilization // margin_per_spread_unit) 

118 at_target = int(portfolio_value * target_margin_utilization // margin_per_spread_unit) 

119 return max(min(int(at_target * confidence_multiplier), max_affordable), 0) 

120 

121 

122def build_margin_position_sizing( 

123 strategy_name: str, 

124 signal_direction: str, 

125 confidence: float, 

126 available_chain: list[dict], 

127 underlying_price: float, 

128 portfolio_value: float, 

129 contract_multiplier: float = 100.0, 

130 target_delta_at_full_confidence: float = 0.60, 

131 target_margin_utilization: float = 0.20, 

132 max_margin_utilization: float = 0.40, 

133 pct_of_underlying_value: float = 0.20, 

134 min_pct_of_underlying_value: float = 0.10, 

135 **selector_tuning_kwargs: Any, 

136) -> MarginSizingDecision | None: 

137 """The single public entry point for every margin-tier strategy 

138 (risk_tier in {"margin_naked", "margin_uncovered_leg", 

139 "margin_bounded_backspread"}) - dispatches leg selection via 

140 options_strategy.select_strategy_legs() (the SAME registry-driven 

141 selector every vega-budget strategy uses, so a ladder's or 

142 backspread's strikes are chosen identically regardless of which 

143 sizing model ultimately budgets it), then sizes via the sub-model its 

144 risk_tier maps to. Returns None for confidence/portfolio_value <= 0, 

145 an invalid signal_direction, a non-margin-tier strategy_name (sized by 

146 options_strategy.py instead), or when selection/margin-budget rounds 

147 to zero contracts - never raises.""" 

148 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name) 

149 if spec is None or spec.risk_tier not in ( 

150 "margin_naked", "margin_uncovered_leg", "margin_bounded_backspread", 

151 ): 

152 return None 

153 

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

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

156 underlying_price = max(float(underlying_price), 0.0) 

157 if confidence == 0.0 or portfolio_value <= 0.0 or underlying_price <= 0.0: 

158 return None 

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

160 return None 

161 

162 target_delta = target_delta_at_full_confidence * confidence 

163 legs_by_role = select_strategy_legs(strategy_name, available_chain, target_delta, **selector_tuning_kwargs) 

164 if legs_by_role is None: 

165 return None 

166 

167 if spec.risk_tier == "margin_naked": 

168 margin_per_unit = _naked_margin_requirement_for_naked_tier( 

169 spec, legs_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value, 

170 ) 

171 reason = "reg_t_style_naked_margin_sizing" 

172 elif spec.risk_tier == "margin_uncovered_leg": 

173 margin_per_unit = _uncovered_leg_margin_requirement( 

174 spec, legs_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value, 

175 ) 

176 reason = "uncovered_ladder_leg_margin_sizing" 

177 else: 

178 margin_per_unit = _bounded_backspread_max_loss(spec, legs_by_role, contract_multiplier) 

179 reason = "bounded_max_loss_backspread_margin_sizing" 

180 

181 contracts = _contracts_from_margin_budget( 

182 margin_per_unit, confidence, portfolio_value, target_margin_utilization, max_margin_utilization, 

183 ) 

184 if contracts <= 0: 

185 return None 

186 

187 margin_required = contracts * margin_per_unit 

188 return MarginSizingDecision( 

189 strategy_name=strategy_name, 

190 legs=_legs_tuple_from_roles(spec, legs_by_role), 

191 expiries=_expiries_tuple_from_roles(spec, legs_by_role), 

192 contracts=contracts, 

193 margin_required=margin_required, 

194 margin_utilization=margin_required / portfolio_value, 

195 sizing_reason=reason, 

196 ) 

197 

198 

199def build_margin_position_sizing_for_legs( 

200 strategy_name: str, 

201 held_rows_by_role: dict[str, dict], 

202 underlying_price: float, 

203 portfolio_value: float, 

204 contract_multiplier: float = 100.0, 

205 max_margin_utilization: float = 0.40, 

206 pct_of_underlying_value: float = 0.20, 

207 min_pct_of_underlying_value: float = 0.10, 

208) -> MarginSizingDecision | None: 

209 """Resize-in-place sibling of build_margin_position_sizing() - sizes 

210 an ALREADY-HELD margin-tier position on its legs' own current chain 

211 rows, skipping selection entirely (held_rows_by_role must carry an 

212 entry for every role in MULTI_LEG_STRATEGY_REGISTRY[strategy_name].legs, 

213 same shape select_strategy_legs() returns). No confidence-scaled soft 

214 target here - the position already exists, so sizing is to the full 

215 max_margin_utilization ceiling directly, the same "size to budget on 

216 already-resolved greeks, no fresh confidence input" convention 

217 options_strategy.py's build_multi_leg_position_sizing_for_legs() and 

218 build_options_position_sizing_for_contract() already use.""" 

219 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name) 

220 if spec is None or spec.risk_tier not in ( 

221 "margin_naked", "margin_uncovered_leg", "margin_bounded_backspread", 

222 ): 

223 return None 

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

225 underlying_price = max(float(underlying_price), 0.0) 

226 if portfolio_value <= 0.0 or underlying_price <= 0.0: 

227 return None 

228 

229 if spec.risk_tier == "margin_naked": 

230 margin_per_unit = _naked_margin_requirement_for_naked_tier( 

231 spec, held_rows_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value, 

232 ) 

233 reason = "held_legs_own_greeks_naked_margin_sizing" 

234 elif spec.risk_tier == "margin_uncovered_leg": 

235 margin_per_unit = _uncovered_leg_margin_requirement( 

236 spec, held_rows_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value, 

237 ) 

238 reason = "held_legs_own_greeks_uncovered_leg_margin_sizing" 

239 else: 

240 margin_per_unit = _bounded_backspread_max_loss(spec, held_rows_by_role, contract_multiplier) 

241 reason = "held_legs_own_greeks_bounded_backspread_margin_sizing" 

242 

243 if margin_per_unit <= 0.0: 

244 return None 

245 contracts = int(portfolio_value * max_margin_utilization // margin_per_unit) 

246 if contracts <= 0: 

247 return None 

248 

249 margin_required = contracts * margin_per_unit 

250 return MarginSizingDecision( 

251 strategy_name=strategy_name, 

252 legs=_legs_tuple_from_roles(spec, held_rows_by_role), 

253 expiries=_expiries_tuple_from_roles(spec, held_rows_by_role), 

254 contracts=contracts, 

255 margin_required=margin_required, 

256 margin_utilization=margin_required / portfolio_value, 

257 sizing_reason=reason, 

258 ) 

259 

260 

261def _naked_margin_requirement_for_naked_tier( 

262 spec, legs_by_role: dict[str, Any], underlying_price: float, contract_multiplier: float, 

263 pct_of_underlying_value: float, min_pct_of_underlying_value: float, 

264) -> float: 

265 """naked_call/naked_put: the single short leg's own naked margin. 

266 short_straddle/short_strangle: the broker convention of "margin on the 

267 greater side only" (both legs can't be assigned against the same 

268 move) - max() of the two legs' naked margin, NOT the sum; the premium 

269 credit from the other leg is ignored (conservative - overestimates 

270 margin required in the direction of safety). short_call_backspread/ 

271 short_put_backspread: naked margin at the heavier-ratio (2x) SHORT 

272 leg's strike, per SPREAD UNIT (i.e. for the 2 short contracts one 

273 spread unit implies) - the 1 long contract's partial hedge is 

274 deliberately ignored, the same conservative-direction simplification.""" 

275 short_legs = [leg for leg in spec.legs if leg.side == "short"] 

276 per_leg_margins = [ 

277 _naked_margin_per_contract( 

278 underlying_price, float(legs_by_role[leg.role]["strike"]), leg.right, contract_multiplier, 

279 pct_of_underlying_value, min_pct_of_underlying_value, 

280 ) * leg.ratio 

281 for leg in short_legs 

282 ] 

283 if not per_leg_margins: 

284 return 0.0 

285 if len(short_legs) == 1: 

286 return per_leg_margins[0] 

287 return max(per_leg_margins) 

288 

289 

290def _uncovered_leg_margin_requirement( 

291 spec, legs_by_role: dict[str, Any], underlying_price: float, contract_multiplier: float, 

292 pct_of_underlying_value: float, min_pct_of_underlying_value: float, 

293) -> float: 

294 """bull_call_ladder/bear_put_ladder only (risk_tier == 

295 "margin_uncovered_leg") - of the ladder's 3 legs (1 long + 2 short, 

296 same ratio), exactly 1 short contract is genuinely uncovered (the 

297 other is offset 1:1 by the long leg); naked margin applies to ONE 

298 contract at the strike furthest from the long leg (the excess leg), 

299 never to both short legs (that would double-count the 1:1-hedged 

300 short).""" 

301 long_leg = next(leg for leg in spec.legs if leg.side == "long") 

302 short_legs = [leg for leg in spec.legs if leg.side == "short"] 

303 long_strike = float(legs_by_role[long_leg.role]["strike"]) 

304 excess_leg = max(short_legs, key=lambda leg: abs(float(legs_by_role[leg.role]["strike"]) - long_strike)) 

305 return _naked_margin_per_contract( 

306 underlying_price, float(legs_by_role[excess_leg.role]["strike"]), excess_leg.right, contract_multiplier, 

307 pct_of_underlying_value, min_pct_of_underlying_value, 

308 ) 

309 

310 

311def _bounded_backspread_max_loss(spec, legs_by_role: dict[str, Any], contract_multiplier: float) -> float: 

312 """call_backspread/put_backspread only (risk_tier == 

313 "margin_bounded_backspread") - defined max loss per spread unit: 

314 (strike_width - net_credit) * contract_multiplier, occurring at the 

315 far (heavier-ratio) strike. net_credit uses bid/ask when present 

316 (short leg's bid minus long leg's ask * ratio), 0.0 when absent (the 

317 same "never let a missing diagnostic field gate sizing" convention as 

318 the vega-budget path's net_debit_or_credit) - a 0.0 credit assumption 

319 is the conservative (larger max-loss) direction.""" 

320 short_leg = next(leg for leg in spec.legs if leg.side == "short") 

321 long_leg = next(leg for leg in spec.legs if leg.side == "long") 

322 short_row = legs_by_role[short_leg.role] 

323 long_row = legs_by_role[long_leg.role] 

324 strike_width = abs(float(long_row["strike"]) - float(short_row["strike"])) 

325 

326 short_bid = short_row.get("bid") 

327 long_ask = long_row.get("ask") 

328 if short_bid is not None and long_ask is not None: 

329 net_credit = short_leg.ratio * float(short_bid) - long_leg.ratio * float(long_ask) 

330 else: 

331 net_credit = 0.0 

332 

333 max_loss_per_unit = strike_width - net_credit 

334 return max(max_loss_per_unit, 0.0) * contract_multiplier