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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
DataFetcher — 4-source fallback chain for SPX options chain data.
|
| 3 |
+
|
| 4 |
+
Priority: IBKR → Tastytrade → CBOE → Yahoo Finance → Stale Cache → Demo
|
| 5 |
+
Each source normalizes output to the same internal strike-record format.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import logging
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
from datetime import date
|
| 11 |
+
from typing import Optional
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
# Internal strike record schema:
|
| 18 |
+
# {
|
| 19 |
+
# strike: float, expiry: "YYYY-MM-DD",
|
| 20 |
+
# oi_call: int, oi_put: int,
|
| 21 |
+
# iv_call: float, iv_put: float, # annualized implied vol
|
| 22 |
+
# delta_call: float, gamma_call: float,
|
| 23 |
+
# delta_put: float, gamma_put: float,
|
| 24 |
+
# vanna_call: float, vanna_put: float # dDelta/dIV
|
| 25 |
+
# }
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class SourceResult:
|
| 30 |
+
source: str
|
| 31 |
+
spot: float
|
| 32 |
+
strikes: list[dict] = field(default_factory=list)
|
| 33 |
+
expiry_primary: str = ""
|
| 34 |
+
dte: int = 0
|
| 35 |
+
oi_total: int = 0
|
| 36 |
+
stale: bool = False
|
| 37 |
+
error: Optional[str] = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DataFetcher:
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
ibkr_host: str = "127.0.0.1",
|
| 44 |
+
ibkr_port: int = 7497,
|
| 45 |
+
tt_token: Optional[str] = None,
|
| 46 |
+
spot_pct_filter: float = 0.08, # only include strikes within ±8% of spot
|
| 47 |
+
):
|
| 48 |
+
self.ibkr_host = ibkr_host
|
| 49 |
+
self.ibkr_port = ibkr_port
|
| 50 |
+
self.tt_token = tt_token
|
| 51 |
+
self.spot_pct_filter = spot_pct_filter
|
| 52 |
+
self._last_result: Optional[SourceResult] = None
|
| 53 |
+
|
| 54 |
+
def fetch_options_chain(self, symbol: str = "SPX") -> SourceResult:
|
| 55 |
+
for source_fn in [
|
| 56 |
+
self._fetch_ibkr,
|
| 57 |
+
self._fetch_tastytrade,
|
| 58 |
+
self._fetch_cboe,
|
| 59 |
+
self._fetch_yahoo,
|
| 60 |
+
]:
|
| 61 |
+
try:
|
| 62 |
+
result = source_fn(symbol)
|
| 63 |
+
if result and result.strikes:
|
| 64 |
+
logger.info(f"Data fetched from {result.source} ({len(result.strikes)} strikes)")
|
| 65 |
+
self._last_result = result
|
| 66 |
+
return result
|
| 67 |
+
except Exception as e:
|
| 68 |
+
logger.warning(f"{source_fn.__name__} failed: {e}")
|
| 69 |
+
|
| 70 |
+
if self._last_result:
|
| 71 |
+
logger.warning("All live sources failed — returning stale cache data")
|
| 72 |
+
self._last_result.stale = True
|
| 73 |
+
return self._last_result
|
| 74 |
+
|
| 75 |
+
logger.warning("No live data and no cache — using synthetic demo data")
|
| 76 |
+
return self._synthetic_demo(symbol)
|
| 77 |
+
|
| 78 |
+
# ------------------------------------------------------------------
|
| 79 |
+
# IBKR via ib_insync
|
| 80 |
+
# ib_insync requires an asyncio event loop. Flask worker threads
|
| 81 |
+
# don't have one, so we run the entire operation in a dedicated
|
| 82 |
+
# thread where we set up a fresh event loop first.
|
| 83 |
+
# Requires: TWS or IB Gateway on ibkr_host:ibkr_port, API enabled
|
| 84 |
+
# ------------------------------------------------------------------
|
| 85 |
+
def _fetch_ibkr(self, symbol: str) -> SourceResult:
|
| 86 |
+
import asyncio
|
| 87 |
+
import random
|
| 88 |
+
import threading
|
| 89 |
+
|
| 90 |
+
result: list = [None]
|
| 91 |
+
exc: list = [None]
|
| 92 |
+
|
| 93 |
+
host = self.ibkr_host
|
| 94 |
+
port = self.ibkr_port
|
| 95 |
+
pct = self.spot_pct_filter
|
| 96 |
+
nearest_expiry = self._nearest_expiry_raw
|
| 97 |
+
|
| 98 |
+
def _run():
|
| 99 |
+
# Set event loop BEFORE importing ib_insync — its module-level
|
| 100 |
+
# code accesses asyncio.get_event_loop() at import time.
|
| 101 |
+
import math
|
| 102 |
+
loop = asyncio.new_event_loop()
|
| 103 |
+
asyncio.set_event_loop(loop)
|
| 104 |
+
from ib_insync import IB, Index, Option # import after loop is set
|
| 105 |
+
|
| 106 |
+
client_id = random.randint(200, 299)
|
| 107 |
+
ib = IB()
|
| 108 |
+
try:
|
| 109 |
+
ib.connect(host, port, clientId=client_id, timeout=6, readonly=True)
|
| 110 |
+
|
| 111 |
+
# 1. SPX spot price via reqHistoricalData (last 2 daily bars).
|
| 112 |
+
# This is more reliable than the CLOSE tick, which on weekends
|
| 113 |
+
# returns T-1 (day before the most recent close) for indices.
|
| 114 |
+
spx = Index("SPX", "CBOE")
|
| 115 |
+
ib.qualifyContracts(spx)
|
| 116 |
+
hist_bars = ib.reqHistoricalData(
|
| 117 |
+
spx, endDateTime="", durationStr="2 D",
|
| 118 |
+
barSizeSetting="1 day", whatToShow="TRADES",
|
| 119 |
+
useRTH=True, formatDate=1,
|
| 120 |
+
)
|
| 121 |
+
if hist_bars:
|
| 122 |
+
spot = float(hist_bars[-1].close)
|
| 123 |
+
else:
|
| 124 |
+
# Fallback: streaming tick (may be T-1 on weekends)
|
| 125 |
+
spx_ticker = ib.reqMktData(spx, "", snapshot=False)
|
| 126 |
+
ib.sleep(3)
|
| 127 |
+
raw_spot = next(
|
| 128 |
+
(v for v in (spx_ticker.last, spx_ticker.close, spx_ticker.bid)
|
| 129 |
+
if v is not None and not math.isnan(v) and v > 0),
|
| 130 |
+
None,
|
| 131 |
+
)
|
| 132 |
+
ib.cancelMktData(spx)
|
| 133 |
+
if raw_spot is None:
|
| 134 |
+
raise ValueError("IBKR: SPX spot price not available")
|
| 135 |
+
spot = float(raw_spot)
|
| 136 |
+
|
| 137 |
+
# 2. Option chain params — must pass the actual conId (not 0)
|
| 138 |
+
chains = ib.reqSecDefOptParams("SPX", "", "IND", spx.conId)
|
| 139 |
+
# SPX index options trade on CBOE; equity options use SMART
|
| 140 |
+
smart = (
|
| 141 |
+
next((c for c in chains if c.exchange == "SMART"), None)
|
| 142 |
+
or next((c for c in chains if c.exchange == "CBOE"), None)
|
| 143 |
+
or next((c for c in chains if c.expirations and c.strikes), None)
|
| 144 |
+
)
|
| 145 |
+
if not smart:
|
| 146 |
+
raise ValueError(f"No option params from IBKR (exchanges: {[c.exchange for c in chains]})")
|
| 147 |
+
|
| 148 |
+
expiry_raw = nearest_expiry(list(smart.expirations))
|
| 149 |
+
expiry_str = f"{expiry_raw[:4]}-{expiry_raw[4:6]}-{expiry_raw[6:]}"
|
| 150 |
+
dte = (date.fromisoformat(expiry_str) - date.today()).days
|
| 151 |
+
|
| 152 |
+
# 3. Use reqContractDetails to get all VALID call contracts for
|
| 153 |
+
# the specific expiry — returns exactly the strikes that exist,
|
| 154 |
+
# with conId populated (needed for reqMktData).
|
| 155 |
+
# We probe with SPXW; if empty, fall back to SPX trading class.
|
| 156 |
+
for tc in ("SPXW", "SPX"):
|
| 157 |
+
template = Option("SPX", expiry_raw, 0, "C", "CBOE",
|
| 158 |
+
currency="USD", multiplier="100",
|
| 159 |
+
tradingClass=tc)
|
| 160 |
+
call_details = ib.reqContractDetails(template)
|
| 161 |
+
if call_details:
|
| 162 |
+
trading_class = tc
|
| 163 |
+
break
|
| 164 |
+
else:
|
| 165 |
+
raise ValueError("No contract details returned for SPX options")
|
| 166 |
+
|
| 167 |
+
# Filter by spot range
|
| 168 |
+
call_contracts = [
|
| 169 |
+
cd.contract for cd in call_details
|
| 170 |
+
if abs(cd.contract.strike - spot) / spot <= pct
|
| 171 |
+
]
|
| 172 |
+
if not call_contracts:
|
| 173 |
+
raise ValueError(f"No SPX option contracts in ±{pct:.0%} range of {spot:.0f}")
|
| 174 |
+
|
| 175 |
+
# Build matching put contracts (same strikes, fully specified)
|
| 176 |
+
put_contracts = [
|
| 177 |
+
Option("SPX", expiry_raw, c.strike, "P", "CBOE",
|
| 178 |
+
currency="USD", multiplier="100",
|
| 179 |
+
tradingClass=trading_class)
|
| 180 |
+
for c in call_contracts
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
# 4. Stream calls, then puts sequentially — TWS limits simultaneous
|
| 184 |
+
# streaming tickers to ~100; ±8% filter yields ~65 strikes per side,
|
| 185 |
+
# so each batch is safely under the limit.
|
| 186 |
+
# Generic tick "101" (OI) requires streaming, not snapshot.
|
| 187 |
+
records: dict[float, dict] = {}
|
| 188 |
+
|
| 189 |
+
for side_contracts in (call_contracts, put_contracts):
|
| 190 |
+
side_tickers = {
|
| 191 |
+
(float(c.strike), c.right): ib.reqMktData(c, "101", False, False)
|
| 192 |
+
for c in side_contracts
|
| 193 |
+
}
|
| 194 |
+
ib.sleep(6) # allow Greeks + OI ticks to populate
|
| 195 |
+
for c in side_contracts:
|
| 196 |
+
k = float(c.strike)
|
| 197 |
+
right = c.right
|
| 198 |
+
tk = side_tickers[(k, right)]
|
| 199 |
+
ib.cancelMktData(c)
|
| 200 |
+
|
| 201 |
+
if k not in records:
|
| 202 |
+
records[k] = _empty_record(k, expiry_str)
|
| 203 |
+
r = records[k]
|
| 204 |
+
|
| 205 |
+
greeks = tk.modelGreeks
|
| 206 |
+
iv = greeks.impliedVol if greeks else None
|
| 207 |
+
delta = greeks.delta if greeks else None
|
| 208 |
+
gamma = greeks.gamma if greeks else None
|
| 209 |
+
|
| 210 |
+
if right == "C":
|
| 211 |
+
if iv and 0 < iv < 5:
|
| 212 |
+
r["iv_call"] = iv
|
| 213 |
+
if delta is not None and abs(delta) <= 1:
|
| 214 |
+
r["delta_call"] = delta
|
| 215 |
+
if gamma is not None and gamma > 0:
|
| 216 |
+
r["gamma_call"] = gamma
|
| 217 |
+
oi_raw = tk.callOpenInterest
|
| 218 |
+
r["oi_call"] = 0 if (oi_raw is None or math.isnan(oi_raw)) else int(oi_raw)
|
| 219 |
+
else:
|
| 220 |
+
if iv and 0 < iv < 5:
|
| 221 |
+
r["iv_put"] = iv
|
| 222 |
+
if delta is not None and abs(delta) <= 1:
|
| 223 |
+
r["delta_put"] = delta
|
| 224 |
+
if gamma is not None and gamma > 0:
|
| 225 |
+
r["gamma_put"] = gamma
|
| 226 |
+
oi_raw = tk.putOpenInterest
|
| 227 |
+
r["oi_put"] = 0 if (oi_raw is None or math.isnan(oi_raw)) else int(oi_raw)
|
| 228 |
+
|
| 229 |
+
result[0] = (spot, expiry_str, dte, records)
|
| 230 |
+
|
| 231 |
+
except Exception as e:
|
| 232 |
+
exc[0] = e
|
| 233 |
+
finally:
|
| 234 |
+
try:
|
| 235 |
+
ib.disconnect()
|
| 236 |
+
except Exception:
|
| 237 |
+
pass
|
| 238 |
+
loop.close()
|
| 239 |
+
|
| 240 |
+
t = threading.Thread(target=_run, daemon=True)
|
| 241 |
+
t.start()
|
| 242 |
+
t.join(timeout=60)
|
| 243 |
+
|
| 244 |
+
if exc[0] is not None:
|
| 245 |
+
raise exc[0]
|
| 246 |
+
if result[0] is None:
|
| 247 |
+
raise TimeoutError(f"IBKR fetch thread timed out after 60s")
|
| 248 |
+
|
| 249 |
+
spot, expiry_str, dte, records = result[0]
|
| 250 |
+
strikes_list = list(records.values())
|
| 251 |
+
_add_vanna(strikes_list)
|
| 252 |
+
return SourceResult(
|
| 253 |
+
source="ibkr", spot=spot, strikes=strikes_list,
|
| 254 |
+
expiry_primary=expiry_str, dte=dte,
|
| 255 |
+
oi_total=sum(s["oi_call"] + s["oi_put"] for s in strikes_list),
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# ------------------------------------------------------------------
|
| 259 |
+
# Tastytrade REST API
|
| 260 |
+
# Requires: CRASH_MONITOR_TT_TOKEN env var
|
| 261 |
+
# ------------------------------------------------------------------
|
| 262 |
+
def _fetch_tastytrade(self, symbol: str) -> SourceResult:
|
| 263 |
+
if not self.tt_token:
|
| 264 |
+
raise ValueError("CRASH_MONITOR_TT_TOKEN not configured")
|
| 265 |
+
|
| 266 |
+
import tastytrade
|
| 267 |
+
from tastytrade.instruments import NestedOptionChain
|
| 268 |
+
|
| 269 |
+
session = tastytrade.Session(remember_token=self.tt_token)
|
| 270 |
+
chain = NestedOptionChain.get_chain(session, "SPXW")
|
| 271 |
+
|
| 272 |
+
# SPX spot approximation via SPY × 10
|
| 273 |
+
spy = tastytrade.instruments.Equity.get_equity(session, "SPY")
|
| 274 |
+
spot = float(spy.bid_price) * 10
|
| 275 |
+
|
| 276 |
+
expiry_obj = min(chain.expirations, key=lambda e: abs(e.days_to_expiration - 35))
|
| 277 |
+
expiry_str = expiry_obj.expiration_date.isoformat()
|
| 278 |
+
dte = expiry_obj.days_to_expiration
|
| 279 |
+
|
| 280 |
+
strikes_list = []
|
| 281 |
+
for strike_obj in expiry_obj.strikes:
|
| 282 |
+
k = float(strike_obj.strike_price)
|
| 283 |
+
if abs(k - spot) / spot > self.spot_pct_filter:
|
| 284 |
+
continue
|
| 285 |
+
r = _empty_record(k, expiry_str)
|
| 286 |
+
strikes_list.append(r)
|
| 287 |
+
|
| 288 |
+
_add_vanna(strikes_list)
|
| 289 |
+
return SourceResult(
|
| 290 |
+
source="tastytrade", spot=spot, strikes=strikes_list,
|
| 291 |
+
expiry_primary=expiry_str, dte=dte,
|
| 292 |
+
oi_total=sum(s["oi_call"] + s["oi_put"] for s in strikes_list),
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
# ------------------------------------------------------------------
|
| 296 |
+
# CBOE delayed JSON feed (no auth required)
|
| 297 |
+
# ------------------------------------------------------------------
|
| 298 |
+
def _fetch_cboe(self, symbol: str) -> SourceResult:
|
| 299 |
+
import requests
|
| 300 |
+
|
| 301 |
+
url = "https://cdn.cboe.com/api/global/delayed_quotes/options/SPX.json"
|
| 302 |
+
r = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
|
| 303 |
+
r.raise_for_status()
|
| 304 |
+
data = r.json()
|
| 305 |
+
|
| 306 |
+
spot = float(data["data"]["current_price"])
|
| 307 |
+
options = data["data"]["options"]
|
| 308 |
+
|
| 309 |
+
expiry_dates = sorted({o["expiration"] for o in options})
|
| 310 |
+
target_expiry = min(
|
| 311 |
+
expiry_dates,
|
| 312 |
+
key=lambda e: abs((date.fromisoformat(e) - date.today()).days - 35),
|
| 313 |
+
)
|
| 314 |
+
dte = (date.fromisoformat(target_expiry) - date.today()).days
|
| 315 |
+
|
| 316 |
+
records: dict[float, dict] = {}
|
| 317 |
+
for o in options:
|
| 318 |
+
if o["expiration"] != target_expiry:
|
| 319 |
+
continue
|
| 320 |
+
k = float(o["strike"])
|
| 321 |
+
if abs(k - spot) / spot > self.spot_pct_filter:
|
| 322 |
+
continue
|
| 323 |
+
if k not in records:
|
| 324 |
+
records[k] = _empty_record(k, target_expiry)
|
| 325 |
+
r = records[k]
|
| 326 |
+
if o["option_type"] == "C":
|
| 327 |
+
r["oi_call"] = int(o.get("open_interest", 0))
|
| 328 |
+
r["iv_call"] = float(o.get("iv", 0.18))
|
| 329 |
+
r["delta_call"] = float(o.get("delta", 0.5))
|
| 330 |
+
r["gamma_call"] = float(o.get("gamma", 0.002))
|
| 331 |
+
else:
|
| 332 |
+
r["oi_put"] = int(o.get("open_interest", 0))
|
| 333 |
+
r["iv_put"] = float(o.get("iv", 0.19))
|
| 334 |
+
r["delta_put"] = float(o.get("delta", -0.5))
|
| 335 |
+
r["gamma_put"] = float(o.get("gamma", 0.002))
|
| 336 |
+
|
| 337 |
+
strikes_list = list(records.values())
|
| 338 |
+
_add_vanna(strikes_list)
|
| 339 |
+
return SourceResult(
|
| 340 |
+
source="cboe", spot=spot, strikes=strikes_list,
|
| 341 |
+
expiry_primary=target_expiry, dte=dte,
|
| 342 |
+
oi_total=sum(s["oi_call"] + s["oi_put"] for s in strikes_list),
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
# ------------------------------------------------------------------
|
| 346 |
+
# Yahoo Finance (via yfinance library)
|
| 347 |
+
# ------------------------------------------------------------------
|
| 348 |
+
def _fetch_yahoo(self, symbol: str) -> SourceResult:
|
| 349 |
+
import yfinance as yf
|
| 350 |
+
|
| 351 |
+
spot_info = yf.Ticker("^GSPC").fast_info
|
| 352 |
+
spot = float(spot_info.get("last_price", 6632.0))
|
| 353 |
+
|
| 354 |
+
ticker = yf.Ticker("^SPXW")
|
| 355 |
+
expirations = ticker.options
|
| 356 |
+
if not expirations:
|
| 357 |
+
raise ValueError("Yahoo returned no option expirations")
|
| 358 |
+
|
| 359 |
+
target_expiry = min(
|
| 360 |
+
expirations,
|
| 361 |
+
key=lambda e: abs((date.fromisoformat(e) - date.today()).days - 35),
|
| 362 |
+
)
|
| 363 |
+
dte = (date.fromisoformat(target_expiry) - date.today()).days
|
| 364 |
+
chain = ticker.option_chain(target_expiry)
|
| 365 |
+
|
| 366 |
+
records: dict[float, dict] = {}
|
| 367 |
+
for _, row in chain.calls.iterrows():
|
| 368 |
+
k = float(row["strike"])
|
| 369 |
+
if abs(k - spot) / spot > self.spot_pct_filter:
|
| 370 |
+
continue
|
| 371 |
+
if k not in records:
|
| 372 |
+
records[k] = _empty_record(k, target_expiry)
|
| 373 |
+
records[k]["oi_call"] = int(row.get("openInterest", 0))
|
| 374 |
+
records[k]["iv_call"] = float(row.get("impliedVolatility", 0.18))
|
| 375 |
+
|
| 376 |
+
for _, row in chain.puts.iterrows():
|
| 377 |
+
k = float(row["strike"])
|
| 378 |
+
if k in records:
|
| 379 |
+
records[k]["oi_put"] = int(row.get("openInterest", 0))
|
| 380 |
+
records[k]["iv_put"] = float(row.get("impliedVolatility", 0.19))
|
| 381 |
+
|
| 382 |
+
strikes_list = list(records.values())
|
| 383 |
+
_add_vanna(strikes_list)
|
| 384 |
+
return SourceResult(
|
| 385 |
+
source="yahoo", spot=spot, strikes=strikes_list,
|
| 386 |
+
expiry_primary=target_expiry, dte=dte,
|
| 387 |
+
oi_total=sum(s["oi_call"] + s["oi_put"] for s in strikes_list),
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# ------------------------------------------------------------------
|
| 391 |
+
# Synthetic demo (offline / no credentials)
|
| 392 |
+
# ------------------------------------------------------------------
|
| 393 |
+
def _synthetic_demo(self, symbol: str) -> SourceResult:
|
| 394 |
+
"""Realistic synthetic SPX data for offline/demo use."""
|
| 395 |
+
spot = 6632.19
|
| 396 |
+
rng = np.random.default_rng(42)
|
| 397 |
+
strikes = []
|
| 398 |
+
for k in np.arange(5800, 7400, 25):
|
| 399 |
+
atm_dist = (k - spot) / spot
|
| 400 |
+
iv_call = max(0.05, 0.18 + abs(atm_dist) * 0.3 - atm_dist * 0.05)
|
| 401 |
+
iv_put = max(0.05, iv_call + 0.01 + max(0.0, -atm_dist * 0.08))
|
| 402 |
+
gamma = float(0.003 * np.exp(-50 * atm_dist ** 2))
|
| 403 |
+
delta_call = float(np.clip(0.5 - atm_dist * 2.5, 0.01, 0.99))
|
| 404 |
+
strikes.append({
|
| 405 |
+
"strike": float(k),
|
| 406 |
+
"expiry": "2026-04-17",
|
| 407 |
+
"oi_call": int(abs(rng.normal(8000, 3000))),
|
| 408 |
+
"oi_put": int(abs(rng.normal(10000, 4000))),
|
| 409 |
+
"iv_call": round(iv_call, 4),
|
| 410 |
+
"iv_put": round(iv_put, 4),
|
| 411 |
+
"delta_call": round(delta_call, 4),
|
| 412 |
+
"gamma_call": round(gamma, 6),
|
| 413 |
+
"delta_put": round(delta_call - 1.0, 4),
|
| 414 |
+
"gamma_put": round(gamma, 6),
|
| 415 |
+
"vanna_call": round(delta_call * (1 - delta_call) / max(iv_call, 0.01), 4),
|
| 416 |
+
"vanna_put": round(abs(delta_call - 1) * (1 - abs(delta_call - 1)) / max(iv_put, 0.01), 4),
|
| 417 |
+
})
|
| 418 |
+
return SourceResult(
|
| 419 |
+
source="demo", spot=spot, strikes=strikes,
|
| 420 |
+
expiry_primary="2026-04-17", dte=35,
|
| 421 |
+
oi_total=sum(s["oi_call"] + s["oi_put"] for s in strikes),
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
@staticmethod
|
| 425 |
+
def _nearest_expiry_raw(expirations: list[str], target_dte: int = 35) -> str:
|
| 426 |
+
today = date.today()
|
| 427 |
+
return min(
|
| 428 |
+
expirations,
|
| 429 |
+
key=lambda e: abs(
|
| 430 |
+
(date(int(e[:4]), int(e[4:6]), int(e[6:])) - today).days - target_dte
|
| 431 |
+
),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
# ---------------------------------------------------------------------------
|
| 436 |
+
# Helpers
|
| 437 |
+
# ---------------------------------------------------------------------------
|
| 438 |
+
|
| 439 |
+
def _empty_record(strike: float, expiry: str) -> dict:
|
| 440 |
+
return {
|
| 441 |
+
"strike": strike, "expiry": expiry,
|
| 442 |
+
"oi_call": 0, "oi_put": 0,
|
| 443 |
+
"iv_call": 0.18, "iv_put": 0.19,
|
| 444 |
+
"delta_call": 0.5, "gamma_call": 0.002,
|
| 445 |
+
"delta_put": -0.5, "gamma_put": 0.002,
|
| 446 |
+
"vanna_call": 0.0, "vanna_put": 0.0,
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _add_vanna(strikes: list[dict]) -> None:
|
| 451 |
+
"""Add vanna approximation in-place: dDelta/dIV ≈ delta(1−delta)/IV."""
|
| 452 |
+
for r in strikes:
|
| 453 |
+
r["vanna_call"] = r["delta_call"] * (1 - r["delta_call"]) / max(r["iv_call"], 0.01)
|
| 454 |
+
r["vanna_put"] = abs(r["delta_put"]) * (1 - abs(r["delta_put"])) / max(r["iv_put"], 0.01)
|