Download options_scanner/scan.py from Reckless88/options-scanner: direct link, hf CLI and curl.
- Browser
- Download file 7.7 kB
-
https://huggingface.co/datasets/Reckless88/options-scanner/resolve/main/options_scanner/scan.py
- Command line
-
hf download hf://datasets/Reckless88/options-scanner/options_scanner/scan.py
-
curl -L -o scan.py https://huggingface.co/datasets/Reckless88/options-scanner/resolve/main/options_scanner/scan.py
7.7 kB
| """Scanner CLI — the automated daily/loop run. | |
| Usage: | |
| python -m options_scanner.scan # auto universe, free data | |
| python -m options_scanner.scan --symbols SPY,QQQ # explicit watchlist | |
| python -m options_scanner.scan --provider tradier # force real-time provider | |
| python -m options_scanner.scan --output results.json --csv results.csv | |
| TRADIER_API_KEY / POLYGON_API_KEY in the environment switch to real-time data | |
| automatically. | |
| """ | |
| import argparse | |
| import csv | |
| import json | |
| import sys | |
| import time | |
| from datetime import datetime, timezone | |
| from .config import RiskParams | |
| from .universe import auto_universe | |
| from .data import get_provider | |
| from .strategies import ALL_BUILDERS | |
| from .risk import passes_liquidity, passes_defined_risk, risk_report, score | |
| from .chain_model import Chain | |
| def fetch_chain(provider, symbol, max_expiries, retries=2): | |
| last_err = None | |
| for _ in range(retries + 1): | |
| try: | |
| return provider.get_chain(symbol, max_expiries=max_expiries) | |
| except Exception as e: | |
| last_err = e | |
| time.sleep(1.0) | |
| raise last_err | |
| def earnings_gate_ok(chain, candidate, params): | |
| if not params.avoid_earnings or not chain.next_earnings: | |
| return True, "" | |
| earn = chain.next_earnings | |
| exps = {l.expiry for l, _ in candidate.legs} | |
| for e in exps: | |
| if earn <= e: # earnings fall inside the trade's life | |
| return False, f"earnings {earn} inside trade window (expiry {e})" | |
| return True, "" | |
| def scan_symbol(provider, symbol, params, max_expiries=5): | |
| chain = fetch_chain(provider, symbol, max_expiries) | |
| if not chain.quotes or chain.spot <= 0: | |
| return symbol, [], f"empty chain" | |
| horizon = chain.expirations(min_dte=params.min_dte, max_dte=params.max_dte)[0] | |
| candidates = [] | |
| for builder in ALL_BUILDERS: | |
| for cand in builder(chain, params): | |
| # risk metrics on the earliest short-expiry horizon | |
| cand.risk_metrics(chain, min(l.expiry for l, _ in cand.legs)) | |
| ok, why = passes_liquidity(cand, params.min_oi, params.max_rel_spread) | |
| if not ok: | |
| cand.reasons.append(f"rejected: {why}") | |
| continue | |
| ok, why = passes_defined_risk(cand, params.allow_undefined_risk) | |
| if not ok: | |
| cand.reasons.append(f"rejected: {why}") | |
| continue | |
| if cand.max_loss * 100.0 > params.account_size * params.max_buying_power_pct / 100.0: | |
| cand.reasons.append( | |
| f"rejected: BPE ${cand.max_loss * 100:.0f} > " | |
| f"{params.max_buying_power_pct:.0f}% of ${params.account_size:,.0f}") | |
| continue | |
| ok, why = earnings_gate_ok(chain, cand, params) | |
| if not ok: | |
| cand.reasons.append(f"rejected: {why}") | |
| continue | |
| if cand.net_credit < 0 and cand.max_profit <= 0: | |
| continue | |
| score(cand) | |
| candidates.append(cand) | |
| # keep the best few per symbol, annotated | |
| candidates.sort(key=lambda c: c.score, reverse=True) | |
| for c in candidates: | |
| c.reasons.append(f"chain liquidity {chain.liquidity_score(min(l.expiry for l, _ in c.legs)):.0f}/100, " | |
| f"ATM IV {chain.iv30:.0%}, spot {chain.spot:g}, earnings {chain.next_earnings or 'n/a'}") | |
| return symbol, candidates[:params.max_candidates_per_symbol], "" | |
| def to_row(symbol, c): | |
| notes = c.notes | |
| if "Backspread" in c.name: | |
| notes += " | max profit unbounded above; reported value is at the +60% grid boundary" | |
| return { | |
| "symbol": symbol, "strategy": c.name, "view": c.view, | |
| "net_credit_debit": round(c.net_credit, 2), "credit_debit_usd": round(c.net_credit * 100, 2), | |
| "max_profit_usd": round(c.max_profit * 100, 2), "max_loss_usd": round(c.max_loss * 100, 2), | |
| "pop_pct": round(c.pop * 100, 1), "score": c.score, | |
| "breakevens": ",".join(str(b) for b in c.breakevens), | |
| "legs": " ; ".join(l.label() for l, _ in c.legs), | |
| "notes": notes, "reasons": " | ".join(c.reasons), | |
| } | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(prog="options-scanner") | |
| ap.add_argument("--symbols", default="", help="comma-separated watchlist; empty = auto") | |
| ap.add_argument("--provider", default=None, choices=["alpaca", "tradier", "polygon", "yfinance"]) | |
| ap.add_argument("--auto-top", type=int, default=10, help="universe size when auto-picking") | |
| ap.add_argument("--max-expiries", type=int, default=5) | |
| ap.add_argument("--account-size", type=float, default=25000.0) | |
| ap.add_argument("--risk-pct", type=float, default=5.0) | |
| ap.add_argument("--output", default="results.json") | |
| ap.add_argument("--csv", default="") | |
| ap.add_argument("--allow-undefined-risk", action="store_true", | |
| help="admit naked straddles/strangles (NOT recommended)") | |
| args = ap.parse_args(argv) | |
| params = RiskParams(account_size=args.account_size, max_buying_power_pct=args.risk_pct, | |
| allow_undefined_risk=args.allow_undefined_risk) | |
| provider = get_provider(args.provider) | |
| print(f"[scan] provider={provider.name} account=${params.account_size:,.0f} " | |
| f"max risk/trade={params.max_buying_power_pct:.0f}%", flush=True) | |
| if args.symbols: | |
| universe = [s.strip().upper() for s in args.symbols.split(",") if s.strip()] | |
| else: | |
| universe = auto_universe() | |
| results, errors = [], [] | |
| started = time.time() | |
| for sym in universe: | |
| try: | |
| sym, cands, err = scan_symbol(provider, sym, params, args.max_expiries) | |
| if err: | |
| errors.append({"symbol": sym, "error": err}) | |
| print(f"[scan] {sym}: {err}", flush=True) | |
| elif cands: | |
| print(f"[scan] {sym}: {len(cands)} candidates " | |
| f"(best {cands[0].name} score {cands[0].score})", flush=True) | |
| for c in cands: | |
| results.append(to_row(sym, c)) | |
| except Exception as e: | |
| errors.append({"symbol": sym, "error": str(e)[:200]}) | |
| print(f"[scan] {sym}: ERROR {e}", flush=True) | |
| time.sleep(0.4) # be polite to the free endpoint | |
| results.sort(key=lambda r: r["score"], reverse=True) | |
| payload = { | |
| "generated_at": datetime.now(timezone.utc).isoformat(), | |
| "provider": provider.name, | |
| "universe_size": len(universe), | |
| "scanned": len(universe) - len(errors), | |
| "params": { | |
| "account_size": params.account_size, | |
| "max_buying_power_pct": params.max_buying_power_pct, | |
| "credit_short_delta": params.credit_short_delta, | |
| "condor_short_delta": params.condor_short_delta, | |
| "min_oi": params.min_oi, "max_rel_spread": params.max_rel_spread, | |
| "allow_undefined_risk": params.allow_undefined_risk, | |
| "avoid_earnings": params.avoid_earnings, | |
| }, | |
| "top_candidates": results, | |
| "errors": errors, | |
| "runtime_seconds": round(time.time() - started, 1), | |
| } | |
| with open(args.output, "w") as f: | |
| json.dump(payload, f, indent=1) | |
| print(f"[scan] wrote {args.output}: {len(results)} candidates, " | |
| f"{len(errors)} errors, {payload['runtime_seconds']}s", flush=True) | |
| if args.csv: | |
| if results: | |
| with open(args.csv, "w", newline="") as f: | |
| w = csv.DictWriter(f, fieldnames=list(results[0].keys())) | |
| w.writeheader() | |
| w.writerows(results) | |
| print(f"[scan] wrote {args.csv}", flush=True) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |