Coverage for portfolio/options_arbitrage_detector.py: 100%
112 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Mispricing detector for the 6 stubbed arbitrage strategies (box_spread,
2short_box_spread, conversion, reverse_conversion, jelly_roll,
3short_jelly_roll) - V4.6 (development/Problems.md #59/Roadmap).
5These 6 strategies have had full registry entries, leg selectors, and
6unit tests since V4.5, but were never invoked from the live signal path
7by design: driving them correctly requires comparing an observed
8structure's market price against its risk-free-rate-implied FAIR value
9(a genuine arbitrage/mispricing signal), not a directional or volatility
10view like every other strategy family in this codebase. This module is
11that signal source.
13Off by default (phase_v2.options_risk.arbitrage_detector.enabled) - an
14explicit, SEPARATE opt-in from enabling these 6 names in
15enabled_strategy_names, matching every other new-capability gate in this
16project's history (ship available, default off, opt in per-item).
18Every fair-value formula here is the standard, textbook closed-form
19result for its structure - not a fitted/calibrated model - since the
20whole premise of arbitrage detection is comparing an OBSERVED price
21against a THEORETICALLY-derived one, not a statistical estimate. Ignores
22dividends (dividend_yield=0.0), matching features/options_greeks.py's
23own existing convention for this codebase.
24"""
26from __future__ import annotations
28import math
29from datetime import date
30from typing import TYPE_CHECKING, Any
32from portfolio.options_strategy import (
33 MULTI_LEG_STRATEGY_REGISTRY,
34 OptionsMultiLegPositionDecision,
35 _expiries_tuple_from_roles,
36 _legs_tuple_from_roles,
37 _net_vega_and_delta_per_unit,
38 select_strategy_legs,
39)
41if TYPE_CHECKING:
42 from collections.abc import Iterable
45def box_spread_fair_value(
46 higher_strike: float, lower_strike: float, risk_free_rate: float, time_to_expiry_years: float,
47) -> float:
48 """A box spread (long put + short call at the higher strike, short
49 put + long call at the lower strike, same expiry) synthesizes a
50 risk-free zero-coupon bond paying (higher_strike - lower_strike) at
51 expiry - its fair value today is that payoff discounted at the
52 risk-free rate. Standard textbook result."""
53 return (higher_strike - lower_strike) * math.exp(-risk_free_rate * max(time_to_expiry_years, 0.0))
56def pv_dividends_to_expiry(payments: Iterable[tuple[date, float]] | None, current_date: date, expiry_date_str: str, risk_free_rate: float) -> float:
57 """Present value of the dividends going ex after `current_date` and on or before the expiry. `payments` holds
58 (ex_date, cash_per_share) pairs. A row it can't read counts as no dividend, as the detector did before it knew of any."""
59 total = 0.0
60 for ex_date, amount in payments or ():
61 try:
62 years = _years_between(current_date, str(ex_date))
63 to_expiry = _years_between(current_date, str(expiry_date_str))
64 cash = float(amount)
65 except (TypeError, ValueError):
66 continue
67 if 0.0 < years <= to_expiry and math.isfinite(cash) and cash > 0.0:
68 total += cash * math.exp(-risk_free_rate * years)
69 return total
72def conversion_parity_value(
73 call_price: float, put_price: float, spot: float, strike: float, risk_free_rate: float, time_to_expiry_years: float,
74 pv_dividends: float = 0.0,
75) -> float:
76 """Put-call parity: call_price - put_price should equal
77 spot - pv_dividends - strike * exp(-r*T). Returns the SIGNED
78 discrepancy (actual minus theoretical). A conversion (long stock, long
79 put, short call) locks in call - put - spot + PV(strike) + PV(dividends), which is this
80 discrepancy, so it profits when it is positive (calls rich against
81 puts); a reverse conversion profits when it is negative. Without
82 `pv_dividends`, a dividend payer's calls read cheap: a reverse conversion is short the
83 stock and owes each dividend, which is why it fired on AAPL at fair prices."""
84 theoretical = spot - pv_dividends - strike * math.exp(-risk_free_rate * max(time_to_expiry_years, 0.0))
85 actual = call_price - put_price
86 return actual - theoretical
89def jelly_roll_fair_value(
90 strike: float, risk_free_rate: float, near_time_to_expiry_years: float, far_time_to_expiry_years: float,
91) -> float:
92 """The interest-rate-implied fair cost of a jelly roll (rolling a
93 synthetic position from the near expiry to the far one) - the
94 discounted strike difference between the two expiries, the standard
95 cost-of-carry result for extending a synthetic forward's expiry."""
96 near_discount = math.exp(-risk_free_rate * max(near_time_to_expiry_years, 0.0))
97 far_discount = math.exp(-risk_free_rate * max(far_time_to_expiry_years, 0.0))
98 return strike * (near_discount - far_discount)
101def detect_mispricing(actual_net_cost: float, fair_value: float, min_mispricing_bps: float, notional: float) -> bool:
102 """Shared threshold predicate for all 3 families above: True when the
103 discrepancy between actual_net_cost and fair_value exceeds
104 min_mispricing_bps of notional - requiring a MINIMUM edge (not a bare
105 non-zero difference) accounts for real bid/ask spread and transaction
106 costs a genuine arbitrage must clear to be worth trading. Returns
107 False (never trades, never raises) when notional is non-positive."""
108 if notional <= 0.0:
109 return False
110 mispricing_bps = abs(actual_net_cost - fair_value) / notional * 10_000.0
111 return mispricing_bps >= min_mispricing_bps
114def detect_executable_edge(edge: float, min_mispricing_bps: float, notional: float) -> bool:
115 """True when entering the structure at executable prices beats its fair value by at least the threshold. One-sided: a
116 structure priced dear is no arbitrage for the side that would pay up, and only its opposite may fire."""
117 if notional <= 0.0:
118 return False
119 return edge / notional * 10_000.0 >= min_mispricing_bps
122def _years_between(current_date, expiry_date_str: str) -> float:
123 """ISO-date-string expiry minus current_date, in years (365-day
124 convention, matching main.py::_build_options_chains_payload()'s own
125 time_to_expiry_years computation for greeks). Returns 0.0 (never
126 negative, never raises) for an unparseable/past expiry."""
127 try:
128 expiry_date = date.fromisoformat(expiry_date_str)
129 except (TypeError, ValueError):
130 return 0.0
131 return max((expiry_date - current_date).days, 0) / 365.0
134def _actual_net_cost(spec, legs_by_role: dict[str, Any]) -> float:
135 """Signed cost to enter the FULL spread unit at current market
136 bid/ask: pay ask for every LONG leg, receive bid for every SHORT leg
137 - read from each leg's own `.side` (registry-driven), never hardcoded
138 per strategy_name, since box_spread/short_box_spread and jelly_roll/
139 short_jelly_roll invert which role is long vs. short while keeping
140 the SAME role names (see MULTI_LEG_STRATEGY_REGISTRY's own docstring)
141 - the exact bug this generic formula avoids versus hand-writing one
142 signed formula per strategy_name."""
143 net_cost = 0.0
144 for leg_spec in spec.legs:
145 row = legs_by_role[leg_spec.role]
146 price = float(row["ask"]) if leg_spec.side == "long" else float(row["bid"])
147 sign = 1.0 if leg_spec.side == "long" else -1.0
148 net_cost += sign * price
149 return net_cost
152def select_arbitrage_signal(
153 strategy_name: str,
154 available_chain: list[dict],
155 current_date: date,
156 risk_free_rate: float,
157 min_mispricing_bps: float,
158 target_delta: float = 0.5,
159 dividend_payments: Iterable[tuple[date, float]] | None=None,
160) -> bool:
161 """Composes the existing V4.5 arbitrage leg selectors
162 (select_strategy_legs(), already registry-driven) with the fair-value/
163 threshold functions above: True iff THIS bar's chain shows an
164 exploitable mispricing for strategy_name, using each leg's own
165 bid/ask and days-to-expiry. Strike/expiry ROLES (which role is
166 "higher"/"lower"/"near"/"far") are resolved from
167 MULTI_LEG_STRATEGY_REGISTRY, never hardcoded per strategy_name - the
168 short_* variants invert which role holds which strike/side while
169 keeping the same role NAMES. Returns False (never a crash) on any
170 missing selection/pricing/date data, or for any strategy_name outside
171 the 6 arbitrage families - degrade-to-absent, matching every other
172 selector's convention in this module's sibling file."""
173 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name)
174 if spec is None or current_date is None:
175 return False
176 legs_by_role = select_strategy_legs(strategy_name, available_chain, target_delta)
177 if legs_by_role is None:
178 return False
180 try:
181 if strategy_name in ("box_spread", "short_box_spread"):
182 higher_role = next(leg.role for leg in spec.legs if leg.strike_role == "higher")
183 lower_role = next(leg.role for leg in spec.legs if leg.strike_role == "lower")
184 higher_row = legs_by_role[higher_role]
185 lower_row = legs_by_role[lower_role]
186 higher_strike = float(higher_row["strike"])
187 lower_strike = float(lower_row["strike"])
188 time_to_expiry_years = _years_between(current_date, higher_row["expiry"])
189 fair_value = box_spread_fair_value(higher_strike, lower_strike, risk_free_rate, time_to_expiry_years)
190 actual_net_cost = _actual_net_cost(spec, legs_by_role)
191 # long: pay the cost, collect the discounted payoff. short: the cost is a credit, and the payoff is owed.
192 edge = fair_value - actual_net_cost if strategy_name == "box_spread" else -actual_net_cost - fair_value
193 return detect_executable_edge(edge, min_mispricing_bps, higher_strike - lower_strike)
195 if strategy_name in ("conversion", "reverse_conversion"):
196 call_role = next(leg.role for leg in spec.legs if leg.right == "call")
197 put_role = next(leg.role for leg in spec.legs if leg.right == "put")
198 call_row = legs_by_role[call_role]
199 put_row = legs_by_role[put_role]
200 strike = float(call_row["strike"])
201 spot = float(call_row.get("underlying_price") or strike)
202 time_to_expiry_years = _years_between(current_date, call_row["expiry"])
203 # at the prices one could trade: a conversion sells the call and buys the put, a reverse does the opposite
204 if strategy_name == "conversion":
205 call_price, put_price, sign = float(call_row["bid"]), float(put_row["ask"]), 1.0
206 else:
207 call_price, put_price, sign = float(call_row["ask"]), float(put_row["bid"]), -1.0
208 pv_dividends = pv_dividends_to_expiry(dividend_payments, current_date, call_row["expiry"], risk_free_rate)
209 discrepancy = conversion_parity_value(call_price, put_price, spot, strike, risk_free_rate, time_to_expiry_years, pv_dividends)
210 return detect_executable_edge(sign * discrepancy, min_mispricing_bps, strike)
212 if strategy_name in ("jelly_roll", "short_jelly_roll"):
213 near_call_role = next(leg.role for leg in spec.legs if leg.right == "call" and leg.expiry_role == "near")
214 far_call_role = next(leg.role for leg in spec.legs if leg.right == "call" and leg.expiry_role == "far")
215 near_row = legs_by_role[near_call_role]
216 far_row = legs_by_role[far_call_role]
217 strike = float(near_row["strike"])
218 near_time_to_expiry_years = _years_between(current_date, near_row["expiry"])
219 far_time_to_expiry_years = _years_between(current_date, far_row["expiry"])
220 fair_value = jelly_roll_fair_value(strike, risk_free_rate, near_time_to_expiry_years, far_time_to_expiry_years)
221 actual_net_cost = _actual_net_cost(spec, legs_by_role)
222 edge = fair_value - actual_net_cost if strategy_name == "jelly_roll" else -actual_net_cost - fair_value
223 return detect_executable_edge(edge, min_mispricing_bps, strike)
224 except (KeyError, TypeError, ValueError):
225 return False
227 return False
230def build_arbitrage_position_sizing(
231 strategy_name: str,
232 available_chain: list[dict],
233 current_date: date,
234 risk_free_rate: float,
235 min_mispricing_bps: float,
236 max_contracts_per_signal: int = 1,
237 target_delta: float = 0.5,
238) -> OptionsMultiLegPositionDecision | None:
239 """The ONLY sizing path for the 6 arbitrage strategies - deliberately
240 NOT vega-budget or margin-tier sized (an arbitrage structure is
241 delta/vega-neutral by construction, so a vega budget has nothing
242 meaningful to scale against). Sized instead to a small, FIXED
243 `max_contracts_per_signal` (default 1) whenever
244 select_arbitrage_signal() confirms a real mispricing this bar - a
245 deliberately conservative first-cut sizing model for a genuinely new
246 capability, not a risk-budgeted one; a real margin-aware arbitrage
247 sizer is a reasonable future follow-up once this is IB-verified.
248 Returns None when no mispricing is detected, selection fails, or
249 max_contracts_per_signal isn't positive - never raises."""
250 if max_contracts_per_signal <= 0:
251 return None
252 if not select_arbitrage_signal(strategy_name, available_chain, current_date, risk_free_rate, min_mispricing_bps, target_delta):
253 return None
254 spec = MULTI_LEG_STRATEGY_REGISTRY.get(strategy_name)
255 if spec is None:
256 return None
257 legs_by_role = select_strategy_legs(strategy_name, available_chain, target_delta)
258 if legs_by_role is None:
259 return None
261 net_vega, net_delta = _net_vega_and_delta_per_unit(spec, legs_by_role)
262 return OptionsMultiLegPositionDecision(
263 strategy_name=strategy_name,
264 legs=_legs_tuple_from_roles(spec, legs_by_role),
265 expiries=_expiries_tuple_from_roles(spec, legs_by_role),
266 contracts=int(max_contracts_per_signal),
267 net_debit_or_credit=_actual_net_cost(spec, legs_by_role),
268 net_delta=net_delta,
269 net_vega=net_vega,
270 sizing_reason="arbitrage_mispricing_fixed_size_sizing",
271 )