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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Market data providers — one normalized interface, four adapters.
|
| 2 |
+
|
| 3 |
+
- YFinanceProvider: free, ~15-min delayed. Zero setup. Default.
|
| 4 |
+
- TradierProvider: real-time with an API key (broker account, free tier).
|
| 5 |
+
- PolygonProvider: real-time snapshot with API key.
|
| 6 |
+
- AlpacaProvider: real-time snapshots with key/secret (greeks computed).
|
| 7 |
+
|
| 8 |
+
Set keys as environment variables TRADIER_API_KEY / POLYGON_API_KEY /
|
| 9 |
+
ALPACA_KEY_ID + ALPACA_SECRET_KEY and the scanner picks the best available
|
| 10 |
+
provider automatically (Tradier > Alpaca > Polygon > yfinance), or force one
|
| 11 |
+
with provider="tradier|alpaca|polygon|yfinance".
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import json
|
| 15 |
+
import urllib.request
|
| 16 |
+
from datetime import datetime, date, timezone
|
| 17 |
+
|
| 18 |
+
from .chain_model import Chain, Quote
|
| 19 |
+
from .pricing import bs_delta, implied_vol, bs_gamma, bs_theta, bs_vega
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class DataProvider:
|
| 23 |
+
name = "base"
|
| 24 |
+
|
| 25 |
+
def get_spot(self, symbol):
|
| 26 |
+
raise NotImplementedError
|
| 27 |
+
|
| 28 |
+
def get_chain(self, symbol, max_expiries=6):
|
| 29 |
+
raise NotImplementedError
|
| 30 |
+
|
| 31 |
+
def get_next_earnings(self, symbol):
|
| 32 |
+
return ""
|
| 33 |
+
|
| 34 |
+
def _fetch_json(self, url, headers=None, timeout=15):
|
| 35 |
+
req = urllib.request.Request(url, headers=headers or {"User-Agent": "options-scanner/1.0"})
|
| 36 |
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 37 |
+
return json.loads(resp.read().decode())
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class YFinanceProvider(DataProvider):
|
| 41 |
+
"""Free delayed data. Requires `pip install yfinance`."""
|
| 42 |
+
name = "yfinance"
|
| 43 |
+
|
| 44 |
+
def __init__(self):
|
| 45 |
+
import yfinance as yf # noqa: F401 (fail fast if missing)
|
| 46 |
+
self._yf = yf
|
| 47 |
+
|
| 48 |
+
def get_spot(self, symbol):
|
| 49 |
+
t = self._yf.Ticker(symbol)
|
| 50 |
+
price = None
|
| 51 |
+
try:
|
| 52 |
+
fi = t.fast_info
|
| 53 |
+
price = fi["lastPrice"] if "lastPrice" in fi else fi.last_price
|
| 54 |
+
except Exception:
|
| 55 |
+
pass
|
| 56 |
+
if not price:
|
| 57 |
+
price = t.history(period="1d")["Close"].iloc[-1]
|
| 58 |
+
return float(price)
|
| 59 |
+
|
| 60 |
+
def get_next_earnings(self, symbol):
|
| 61 |
+
try:
|
| 62 |
+
cal = self._yf.Ticker(symbol).calendar
|
| 63 |
+
if isinstance(cal, dict):
|
| 64 |
+
d = cal.get("Earnings Date")
|
| 65 |
+
if isinstance(d, list) and d:
|
| 66 |
+
return d[0].strftime("%Y-%m-%d") if hasattr(d[0], "strftime") else str(d[0])
|
| 67 |
+
if d and hasattr(d, "strftime"):
|
| 68 |
+
return d.strftime("%Y-%m-%d")
|
| 69 |
+
except Exception:
|
| 70 |
+
pass
|
| 71 |
+
return ""
|
| 72 |
+
|
| 73 |
+
def get_chain(self, symbol, max_expiries=6):
|
| 74 |
+
t = self._yf.Ticker(symbol)
|
| 75 |
+
spot = self.get_spot(symbol)
|
| 76 |
+
exps = list(t.options)[:max_expiries]
|
| 77 |
+
quotes = []
|
| 78 |
+
for exp in exps:
|
| 79 |
+
oc = t.option_chain(exp)
|
| 80 |
+
for df, kind in ((oc.calls, "C"), (oc.puts, "P")):
|
| 81 |
+
for _, row in df.iterrows():
|
| 82 |
+
bid, ask = float(row.get("bid", 0) or 0), float(row.get("ask", 0) or 0)
|
| 83 |
+
last = float(row.get("lastPrice", 0) or 0)
|
| 84 |
+
iv = float(row.get("impliedVolatility", 0) or 0)
|
| 85 |
+
dte = (datetime.strptime(exp, "%Y-%m-%d").date() -
|
| 86 |
+
datetime.now(timezone.utc).date()).days
|
| 87 |
+
delta = bs_delta(spot, float(row["strike"]), max(dte, 0.5) / 365.0, iv, kind)
|
| 88 |
+
_v = row.get("volume", 0)
|
| 89 |
+
_oi = row.get("openInterest", 0)
|
| 90 |
+
quotes.append(Quote(strike=float(row["strike"]), expiry=exp, kind=kind,
|
| 91 |
+
bid=bid, ask=ask, last=last, iv=iv, delta=delta,
|
| 92 |
+
volume=int(_v) if _v == _v else 0,
|
| 93 |
+
open_interest=int(_oi) if _oi == _oi else 0))
|
| 94 |
+
chain = Chain(symbol=symbol, spot=spot, quotes=quotes)
|
| 95 |
+
back = chain.expirations(min_dte=25, max_dte=45)
|
| 96 |
+
chain.iv30 = chain.atm_iv(back[0] if back else (exps[-1] if exps else exps[0])) if quotes else 0.0
|
| 97 |
+
chain.next_earnings = self.get_next_earnings(symbol)
|
| 98 |
+
return chain
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class TradierProvider(DataProvider):
|
| 102 |
+
"""Real-time (with broker account) option chains incl. greeks.
|
| 103 |
+
TRADIER_API_KEY + optionally TRADIER_BASE (default live)."""
|
| 104 |
+
name = "tradier"
|
| 105 |
+
|
| 106 |
+
def __init__(self, api_key=None, base=None):
|
| 107 |
+
self.key = api_key or os.environ["TRADIER_API_KEY"]
|
| 108 |
+
self.base = base or os.environ.get("TRADIER_BASE", "https://api.tradier.com/v1")
|
| 109 |
+
self.headers = {"Authorization": f"Bearer {self.key}", "Accept": "application/json"}
|
| 110 |
+
|
| 111 |
+
def get_spot(self, symbol):
|
| 112 |
+
data = self._fetch_json(f"{self.base}/markets/quotes?symbols={symbol}", self.headers)
|
| 113 |
+
return float(data["quotes"]["quote"]["last"])
|
| 114 |
+
|
| 115 |
+
def get_chain(self, symbol, max_expiries=6):
|
| 116 |
+
spot = self.get_spot(symbol)
|
| 117 |
+
edata = self._fetch_json(f"{self.base}/markets/options/expirations?symbol={symbol}", self.headers)
|
| 118 |
+
exps = edata["expirations"]["date"][:max_expiries]
|
| 119 |
+
if isinstance(exps, str):
|
| 120 |
+
exps = [exps]
|
| 121 |
+
quotes = []
|
| 122 |
+
for exp in exps:
|
| 123 |
+
cdata = self._fetch_json(f"{self.base}/markets/options/chains?symbol={symbol}&expiration={exp}",
|
| 124 |
+
self.headers)
|
| 125 |
+
opts = (cdata.get("options") or {}).get("option") or []
|
| 126 |
+
if isinstance(opts, dict):
|
| 127 |
+
opts = [opts]
|
| 128 |
+
for o in opts:
|
| 129 |
+
g = o.get("greeks") or {}
|
| 130 |
+
quotes.append(Quote(strike=float(o["strike"]), expiry=exp,
|
| 131 |
+
kind="C" if o["option_type"] == "call" else "P",
|
| 132 |
+
bid=float(o.get("bid") or 0), ask=float(o.get("ask") or 0),
|
| 133 |
+
last=float(o.get("last") or 0),
|
| 134 |
+
iv=float(g.get("mid_iv") or 0),
|
| 135 |
+
delta=float(g.get("delta") or 0),
|
| 136 |
+
volume=int(o.get("volume") or 0),
|
| 137 |
+
open_interest=int(o.get("open_interest") or 0)))
|
| 138 |
+
chain = Chain(symbol=symbol, spot=spot, quotes=quotes)
|
| 139 |
+
back = chain.expirations(min_dte=25, max_dte=45)
|
| 140 |
+
chain.iv30 = chain.atm_iv(back[0] if back else exps[0]) if quotes else 0.0
|
| 141 |
+
return chain
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class PolygonProvider(DataProvider):
|
| 145 |
+
"""Real-time snapshot chain. Requires POLYGON_API_KEY (options plan)."""
|
| 146 |
+
name = "polygon"
|
| 147 |
+
|
| 148 |
+
def __init__(self, api_key=None):
|
| 149 |
+
self.key = api_key or os.environ["POLYGON_API_KEY"]
|
| 150 |
+
|
| 151 |
+
def get_spot(self, symbol):
|
| 152 |
+
data = self._fetch_json(f"https://api.polygon.io/v2/aggs/ticker/I:{symbol}/prev")
|
| 153 |
+
return float(data["results"][0]["c"])
|
| 154 |
+
|
| 155 |
+
def get_chain(self, symbol, max_expiries=6):
|
| 156 |
+
url = (f"https://api.polygon.io/v3/snapshot/options/{symbol}?"
|
| 157 |
+
f"limit=250&apiKey={self.key}")
|
| 158 |
+
quotes, spot = [], 0.0
|
| 159 |
+
while url and len({(q.expiry) for q in quotes}) < max_expiries:
|
| 160 |
+
data = self._fetch_json(url)
|
| 161 |
+
for r in data.get("results", []):
|
| 162 |
+
d = r.get("details", {})
|
| 163 |
+
exp = d.get("expiration_date")
|
| 164 |
+
lq = r.get("last_quote") or {}
|
| 165 |
+
if not exp or r.get("underlying_asset", {}).get("price", 0) == 0:
|
| 166 |
+
spot = spot or float(r.get("underlying_asset", {}).get("price") or 0)
|
| 167 |
+
otype = d.get("contract_type", "").upper()[:1]
|
| 168 |
+
g = r.get("greeks") or {}
|
| 169 |
+
quotes.append(Quote(strike=float(d.get("strike_price", 0)), expiry=exp,
|
| 170 |
+
kind="C" if otype == "C" else "P",
|
| 171 |
+
bid=float(lq.get("bid") or 0), ask=float(lq.get("ask") or 0),
|
| 172 |
+
last=float((r.get("last_trade") or {}).get("price") or 0),
|
| 173 |
+
iv=float(r.get("implied_volatility") or 0) / 100.0,
|
| 174 |
+
delta=float(g.get("delta") or 0),
|
| 175 |
+
volume=int((r.get("day") or {}).get("volume") or 0),
|
| 176 |
+
open_interest=int(r.get("open_interest") or 0)))
|
| 177 |
+
url = data.get("next_url")
|
| 178 |
+
if url:
|
| 179 |
+
url += f"&apiKey={self.key}"
|
| 180 |
+
if spot == 0:
|
| 181 |
+
spot = self.get_spot(symbol)
|
| 182 |
+
chain = Chain(symbol=symbol, spot=spot, quotes=quotes)
|
| 183 |
+
back = chain.expirations(min_dte=25, max_dte=45)
|
| 184 |
+
if quotes and back:
|
| 185 |
+
chain.iv30 = chain.atm_iv(back[0])
|
| 186 |
+
return chain
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class AlpacaProvider(DataProvider):
|
| 190 |
+
"""Real-time options snapshots + IEX stock trades. No greeks/IV from the
|
| 191 |
+
API, so IV is backed out of the mid and delta computed from it.
|
| 192 |
+
ALPACA_KEY_ID + ALPACA_SECRET_KEY (optionally ALPACA_BASE)."""
|
| 193 |
+
name = "alpaca"
|
| 194 |
+
|
| 195 |
+
def __init__(self, key_id=None, secret_key=None, base=None):
|
| 196 |
+
self.key = key_id or os.environ["ALPACA_KEY_ID"]
|
| 197 |
+
self.secret = secret_key or os.environ["ALPACA_SECRET_KEY"]
|
| 198 |
+
self.base = base or os.environ.get("ALPACA_BASE", "https://data.alpaca.markets")
|
| 199 |
+
self.headers = {"APCA-API-KEY-ID": self.key, "APCA-API-SECRET-KEY": self.secret}
|
| 200 |
+
|
| 201 |
+
def get_spot(self, symbol):
|
| 202 |
+
data = self._fetch_json(f"{self.base}/v2/stocks/{symbol}/trades/latest?feed=iex",
|
| 203 |
+
self.headers)
|
| 204 |
+
return float(data["trade"]["p"])
|
| 205 |
+
|
| 206 |
+
def get_next_earnings(self, symbol):
|
| 207 |
+
"""Alpaca has no earnings endpoint; fall back to yfinance calendar."""
|
| 208 |
+
try:
|
| 209 |
+
import yfinance as yf
|
| 210 |
+
cal = yf.Ticker(symbol).calendar
|
| 211 |
+
if isinstance(cal, dict):
|
| 212 |
+
d = cal.get("Earnings Date")
|
| 213 |
+
if isinstance(d, list) and d:
|
| 214 |
+
return d[0].strftime("%Y-%m-%d") if hasattr(d[0], "strftime") else str(d[0])
|
| 215 |
+
if d and hasattr(d, "strftime"):
|
| 216 |
+
return d.strftime("%Y-%m-%d")
|
| 217 |
+
except Exception:
|
| 218 |
+
pass
|
| 219 |
+
return ""
|
| 220 |
+
|
| 221 |
+
def get_chain(self, symbol, max_expiries=6):
|
| 222 |
+
spot = self.get_spot(symbol)
|
| 223 |
+
today = datetime.now(timezone.utc).date()
|
| 224 |
+
quotes = []
|
| 225 |
+
counts = {} # expiry -> quote count, in ascending encounter order
|
| 226 |
+
complete = set() # expiries seen in full (a later expiry appeared, or data ended)
|
| 227 |
+
token = None
|
| 228 |
+
for _ in range(60): # page cap safety
|
| 229 |
+
url = (f"{self.base}/v1beta1/options/snapshots/{symbol}?limit=1000"
|
| 230 |
+
+ (f"&page_token={token}" if token else ""))
|
| 231 |
+
data = self._fetch_json(url, self.headers)
|
| 232 |
+
snaps = data.get("snapshots") or {}
|
| 233 |
+
for occ, s in snaps.items():
|
| 234 |
+
# OCC symbol tail: YYMMDD + C/P + 8-digit strike (x1000)
|
| 235 |
+
if len(occ) < 15:
|
| 236 |
+
continue
|
| 237 |
+
raw = occ[-15:-9]
|
| 238 |
+
exp = f"20{raw[:2]}-{raw[2:4]}-{raw[4:6]}"
|
| 239 |
+
if exp not in counts:
|
| 240 |
+
# snapshots are ordered by expiry, so everything already
|
| 241 |
+
# tracked is now known to be complete
|
| 242 |
+
complete.update(counts)
|
| 243 |
+
counts[exp] = 0
|
| 244 |
+
counts[exp] += 1
|
| 245 |
+
if len(complete) >= max_expiries and exp not in complete:
|
| 246 |
+
break # this expiry is past the window; stop collecting
|
| 247 |
+
kind = occ[-9]
|
| 248 |
+
strike = int(occ[-8:]) / 1000.0
|
| 249 |
+
lq = s.get("latestQuote") or {}
|
| 250 |
+
bid, ask = float(lq.get("bp") or 0), float(lq.get("ap") or 0)
|
| 251 |
+
if bid <= 0 and ask <= 0:
|
| 252 |
+
continue # stale / no market
|
| 253 |
+
if bid <= 0 or ask <= 0 or ask < bid:
|
| 254 |
+
mid = bid if bid > 0 else ask
|
| 255 |
+
else:
|
| 256 |
+
mid = (bid + ask) / 2.0
|
| 257 |
+
last = float((s.get("latestTrade") or {}).get("p") or 0)
|
| 258 |
+
dte = max((date.fromisoformat(exp) - today).days, 0)
|
| 259 |
+
T = max(dte, 0.5) / 365.0
|
| 260 |
+
iv = implied_vol(mid, spot, strike, T, kind)
|
| 261 |
+
if iv <= 0 and last > 0:
|
| 262 |
+
iv = implied_vol(last, spot, strike, T, kind)
|
| 263 |
+
if not (0.005 < iv < 3.0):
|
| 264 |
+
continue # stale/garbage IEX quote: implied vol impossible
|
| 265 |
+
delta = bs_delta(spot, strike, T, iv, kind) if iv > 0 else 0.0
|
| 266 |
+
bar = s.get("dailyBar") or {}
|
| 267 |
+
quotes.append(Quote(strike=strike, expiry=exp,
|
| 268 |
+
kind="C" if kind == "C" else "P",
|
| 269 |
+
bid=bid, ask=ask, last=last, iv=iv, delta=delta,
|
| 270 |
+
volume=int(bar.get("v") or 0),
|
| 271 |
+
open_interest=-1)) # OI not in snapshots (-1 = unknown)
|
| 272 |
+
if len(complete) >= max_expiries:
|
| 273 |
+
break
|
| 274 |
+
token = data.get("next_page_token")
|
| 275 |
+
if not token:
|
| 276 |
+
complete.update(counts) # data exhausted: last expiry is whole
|
| 277 |
+
break
|
| 278 |
+
exps = sorted(e for e in complete if counts.get(e))[:max_expiries]
|
| 279 |
+
keep = set(exps)
|
| 280 |
+
quotes = [q for q in quotes if q.expiry in keep]
|
| 281 |
+
chain = Chain(symbol=symbol, spot=spot, quotes=quotes)
|
| 282 |
+
back = chain.expirations(min_dte=25, max_dte=45)
|
| 283 |
+
if not back and exps:
|
| 284 |
+
# nearest max_expiries can sit entirely under 25 DTE; use the
|
| 285 |
+
# expiry closest to 30 DTE we actually have
|
| 286 |
+
dtes = [(abs((date.fromisoformat(e) - today).days - 30), e) for e in exps]
|
| 287 |
+
back = [min(dtes)[1]]
|
| 288 |
+
chain.iv30 = chain.atm_iv(back[0]) if quotes and back else 0.0
|
| 289 |
+
chain.next_earnings = self.get_next_earnings(symbol)
|
| 290 |
+
return chain
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def get_provider(force=None):
|
| 294 |
+
"""Best available: Tradier (real-time) > Alpaca > Polygon > yfinance (free)."""
|
| 295 |
+
if force == "tradier" or (not force and os.environ.get("TRADIER_API_KEY")):
|
| 296 |
+
return TradierProvider()
|
| 297 |
+
if force == "alpaca" or (not force and os.environ.get("ALPACA_KEY_ID")
|
| 298 |
+
and os.environ.get("ALPACA_SECRET_KEY")):
|
| 299 |
+
return AlpacaProvider()
|
| 300 |
+
if force == "polygon" or (not force and os.environ.get("POLYGON_API_KEY")):
|
| 301 |
+
return PolygonProvider()
|
| 302 |
+
return YFinanceProvider()
|