aether-quant 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. aether_quant-0.0.1.dist-info/METADATA +7 -0
  2. aether_quant-0.0.1.dist-info/RECORD +99 -0
  3. aether_quant-0.0.1.dist-info/WHEEL +5 -0
  4. aether_quant-0.0.1.dist-info/entry_points.txt +2 -0
  5. aether_quant-0.0.1.dist-info/licenses/LICENSE +133 -0
  6. aether_quant-0.0.1.dist-info/top_level.txt +13 -0
  7. analyzer/README.md +69 -0
  8. analyzer/__init__.py +17 -0
  9. analyzer/market_analyzer.py +521 -0
  10. aq_cli.py +3633 -0
  11. audit/README.md +47 -0
  12. audit/__init__.py +38 -0
  13. audit/hash_chain.py +52 -0
  14. audit/postgres_audit.py +61 -0
  15. audit/postgres_worker.py +402 -0
  16. audit/redis_queue.py +124 -0
  17. audit/status_export.py +62 -0
  18. data_pipeline/README.md +257 -0
  19. data_pipeline/__init__.py +6 -0
  20. data_pipeline/bar_synthesis.py +97 -0
  21. data_pipeline/dividend_backfill.py +243 -0
  22. data_pipeline/factor_file_backfill.py +276 -0
  23. data_pipeline/fetch.py +206 -0
  24. data_pipeline/fred_backfill.py +435 -0
  25. data_pipeline/ib_backfill.py +287 -0
  26. data_pipeline/v2_manifest.py +75 -0
  27. data_pipeline/yfinance_backfill.py +501 -0
  28. evaluation/README.md +152 -0
  29. evaluation/__init__.py +73 -0
  30. evaluation/ablation.py +310 -0
  31. evaluation/benchmark_comparison.py +195 -0
  32. evaluation/confidence_threshold_calibration.py +157 -0
  33. evaluation/factor_neutralization_check.py +94 -0
  34. evaluation/feature_parity.py +321 -0
  35. evaluation/feature_reconciliation.py +286 -0
  36. evaluation/impact_model.py +77 -0
  37. evaluation/kill_switch_replay.py +186 -0
  38. evaluation/limit_fill_simulator.py +152 -0
  39. evaluation/model_predictions.py +192 -0
  40. evaluation/monte_carlo.py +161 -0
  41. evaluation/public_benchmarks.py +117 -0
  42. evaluation/rank_book_simulator.py +494 -0
  43. evaluation/rank_ic_core.py +204 -0
  44. evaluation/rank_signal_calibration.py +690 -0
  45. evaluation/rolling_ic_gate_calibration.py +190 -0
  46. evaluation/rolling_ic_gate_replay.py +138 -0
  47. execution/README.md +281 -0
  48. execution/__init__.py +80 -0
  49. execution/config_cache.py +48 -0
  50. execution/cost_model.py +213 -0
  51. execution/lean_config_render.py +131 -0
  52. execution/live_credentials.py +38 -0
  53. execution/live_credentials_io.py +52 -0
  54. execution/order_gate.py +388 -0
  55. execution/paper_readiness.py +181 -0
  56. execution/paper_readiness_io.py +54 -0
  57. execution/paper_readiness_report.py +103 -0
  58. execution/paper_readiness_scheduler.py +137 -0
  59. execution/reconciliation.py +160 -0
  60. execution/runtime_config_io.py +38 -0
  61. execution/secret_scan.py +73 -0
  62. features/README.md +77 -0
  63. features/__init__.py +137 -0
  64. features/alt_data_features.py +154 -0
  65. features/bond_features.py +275 -0
  66. features/cross_asset_sensitivity.py +79 -0
  67. features/derivatives_macro_features.py +72 -0
  68. features/macro_features.py +79 -0
  69. features/options_greeks.py +329 -0
  70. features/sector_map.py +53 -0
  71. features/technical_indicators.py +185 -0
  72. generate_backtest_report.py +311 -0
  73. generate_evaluation_report.py +712 -0
  74. inference/README.md +105 -0
  75. inference/__init__.py +36 -0
  76. inference/exported_model.py +929 -0
  77. inference/parallel_inference.py +160 -0
  78. inference/strategy_selector_inference.py +75 -0
  79. json_safety.py +130 -0
  80. portfolio/README.md +447 -0
  81. portfolio/__init__.py +41 -0
  82. portfolio/book_construction.py +786 -0
  83. portfolio/book_neutrality.py +178 -0
  84. portfolio/hrp_allocation.py +159 -0
  85. portfolio/options_arbitrage_detector.py +232 -0
  86. portfolio/options_assignment_risk.py +119 -0
  87. portfolio/options_margin_sizing.py +333 -0
  88. portfolio/options_strategy.py +1999 -0
  89. portfolio/rank_signal.py +219 -0
  90. portfolio/rolling_ic_gate.py +183 -0
  91. risk/README.md +275 -0
  92. risk/__init__.py +38 -0
  93. risk/asset_class_router.py +584 -0
  94. risk/forex_risk.py +158 -0
  95. risk/futures_risk.py +202 -0
  96. risk/kill_switch.py +261 -0
  97. risk/manual_override.py +118 -0
  98. risk/position_sizing.py +303 -0
  99. risk/rl_sizing.py +189 -0
@@ -0,0 +1,119 @@
1
+ """Early-call-assignment-risk signal (V4.7, development/Problems.md -
2
+ early-assignment probability/pricing modeling) - a genuinely distinct
3
+ concern from options_strategy.py's sizing/selection logic, so it lives in
4
+ its own module rather than folded in there.
5
+
6
+ Pure, stdlib-only functions (math only - no scipy/numpy, same convention
7
+ as features/options_greeks.py and every other portfolio/risk module),
8
+ every function degrades to a neutral "no risk detected" default (0.0/
9
+ False) on missing input rather than raising - main.py's
10
+ _apply_option_assignment_risk_sweep() is what actually acts on this
11
+ module's output, this module only ever computes the signal.
12
+
13
+ Scope, deliberately narrow: this module ONLY addresses dividend-driven
14
+ early exercise of a SHORT CALL leg - the one shape where the classic
15
+ textbook early-exercise-optimality rule (exercise early only when the
16
+ option's extrinsic value is less than the dividend about to be captured)
17
+ applies. A short PUT approaching expiry deep ITM is a pin-risk concern
18
+ already partly covered by portfolio/options_strategy.py::option_auto_close_due()'s
19
+ calendar-days-to-expiry safety net, not a dividend-driven concern - out of
20
+ scope here by construction (assignment_risk_score() below always scores a
21
+ put at 0.0).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import math
27
+
28
+ _SQRT_2PI = math.sqrt(2.0 * math.pi)
29
+
30
+
31
+ def _normal_cdf(x: float) -> float:
32
+ return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))
33
+
34
+
35
+ def extrinsic_value(option_price: float | None, spot: float, strike: float, right: str) -> float | None:
36
+ """option_price minus intrinsic value. Returns None (not 0.0) when
37
+ option_price is missing/non-positive - "unknown extrinsic value" must
38
+ never be indistinguishable from "zero extrinsic value" (a real,
39
+ meaningful early-exercise trigger condition in its own right), the
40
+ same None-vs-neutral-default distinction features/bond_features.py's
41
+ module docstring already establishes for this codebase."""
42
+ if option_price is None or option_price <= 0.0:
43
+ return None
44
+ intrinsic = max(spot - strike, 0.0) if right.lower() == "call" else max(strike - spot, 0.0)
45
+ return option_price - intrinsic
46
+
47
+
48
+ def early_exercise_optimal_for_dividend(extrinsic_value: float | None, expected_dividend_amount: float | None) -> bool:
49
+ """Classic textbook rule: early call exercise is optimal only when the
50
+ option's extrinsic value is LESS than the dividend the holder would
51
+ capture by exercising before ex-div (they give up less time value than
52
+ they gain in dividend). Returns False (never optimal) when either
53
+ input is None - an unknown value never triggers a false-positive risk
54
+ flag."""
55
+ if extrinsic_value is None or expected_dividend_amount is None:
56
+ return False
57
+ return extrinsic_value < expected_dividend_amount
58
+
59
+
60
+ def days_to_next_ex_dividend(current_date, next_ex_dividend_date) -> int | None:
61
+ """Pure date arithmetic, mirrors options_strategy.option_auto_close_due()'s
62
+ own calendar-day-diff pattern. None when either input is missing -
63
+ never raises."""
64
+ if current_date is None or next_ex_dividend_date is None:
65
+ return None
66
+ return (next_ex_dividend_date - current_date).days
67
+
68
+
69
+ def assignment_risk_score(
70
+ moneyness: float | None,
71
+ right: str,
72
+ extrinsic_value: float | None,
73
+ expected_dividend_amount: float | None,
74
+ days_to_next_ex_div: int | None,
75
+ window_days: int,
76
+ ) -> float:
77
+ """0.0-1.0 composite early-call-assignment-risk score.
78
+
79
+ Call-only by construction: a put always scores 0.0 (an upcoming
80
+ dividend never makes early exercise of a long put rational - dividends
81
+ only ever pull CALL exercise forward). Also 0.0 whenever: the leg
82
+ isn't in-the-money (moneyness <= 1.0), there's no known upcoming
83
+ ex-dividend date within window_days (including a negative
84
+ days_to_next_ex_div - already past due, stale schedule), window_days
85
+ itself is non-positive, or extrinsic_value/expected_dividend_amount is
86
+ unknown (None) or expected_dividend_amount is non-positive.
87
+
88
+ Within the risk window: scores at the time-proximity ceiling when
89
+ early_exercise_optimal_for_dividend() is already True (extrinsic value
90
+ below the expected dividend); otherwise decays smoothly via this
91
+ module's own _normal_cdf() as the extrinsic-value cushion over the
92
+ dividend widens (reusing this codebase's existing probabilistic
93
+ vocabulary rather than inventing an ad hoc formula), further scaled by
94
+ how close the ex-dividend date actually is within the window. Never
95
+ raises."""
96
+ if right.lower() != "call":
97
+ return 0.0
98
+ if moneyness is None or moneyness <= 1.0:
99
+ return 0.0
100
+ if window_days <= 0:
101
+ return 0.0
102
+ if days_to_next_ex_div is None or days_to_next_ex_div < 0 or days_to_next_ex_div > window_days:
103
+ return 0.0
104
+ if extrinsic_value is None or expected_dividend_amount is None or expected_dividend_amount <= 0.0:
105
+ return 0.0
106
+
107
+ time_factor = 1.0 - (days_to_next_ex_div / window_days)
108
+
109
+ if early_exercise_optimal_for_dividend(extrinsic_value, expected_dividend_amount):
110
+ return time_factor
111
+
112
+ cushion_ratio = (extrinsic_value - expected_dividend_amount) / expected_dividend_amount
113
+ cushion_factor = 2.0 * (1.0 - _normal_cdf(cushion_ratio))
114
+ return time_factor * cushion_factor
115
+
116
+
117
+ def assignment_risk_flag(score: float, threshold: float) -> bool:
118
+ """Pure threshold predicate - the sweep-trigger boundary."""
119
+ return score >= threshold
@@ -0,0 +1,333 @@
1
+ """Margin-based sizing for the options strategies whose risk profile a
2
+ vega budget cannot safely represent - genuinely unbounded-risk shorts
3
+ (naked calls/puts, short straddles/strangles, and the two backspread
4
+ variants that invert into a net-short position) and bounded-but-
5
+ asymmetric-ratio structures (ladders' uncovered excess leg, backspreads'
6
+ defined max loss). portfolio/options_strategy.py's build_multi_leg_
7
+ position_sizing() explicitly refuses every strategy_name whose
8
+ StrategySpec.risk_tier isn't "vega_budget" - this module is where those
9
+ refused strategies get sized instead, mirroring risk/futures_risk.py's
10
+ own margin-utilization-targeted (soft target, hard ceiling) shape rather
11
+ than risk/position_sizing.py's volatility-of-notional model.
12
+
13
+ Every formula here is an explicitly documented FIRST APPROXIMATION, not
14
+ broker-accurate margin (development/Problems.md) - IB's real margin
15
+ engine (SPAN/Reg-T with portfolio margining nuances) is not modeled.
16
+ This entire family is hard-gated in main.py to runtime_mode == "backtest"
17
+ as a code-level invariant, not just a config flag a user could flip - see
18
+ main.py's own gate for why.
19
+
20
+ Two real corrections to this feature's own initial plan were found while
21
+ transcribing the ACTUAL Lean leg quantities in options_strategy.py (see
22
+ that module's own note): only bull_call_ladder/bear_put_ladder are
23
+ genuinely uncovered (bear_call_ladder/bull_put_ladder are net-long and
24
+ belong in the vega_budget tier instead), and only short_call_backspread/
25
+ short_put_backspread are genuinely unbounded (call_backspread/
26
+ put_backspread are net-long and bounded, staying in this module's
27
+ bounded-max-loss sub-model, not the naked one).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ from dataclasses import dataclass
33
+
34
+ from portfolio.options_strategy import (
35
+ MULTI_LEG_STRATEGY_REGISTRY,
36
+ OptionsSpreadLeg,
37
+ _expiries_tuple_from_roles,
38
+ _legs_tuple_from_roles,
39
+ select_strategy_legs,
40
+ )
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class MarginSizingDecision:
45
+ """Margin-tier sibling of OptionsMultiLegPositionDecision - same
46
+ legs/expiries/contracts/strategy_name/sizing_reason shape (so
47
+ main.py's record-building code can treat either decision type
48
+ identically via duck typing), plus margin_required/margin_utilization
49
+ in place of net_debit_or_credit/net_delta/net_vega (a margin-tier
50
+ position's defining risk unit is margin consumed, not vega)."""
51
+
52
+ strategy_name: str
53
+ legs: tuple[OptionsSpreadLeg, ...]
54
+ expiries: tuple[str, ...]
55
+ contracts: int
56
+ margin_required: float # total $ margin consumed by `contracts` spread units
57
+ margin_utilization: float # margin_required / portfolio_value
58
+ sizing_reason: str
59
+
60
+ def to_dict(self) -> dict:
61
+ return {
62
+ "strategy_name": self.strategy_name,
63
+ "legs": [
64
+ {
65
+ "strike": leg.strike,
66
+ "right": leg.right,
67
+ "side": leg.side,
68
+ "contract_symbol": str(leg.contract_symbol) if leg.contract_symbol is not None else None,
69
+ }
70
+ for leg in self.legs
71
+ ],
72
+ "expiries": list(self.expiries),
73
+ "contracts": self.contracts,
74
+ "margin_required": self.margin_required,
75
+ "margin_utilization": self.margin_utilization,
76
+ "sizing_reason": self.sizing_reason,
77
+ }
78
+
79
+
80
+ def _naked_margin_per_contract(
81
+ underlying_price: float,
82
+ strike: float,
83
+ right: str,
84
+ contract_multiplier: float,
85
+ pct_of_underlying_value: float,
86
+ min_pct_of_underlying_value: float,
87
+ ) -> float:
88
+ """Simplified Reg-T-style naked margin for ONE short contract:
89
+ max(pct_of_underlying_value * underlying_price - otm_amount,
90
+ min_pct_of_underlying_value * underlying_price) * contract_multiplier.
91
+ otm_amount is strike-price for a short call (OTM when strike > price)
92
+ or price-strike for a short put (OTM when price > strike), floored at
93
+ 0 (an ITM short option gets no OTM discount). Explicitly NOT
94
+ broker-accurate - see module docstring."""
95
+ if underlying_price <= 0.0 or contract_multiplier <= 0.0:
96
+ return 0.0
97
+ otm_amount = max(strike - underlying_price, 0.0) if right == "call" else max(underlying_price - strike, 0.0)
98
+ per_contract = max(
99
+ pct_of_underlying_value * underlying_price - otm_amount,
100
+ min_pct_of_underlying_value * underlying_price,
101
+ )
102
+ return per_contract * contract_multiplier
103
+
104
+
105
+ def _contracts_from_margin_budget(
106
+ margin_per_spread_unit: float, confidence: float, portfolio_value: float,
107
+ target_margin_utilization: float, max_margin_utilization: float,
108
+ ) -> int:
109
+ """Same soft-target/hard-ceiling shape as
110
+ risk/futures_risk.py::build_futures_position_sizing() - scales toward
111
+ target_margin_utilization by confidence, never exceeding the hard
112
+ max_margin_utilization ceiling regardless of confidence."""
113
+ if margin_per_spread_unit <= 0.0:
114
+ return 0
115
+ confidence_multiplier = 0.5 + 0.5 * confidence
116
+ max_affordable = int(portfolio_value * max_margin_utilization // margin_per_spread_unit)
117
+ at_target = int(portfolio_value * target_margin_utilization // margin_per_spread_unit)
118
+ return max(min(int(at_target * confidence_multiplier), max_affordable), 0)
119
+
120
+
121
+ def build_margin_position_sizing(
122
+ strategy_name: str,
123
+ signal_direction: str,
124
+ confidence: float,
125
+ available_chain: list[dict],
126
+ underlying_price: float,
127
+ portfolio_value: float,
128
+ contract_multiplier: float = 100.0,
129
+ target_delta_at_full_confidence: float = 0.60,
130
+ target_margin_utilization: float = 0.20,
131
+ max_margin_utilization: float = 0.40,
132
+ pct_of_underlying_value: float = 0.20,
133
+ min_pct_of_underlying_value: float = 0.10,
134
+ **selector_tuning_kwargs,
135
+ ) -> MarginSizingDecision | None:
136
+ """The single public entry point for every margin-tier strategy
137
+ (risk_tier in {"margin_naked", "margin_uncovered_leg",
138
+ "margin_bounded_backspread"}) - dispatches leg selection via
139
+ options_strategy.select_strategy_legs() (the SAME registry-driven
140
+ selector every vega-budget strategy uses, so a ladder's or
141
+ backspread's strikes are chosen identically regardless of which
142
+ sizing model ultimately budgets it), then sizes via the sub-model its
143
+ risk_tier maps to. Returns None for confidence/portfolio_value <= 0,
144
+ an invalid signal_direction, a non-margin-tier strategy_name (sized by
145
+ options_strategy.py instead), or when selection/margin-budget rounds
146
+ to zero contracts - never raises."""
147
+ spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name)
148
+ if spec is None or spec.risk_tier not in (
149
+ "margin_naked", "margin_uncovered_leg", "margin_bounded_backspread",
150
+ ):
151
+ return None
152
+
153
+ confidence = max(0.0, min(float(confidence), 1.0))
154
+ portfolio_value = max(float(portfolio_value), 0.0)
155
+ underlying_price = max(float(underlying_price), 0.0)
156
+ if confidence == 0.0 or portfolio_value <= 0.0 or underlying_price <= 0.0:
157
+ return None
158
+ if signal_direction not in ("buy", "sell", "short"):
159
+ return None
160
+
161
+ target_delta = target_delta_at_full_confidence * confidence
162
+ legs_by_role = select_strategy_legs(strategy_name, available_chain, target_delta, **selector_tuning_kwargs)
163
+ if legs_by_role is None:
164
+ return None
165
+
166
+ if spec.risk_tier == "margin_naked":
167
+ margin_per_unit = _naked_margin_requirement_for_naked_tier(
168
+ spec, legs_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value,
169
+ )
170
+ reason = "reg_t_style_naked_margin_sizing"
171
+ elif spec.risk_tier == "margin_uncovered_leg":
172
+ margin_per_unit = _uncovered_leg_margin_requirement(
173
+ spec, legs_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value,
174
+ )
175
+ reason = "uncovered_ladder_leg_margin_sizing"
176
+ else:
177
+ margin_per_unit = _bounded_backspread_max_loss(spec, legs_by_role, contract_multiplier)
178
+ reason = "bounded_max_loss_backspread_margin_sizing"
179
+
180
+ contracts = _contracts_from_margin_budget(
181
+ margin_per_unit, confidence, portfolio_value, target_margin_utilization, max_margin_utilization,
182
+ )
183
+ if contracts <= 0:
184
+ return None
185
+
186
+ margin_required = contracts * margin_per_unit
187
+ return MarginSizingDecision(
188
+ strategy_name=strategy_name,
189
+ legs=_legs_tuple_from_roles(spec, legs_by_role),
190
+ expiries=_expiries_tuple_from_roles(spec, legs_by_role),
191
+ contracts=contracts,
192
+ margin_required=margin_required,
193
+ margin_utilization=margin_required / portfolio_value,
194
+ sizing_reason=reason,
195
+ )
196
+
197
+
198
+ def build_margin_position_sizing_for_legs(
199
+ strategy_name: str,
200
+ held_rows_by_role: dict[str, dict],
201
+ underlying_price: float,
202
+ portfolio_value: float,
203
+ contract_multiplier: float = 100.0,
204
+ max_margin_utilization: float = 0.40,
205
+ pct_of_underlying_value: float = 0.20,
206
+ min_pct_of_underlying_value: float = 0.10,
207
+ ) -> MarginSizingDecision | None:
208
+ """Resize-in-place sibling of build_margin_position_sizing() - sizes
209
+ an ALREADY-HELD margin-tier position on its legs' own current chain
210
+ rows, skipping selection entirely (held_rows_by_role must carry an
211
+ entry for every role in MULTI_LEG_STRATEGY_REGISTRY[strategy_name].legs,
212
+ same shape select_strategy_legs() returns). No confidence-scaled soft
213
+ target here - the position already exists, so sizing is to the full
214
+ max_margin_utilization ceiling directly, the same "size to budget on
215
+ already-resolved greeks, no fresh confidence input" convention
216
+ options_strategy.py's build_multi_leg_position_sizing_for_legs() and
217
+ build_options_position_sizing_for_contract() already use."""
218
+ spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name)
219
+ if spec is None or spec.risk_tier not in (
220
+ "margin_naked", "margin_uncovered_leg", "margin_bounded_backspread",
221
+ ):
222
+ return None
223
+ portfolio_value = max(float(portfolio_value), 0.0)
224
+ underlying_price = max(float(underlying_price), 0.0)
225
+ if portfolio_value <= 0.0 or underlying_price <= 0.0:
226
+ return None
227
+
228
+ if spec.risk_tier == "margin_naked":
229
+ margin_per_unit = _naked_margin_requirement_for_naked_tier(
230
+ spec, held_rows_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value,
231
+ )
232
+ reason = "held_legs_own_greeks_naked_margin_sizing"
233
+ elif spec.risk_tier == "margin_uncovered_leg":
234
+ margin_per_unit = _uncovered_leg_margin_requirement(
235
+ spec, held_rows_by_role, underlying_price, contract_multiplier, pct_of_underlying_value, min_pct_of_underlying_value,
236
+ )
237
+ reason = "held_legs_own_greeks_uncovered_leg_margin_sizing"
238
+ else:
239
+ margin_per_unit = _bounded_backspread_max_loss(spec, held_rows_by_role, contract_multiplier)
240
+ reason = "held_legs_own_greeks_bounded_backspread_margin_sizing"
241
+
242
+ if margin_per_unit <= 0.0:
243
+ return None
244
+ contracts = int(portfolio_value * max_margin_utilization // margin_per_unit)
245
+ if contracts <= 0:
246
+ return None
247
+
248
+ margin_required = contracts * margin_per_unit
249
+ return MarginSizingDecision(
250
+ strategy_name=strategy_name,
251
+ legs=_legs_tuple_from_roles(spec, held_rows_by_role),
252
+ expiries=_expiries_tuple_from_roles(spec, held_rows_by_role),
253
+ contracts=contracts,
254
+ margin_required=margin_required,
255
+ margin_utilization=margin_required / portfolio_value,
256
+ sizing_reason=reason,
257
+ )
258
+
259
+
260
+ def _naked_margin_requirement_for_naked_tier(
261
+ spec, legs_by_role: dict, underlying_price: float, contract_multiplier: float,
262
+ pct_of_underlying_value: float, min_pct_of_underlying_value: float,
263
+ ) -> float:
264
+ """naked_call/naked_put: the single short leg's own naked margin.
265
+ short_straddle/short_strangle: the broker convention of "margin on the
266
+ greater side only" (both legs can't be assigned against the same
267
+ move) - max() of the two legs' naked margin, NOT the sum; the premium
268
+ credit from the other leg is ignored (conservative - overestimates
269
+ margin required in the direction of safety). short_call_backspread/
270
+ short_put_backspread: naked margin at the heavier-ratio (2x) SHORT
271
+ leg's strike, per SPREAD UNIT (i.e. for the 2 short contracts one
272
+ spread unit implies) - the 1 long contract's partial hedge is
273
+ deliberately ignored, the same conservative-direction simplification."""
274
+ short_legs = [leg for leg in spec.legs if leg.side == "short"]
275
+ per_leg_margins = [
276
+ _naked_margin_per_contract(
277
+ underlying_price, float(legs_by_role[leg.role]["strike"]), leg.right, contract_multiplier,
278
+ pct_of_underlying_value, min_pct_of_underlying_value,
279
+ ) * leg.ratio
280
+ for leg in short_legs
281
+ ]
282
+ if not per_leg_margins:
283
+ return 0.0
284
+ if len(short_legs) == 1:
285
+ return per_leg_margins[0]
286
+ return max(per_leg_margins)
287
+
288
+
289
+ def _uncovered_leg_margin_requirement(
290
+ spec, legs_by_role: dict, underlying_price: float, contract_multiplier: float,
291
+ pct_of_underlying_value: float, min_pct_of_underlying_value: float,
292
+ ) -> float:
293
+ """bull_call_ladder/bear_put_ladder only (risk_tier ==
294
+ "margin_uncovered_leg") - of the ladder's 3 legs (1 long + 2 short,
295
+ same ratio), exactly 1 short contract is genuinely uncovered (the
296
+ other is offset 1:1 by the long leg); naked margin applies to ONE
297
+ contract at the strike furthest from the long leg (the excess leg),
298
+ never to both short legs (that would double-count the 1:1-hedged
299
+ short)."""
300
+ long_leg = next(leg for leg in spec.legs if leg.side == "long")
301
+ short_legs = [leg for leg in spec.legs if leg.side == "short"]
302
+ long_strike = float(legs_by_role[long_leg.role]["strike"])
303
+ excess_leg = max(short_legs, key=lambda leg: abs(float(legs_by_role[leg.role]["strike"]) - long_strike))
304
+ return _naked_margin_per_contract(
305
+ underlying_price, float(legs_by_role[excess_leg.role]["strike"]), excess_leg.right, contract_multiplier,
306
+ pct_of_underlying_value, min_pct_of_underlying_value,
307
+ )
308
+
309
+
310
+ def _bounded_backspread_max_loss(spec, legs_by_role: dict, contract_multiplier: float) -> float:
311
+ """call_backspread/put_backspread only (risk_tier ==
312
+ "margin_bounded_backspread") - defined max loss per spread unit:
313
+ (strike_width - net_credit) * contract_multiplier, occurring at the
314
+ far (heavier-ratio) strike. net_credit uses bid/ask when present
315
+ (short leg's bid minus long leg's ask * ratio), 0.0 when absent (the
316
+ same "never let a missing diagnostic field gate sizing" convention as
317
+ the vega-budget path's net_debit_or_credit) - a 0.0 credit assumption
318
+ is the conservative (larger max-loss) direction."""
319
+ short_leg = next(leg for leg in spec.legs if leg.side == "short")
320
+ long_leg = next(leg for leg in spec.legs if leg.side == "long")
321
+ short_row = legs_by_role[short_leg.role]
322
+ long_row = legs_by_role[long_leg.role]
323
+ strike_width = abs(float(long_row["strike"]) - float(short_row["strike"]))
324
+
325
+ short_bid = short_row.get("bid")
326
+ long_ask = long_row.get("ask")
327
+ if short_bid is not None and long_ask is not None:
328
+ net_credit = short_leg.ratio * float(short_bid) - long_leg.ratio * float(long_ask)
329
+ else:
330
+ net_credit = 0.0
331
+
332
+ max_loss_per_unit = strike_width - net_credit
333
+ return max(max_loss_per_unit, 0.0) * contract_multiplier