File size: 15,310 Bytes
5151eb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777e83e
5151eb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331f0fb
 
 
 
 
 
 
 
 
 
5151eb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777e83e
 
 
 
 
 
 
 
5151eb9
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"""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()