Download options_scanner/data.py from Reckless88/options-scanner: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/datasets/Reckless88/options-scanner/resolve/main/options_scanner/data.py
- Command line
-
hf download hf://datasets/Reckless88/options-scanner/options_scanner/data.py
-
curl -L -o data.py https://huggingface.co/datasets/Reckless88/options-scanner/resolve/main/options_scanner/data.py
15.3 kB
| """Market data providers — one normalized interface, four adapters. | |
| - YFinanceProvider: free, ~15-min delayed. Zero setup. Default. | |
| - TradierProvider: real-time with an API key (broker account, free tier). | |
| - PolygonProvider: real-time snapshot with API key. | |
| - AlpacaProvider: real-time snapshots with key/secret (greeks computed). | |
| Set keys as environment variables TRADIER_API_KEY / POLYGON_API_KEY / | |
| ALPACA_KEY_ID + ALPACA_SECRET_KEY and the scanner picks the best available | |
| provider automatically (Tradier > Alpaca > Polygon > yfinance), or force one | |
| with provider="tradier|alpaca|polygon|yfinance". | |
| """ | |
| import os | |
| import json | |
| import urllib.request | |
| from datetime import datetime, date, timezone | |
| from .chain_model import Chain, Quote | |
| from .pricing import bs_delta, implied_vol, bs_gamma, bs_theta, bs_vega, bs_price | |
| class DataProvider: | |
| name = "base" | |
| def get_spot(self, symbol): | |
| raise NotImplementedError | |
| def get_chain(self, symbol, max_expiries=6): | |
| raise NotImplementedError | |
| def get_next_earnings(self, symbol): | |
| return "" | |
| def _fetch_json(self, url, headers=None, timeout=15): | |
| req = urllib.request.Request(url, headers=headers or {"User-Agent": "options-scanner/1.0"}) | |
| with urllib.request.urlopen(req, timeout=timeout) as resp: | |
| return json.loads(resp.read().decode()) | |
| class YFinanceProvider(DataProvider): | |
| """Free delayed data. Requires `pip install yfinance`.""" | |
| name = "yfinance" | |
| def __init__(self): | |
| import yfinance as yf # noqa: F401 (fail fast if missing) | |
| self._yf = yf | |
| def get_spot(self, symbol): | |
| t = self._yf.Ticker(symbol) | |
| price = None | |
| try: | |
| fi = t.fast_info | |
| price = fi["lastPrice"] if "lastPrice" in fi else fi.last_price | |
| except Exception: | |
| pass | |
| if not price: | |
| price = t.history(period="1d")["Close"].iloc[-1] | |
| return float(price) | |
| def get_next_earnings(self, symbol): | |
| try: | |
| cal = self._yf.Ticker(symbol).calendar | |
| if isinstance(cal, dict): | |
| d = cal.get("Earnings Date") | |
| if isinstance(d, list) and d: | |
| return d[0].strftime("%Y-%m-%d") if hasattr(d[0], "strftime") else str(d[0]) | |
| if d and hasattr(d, "strftime"): | |
| return d.strftime("%Y-%m-%d") | |
| except Exception: | |
| pass | |
| return "" | |
| def get_chain(self, symbol, max_expiries=6): | |
| t = self._yf.Ticker(symbol) | |
| spot = self.get_spot(symbol) | |
| exps = list(t.options)[:max_expiries] | |
| quotes = [] | |
| for exp in exps: | |
| oc = t.option_chain(exp) | |
| for df, kind in ((oc.calls, "C"), (oc.puts, "P")): | |
| for _, row in df.iterrows(): | |
| bid, ask = float(row.get("bid", 0) or 0), float(row.get("ask", 0) or 0) | |
| last = float(row.get("lastPrice", 0) or 0) | |
| iv = float(row.get("impliedVolatility", 0) or 0) | |
| dte = (datetime.strptime(exp, "%Y-%m-%d").date() - | |
| datetime.now(timezone.utc).date()).days | |
| delta = bs_delta(spot, float(row["strike"]), max(dte, 0.5) / 365.0, iv, kind) | |
| _v = row.get("volume", 0) | |
| _oi = row.get("openInterest", 0) | |
| quotes.append(Quote(strike=float(row["strike"]), expiry=exp, kind=kind, | |
| bid=bid, ask=ask, last=last, iv=iv, delta=delta, | |
| volume=int(_v) if _v == _v else 0, | |
| open_interest=int(_oi) if _oi == _oi else 0)) | |
| chain = Chain(symbol=symbol, spot=spot, quotes=quotes) | |
| back = chain.expirations(min_dte=25, max_dte=45) | |
| chain.iv30 = chain.atm_iv(back[0] if back else (exps[-1] if exps else exps[0])) if quotes else 0.0 | |
| chain.next_earnings = self.get_next_earnings(symbol) | |
| return chain | |
| class TradierProvider(DataProvider): | |
| """Real-time (with broker account) option chains incl. greeks. | |
| TRADIER_API_KEY + optionally TRADIER_BASE (default live).""" | |
| name = "tradier" | |
| def __init__(self, api_key=None, base=None): | |
| self.key = api_key or os.environ["TRADIER_API_KEY"] | |
| self.base = base or os.environ.get("TRADIER_BASE", "https://api.tradier.com/v1") | |
| self.headers = {"Authorization": f"Bearer {self.key}", "Accept": "application/json"} | |
| def get_spot(self, symbol): | |
| data = self._fetch_json(f"{self.base}/markets/quotes?symbols={symbol}", self.headers) | |
| return float(data["quotes"]["quote"]["last"]) | |
| def get_chain(self, symbol, max_expiries=6): | |
| spot = self.get_spot(symbol) | |
| edata = self._fetch_json(f"{self.base}/markets/options/expirations?symbol={symbol}", self.headers) | |
| exps = edata["expirations"]["date"][:max_expiries] | |
| if isinstance(exps, str): | |
| exps = [exps] | |
| quotes = [] | |
| for exp in exps: | |
| cdata = self._fetch_json(f"{self.base}/markets/options/chains?symbol={symbol}&expiration={exp}", | |
| self.headers) | |
| opts = (cdata.get("options") or {}).get("option") or [] | |
| if isinstance(opts, dict): | |
| opts = [opts] | |
| for o in opts: | |
| g = o.get("greeks") or {} | |
| quotes.append(Quote(strike=float(o["strike"]), expiry=exp, | |
| kind="C" if o["option_type"] == "call" else "P", | |
| bid=float(o.get("bid") or 0), ask=float(o.get("ask") or 0), | |
| last=float(o.get("last") or 0), | |
| iv=float(g.get("mid_iv") or 0), | |
| delta=float(g.get("delta") or 0), | |
| volume=int(o.get("volume") or 0), | |
| open_interest=int(o.get("open_interest") or 0))) | |
| chain = Chain(symbol=symbol, spot=spot, quotes=quotes) | |
| # Many Tradier entitlements return no greeks block; compute IV and | |
| # delta from the quotes ourselves when missing. | |
| from datetime import datetime | |
| for q in chain.quotes: | |
| if q.iv <= 0 and q.mid > 0: | |
| dte = (datetime.strptime(q.expiry, "%Y-%m-%d").date() - | |
| datetime.now(timezone.utc).date()).days | |
| T = max(dte, 0.5) / 365.0 | |
| q.iv = implied_vol(q.mid, spot, q.strike, T, q.kind) | |
| q.delta = bs_delta(spot, q.strike, T, q.iv, q.kind) if q.iv > 0 else 0.0 | |
| back = chain.expirations(min_dte=25, max_dte=45) | |
| chain.iv30 = chain.atm_iv(back[0] if back else exps[0]) if quotes else 0.0 | |
| return chain | |
| class PolygonProvider(DataProvider): | |
| """Real-time snapshot chain. Requires POLYGON_API_KEY (options plan).""" | |
| name = "polygon" | |
| def __init__(self, api_key=None): | |
| self.key = api_key or os.environ["POLYGON_API_KEY"] | |
| def get_spot(self, symbol): | |
| data = self._fetch_json(f"https://api.polygon.io/v2/aggs/ticker/I:{symbol}/prev") | |
| return float(data["results"][0]["c"]) | |
| def get_chain(self, symbol, max_expiries=6): | |
| url = (f"https://api.polygon.io/v3/snapshot/options/{symbol}?" | |
| f"limit=250&apiKey={self.key}") | |
| quotes, spot = [], 0.0 | |
| while url and len({(q.expiry) for q in quotes}) < max_expiries: | |
| data = self._fetch_json(url) | |
| for r in data.get("results", []): | |
| d = r.get("details", {}) | |
| exp = d.get("expiration_date") | |
| lq = r.get("last_quote") or {} | |
| if not exp or r.get("underlying_asset", {}).get("price", 0) == 0: | |
| spot = spot or float(r.get("underlying_asset", {}).get("price") or 0) | |
| otype = d.get("contract_type", "").upper()[:1] | |
| g = r.get("greeks") or {} | |
| quotes.append(Quote(strike=float(d.get("strike_price", 0)), expiry=exp, | |
| kind="C" if otype == "C" else "P", | |
| bid=float(lq.get("bid") or 0), ask=float(lq.get("ask") or 0), | |
| last=float((r.get("last_trade") or {}).get("price") or 0), | |
| iv=float(r.get("implied_volatility") or 0) / 100.0, | |
| delta=float(g.get("delta") or 0), | |
| volume=int((r.get("day") or {}).get("volume") or 0), | |
| open_interest=int(r.get("open_interest") or 0))) | |
| url = data.get("next_url") | |
| if url: | |
| url += f"&apiKey={self.key}" | |
| if spot == 0: | |
| spot = self.get_spot(symbol) | |
| chain = Chain(symbol=symbol, spot=spot, quotes=quotes) | |
| back = chain.expirations(min_dte=25, max_dte=45) | |
| if quotes and back: | |
| chain.iv30 = chain.atm_iv(back[0]) | |
| return chain | |
| class AlpacaProvider(DataProvider): | |
| """Real-time options snapshots + IEX stock trades. No greeks/IV from the | |
| API, so IV is backed out of the mid and delta computed from it. | |
| ALPACA_KEY_ID + ALPACA_SECRET_KEY (optionally ALPACA_BASE).""" | |
| name = "alpaca" | |
| def __init__(self, key_id=None, secret_key=None, base=None): | |
| self.key = key_id or os.environ["ALPACA_KEY_ID"] | |
| self.secret = secret_key or os.environ["ALPACA_SECRET_KEY"] | |
| self.base = base or os.environ.get("ALPACA_BASE", "https://data.alpaca.markets") | |
| self.headers = {"APCA-API-KEY-ID": self.key, "APCA-API-SECRET-KEY": self.secret} | |
| def get_spot(self, symbol): | |
| data = self._fetch_json(f"{self.base}/v2/stocks/{symbol}/trades/latest?feed=iex", | |
| self.headers) | |
| return float(data["trade"]["p"]) | |
| def get_next_earnings(self, symbol): | |
| """Alpaca has no earnings endpoint; fall back to yfinance calendar.""" | |
| try: | |
| import yfinance as yf | |
| cal = yf.Ticker(symbol).calendar | |
| if isinstance(cal, dict): | |
| d = cal.get("Earnings Date") | |
| if isinstance(d, list) and d: | |
| return d[0].strftime("%Y-%m-%d") if hasattr(d[0], "strftime") else str(d[0]) | |
| if d and hasattr(d, "strftime"): | |
| return d.strftime("%Y-%m-%d") | |
| except Exception: | |
| pass | |
| return "" | |
| def get_chain(self, symbol, max_expiries=6): | |
| spot = self.get_spot(symbol) | |
| today = datetime.now(timezone.utc).date() | |
| quotes = [] | |
| counts = {} # expiry -> quote count, in ascending encounter order | |
| complete = set() # expiries seen in full (a later expiry appeared, or data ended) | |
| token = None | |
| for _ in range(60): # page cap safety | |
| url = (f"{self.base}/v1beta1/options/snapshots/{symbol}?limit=1000" | |
| + (f"&page_token={token}" if token else "")) | |
| data = self._fetch_json(url, self.headers) | |
| snaps = data.get("snapshots") or {} | |
| for occ, s in snaps.items(): | |
| # OCC symbol tail: YYMMDD + C/P + 8-digit strike (x1000) | |
| if len(occ) < 15: | |
| continue | |
| raw = occ[-15:-9] | |
| exp = f"20{raw[:2]}-{raw[2:4]}-{raw[4:6]}" | |
| if exp not in counts: | |
| # snapshots are ordered by expiry, so everything already | |
| # tracked is now known to be complete | |
| complete.update(counts) | |
| counts[exp] = 0 | |
| counts[exp] += 1 | |
| if len(complete) >= max_expiries and exp not in complete: | |
| break # this expiry is past the window; stop collecting | |
| kind = occ[-9] | |
| strike = int(occ[-8:]) / 1000.0 | |
| lq = s.get("latestQuote") or {} | |
| bid, ask = float(lq.get("bp") or 0), float(lq.get("ap") or 0) | |
| if bid <= 0 and ask <= 0: | |
| continue # stale / no market | |
| if bid <= 0 or ask <= 0 or ask < bid: | |
| mid = bid if bid > 0 else ask | |
| else: | |
| mid = (bid + ask) / 2.0 | |
| last = float((s.get("latestTrade") or {}).get("p") or 0) | |
| dte = max((date.fromisoformat(exp) - today).days, 0) | |
| T = max(dte, 0.5) / 365.0 | |
| iv = implied_vol(mid, spot, strike, T, kind) | |
| if iv <= 0 and last > 0: | |
| iv = implied_vol(last, spot, strike, T, kind) | |
| if not (0.005 < iv < 3.0): | |
| continue # stale/garbage IEX quote: implied vol impossible | |
| delta = bs_delta(spot, strike, T, iv, kind) if iv > 0 else 0.0 | |
| bar = s.get("dailyBar") or {} | |
| quotes.append(Quote(strike=strike, expiry=exp, | |
| kind="C" if kind == "C" else "P", | |
| bid=bid, ask=ask, last=last, iv=iv, delta=delta, | |
| volume=int(bar.get("v") or 0), | |
| open_interest=-1)) # OI not in snapshots (-1 = unknown) | |
| if len(complete) >= max_expiries: | |
| break | |
| token = data.get("next_page_token") | |
| if not token: | |
| complete.update(counts) # data exhausted: last expiry is whole | |
| break | |
| exps = sorted(e for e in complete if counts.get(e))[:max_expiries] | |
| keep = set(exps) | |
| quotes = [q for q in quotes if q.expiry in keep] | |
| chain = Chain(symbol=symbol, spot=spot, quotes=quotes) | |
| back = chain.expirations(min_dte=25, max_dte=45) | |
| if not back and exps: | |
| # nearest max_expiries can sit entirely under 25 DTE; use the | |
| # expiry closest to 30 DTE we actually have | |
| dtes = [(abs((date.fromisoformat(e) - today).days - 30), e) for e in exps] | |
| back = [min(dtes)[1]] | |
| chain.iv30 = chain.atm_iv(back[0]) if quotes and back else 0.0 | |
| # Fair-value sanity: thin IEX quotes can be wildly stale in a way that | |
| # only shows up against the rest of the chain. Reject any quote priced | |
| # below 15% or above 6x its ATM-IV Black-Scholes fair value. | |
| if chain.iv30 > 0: | |
| def _fair(q): | |
| return bs_price(spot, q.strike, max(q.dte, 0.5) / 365.0, chain.iv30, q.kind) | |
| chain.quotes = [q for q in chain.quotes | |
| if 0.15 * _fair(q) <= q.mid <= 6.0 * _fair(q)] | |
| chain.next_earnings = self.get_next_earnings(symbol) | |
| return chain | |
| def get_provider(force=None): | |
| """Best available: Tradier (real-time) > Alpaca > Polygon > yfinance (free).""" | |
| if force == "tradier" or (not force and os.environ.get("TRADIER_API_KEY")): | |
| return TradierProvider() | |
| if force == "alpaca" or (not force and os.environ.get("ALPACA_KEY_ID") | |
| and os.environ.get("ALPACA_SECRET_KEY")): | |
| return AlpacaProvider() | |
| if force == "polygon" or (not force and os.environ.get("POLYGON_API_KEY")): | |
| return PolygonProvider() | |
| return YFinanceProvider() | |