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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scanner CLI — the automated daily/loop run.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
python -m options_scanner.scan # auto universe, free data
|
| 5 |
+
python -m options_scanner.scan --symbols SPY,QQQ # explicit watchlist
|
| 6 |
+
python -m options_scanner.scan --provider tradier # force real-time provider
|
| 7 |
+
python -m options_scanner.scan --output results.json --csv results.csv
|
| 8 |
+
|
| 9 |
+
TRADIER_API_KEY / POLYGON_API_KEY in the environment switch to real-time data
|
| 10 |
+
automatically.
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import csv
|
| 14 |
+
import json
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
|
| 19 |
+
from .config import RiskParams
|
| 20 |
+
from .universe import auto_universe
|
| 21 |
+
from .data import get_provider
|
| 22 |
+
from .strategies import ALL_BUILDERS
|
| 23 |
+
from .risk import passes_liquidity, passes_defined_risk, risk_report, score
|
| 24 |
+
from .chain_model import Chain
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def fetch_chain(provider, symbol, max_expiries, retries=2):
|
| 28 |
+
last_err = None
|
| 29 |
+
for _ in range(retries + 1):
|
| 30 |
+
try:
|
| 31 |
+
return provider.get_chain(symbol, max_expiries=max_expiries)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
last_err = e
|
| 34 |
+
time.sleep(1.0)
|
| 35 |
+
raise last_err
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def earnings_gate_ok(chain, candidate, params):
|
| 39 |
+
if not params.avoid_earnings or not chain.next_earnings:
|
| 40 |
+
return True, ""
|
| 41 |
+
earn = chain.next_earnings
|
| 42 |
+
exps = {l.expiry for l, _ in candidate.legs}
|
| 43 |
+
for e in exps:
|
| 44 |
+
if earn <= e: # earnings fall inside the trade's life
|
| 45 |
+
return False, f"earnings {earn} inside trade window (expiry {e})"
|
| 46 |
+
return True, ""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def scan_symbol(provider, symbol, params, max_expiries=5):
|
| 50 |
+
chain = fetch_chain(provider, symbol, max_expiries)
|
| 51 |
+
if not chain.quotes or chain.spot <= 0:
|
| 52 |
+
return symbol, [], f"empty chain"
|
| 53 |
+
horizon = chain.expirations(min_dte=params.min_dte, max_dte=params.max_dte)[0]
|
| 54 |
+
candidates = []
|
| 55 |
+
for builder in ALL_BUILDERS:
|
| 56 |
+
for cand in builder(chain, params):
|
| 57 |
+
# risk metrics on the earliest short-expiry horizon
|
| 58 |
+
cand.risk_metrics(chain, min(l.expiry for l, _ in cand.legs))
|
| 59 |
+
ok, why = passes_liquidity(cand, params.min_oi, params.max_rel_spread)
|
| 60 |
+
if not ok:
|
| 61 |
+
cand.reasons.append(f"rejected: {why}")
|
| 62 |
+
continue
|
| 63 |
+
ok, why = passes_defined_risk(cand, params.allow_undefined_risk)
|
| 64 |
+
if not ok:
|
| 65 |
+
cand.reasons.append(f"rejected: {why}")
|
| 66 |
+
continue
|
| 67 |
+
if cand.max_loss * 100.0 > params.account_size * params.max_buying_power_pct / 100.0:
|
| 68 |
+
cand.reasons.append(
|
| 69 |
+
f"rejected: BPE ${cand.max_loss * 100:.0f} > "
|
| 70 |
+
f"{params.max_buying_power_pct:.0f}% of ${params.account_size:,.0f}")
|
| 71 |
+
continue
|
| 72 |
+
ok, why = earnings_gate_ok(chain, cand, params)
|
| 73 |
+
if not ok:
|
| 74 |
+
cand.reasons.append(f"rejected: {why}")
|
| 75 |
+
continue
|
| 76 |
+
if cand.net_credit < 0 and cand.max_profit <= 0:
|
| 77 |
+
continue
|
| 78 |
+
score(cand)
|
| 79 |
+
candidates.append(cand)
|
| 80 |
+
# keep the best few per symbol, annotated
|
| 81 |
+
candidates.sort(key=lambda c: c.score, reverse=True)
|
| 82 |
+
for c in candidates:
|
| 83 |
+
c.reasons.append(f"chain liquidity {chain.liquidity_score(min(l.expiry for l, _ in c.legs)):.0f}/100, "
|
| 84 |
+
f"ATM IV {chain.iv30:.0%}, spot {chain.spot:g}, earnings {chain.next_earnings or 'n/a'}")
|
| 85 |
+
return symbol, candidates[:params.max_candidates_per_symbol], ""
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def to_row(symbol, c):
|
| 89 |
+
notes = c.notes
|
| 90 |
+
if "Backspread" in c.name:
|
| 91 |
+
notes += " | max profit unbounded above; reported value is at the +60% grid boundary"
|
| 92 |
+
return {
|
| 93 |
+
"symbol": symbol, "strategy": c.name, "view": c.view,
|
| 94 |
+
"net_credit_debit": round(c.net_credit, 2), "credit_debit_usd": round(c.net_credit * 100, 2),
|
| 95 |
+
"max_profit_usd": round(c.max_profit * 100, 2), "max_loss_usd": round(c.max_loss * 100, 2),
|
| 96 |
+
"pop_pct": round(c.pop * 100, 1), "score": c.score,
|
| 97 |
+
"breakevens": ",".join(str(b) for b in c.breakevens),
|
| 98 |
+
"legs": " ; ".join(l.label() for l, _ in c.legs),
|
| 99 |
+
"notes": notes, "reasons": " | ".join(c.reasons),
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main(argv=None):
|
| 104 |
+
ap = argparse.ArgumentParser(prog="options-scanner")
|
| 105 |
+
ap.add_argument("--symbols", default="", help="comma-separated watchlist; empty = auto")
|
| 106 |
+
ap.add_argument("--provider", default=None, choices=["alpaca", "tradier", "polygon", "yfinance"])
|
| 107 |
+
ap.add_argument("--auto-top", type=int, default=10, help="universe size when auto-picking")
|
| 108 |
+
ap.add_argument("--max-expiries", type=int, default=5)
|
| 109 |
+
ap.add_argument("--account-size", type=float, default=25000.0)
|
| 110 |
+
ap.add_argument("--risk-pct", type=float, default=5.0)
|
| 111 |
+
ap.add_argument("--output", default="results.json")
|
| 112 |
+
ap.add_argument("--csv", default="")
|
| 113 |
+
ap.add_argument("--allow-undefined-risk", action="store_true",
|
| 114 |
+
help="admit naked straddles/strangles (NOT recommended)")
|
| 115 |
+
args = ap.parse_args(argv)
|
| 116 |
+
|
| 117 |
+
params = RiskParams(account_size=args.account_size, max_buying_power_pct=args.risk_pct,
|
| 118 |
+
allow_undefined_risk=args.allow_undefined_risk)
|
| 119 |
+
provider = get_provider(args.provider)
|
| 120 |
+
print(f"[scan] provider={provider.name} account=${params.account_size:,.0f} "
|
| 121 |
+
f"max risk/trade={params.max_buying_power_pct:.0f}%", flush=True)
|
| 122 |
+
|
| 123 |
+
if args.symbols:
|
| 124 |
+
universe = [s.strip().upper() for s in args.symbols.split(",") if s.strip()]
|
| 125 |
+
else:
|
| 126 |
+
universe = auto_universe()
|
| 127 |
+
|
| 128 |
+
results, errors = [], []
|
| 129 |
+
started = time.time()
|
| 130 |
+
for sym in universe:
|
| 131 |
+
try:
|
| 132 |
+
sym, cands, err = scan_symbol(provider, sym, params, args.max_expiries)
|
| 133 |
+
if err:
|
| 134 |
+
errors.append({"symbol": sym, "error": err})
|
| 135 |
+
print(f"[scan] {sym}: {err}", flush=True)
|
| 136 |
+
elif cands:
|
| 137 |
+
print(f"[scan] {sym}: {len(cands)} candidates "
|
| 138 |
+
f"(best {cands[0].name} score {cands[0].score})", flush=True)
|
| 139 |
+
for c in cands:
|
| 140 |
+
results.append(to_row(sym, c))
|
| 141 |
+
except Exception as e:
|
| 142 |
+
errors.append({"symbol": sym, "error": str(e)[:200]})
|
| 143 |
+
print(f"[scan] {sym}: ERROR {e}", flush=True)
|
| 144 |
+
time.sleep(0.4) # be polite to the free endpoint
|
| 145 |
+
|
| 146 |
+
results.sort(key=lambda r: r["score"], reverse=True)
|
| 147 |
+
payload = {
|
| 148 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 149 |
+
"provider": provider.name,
|
| 150 |
+
"universe_size": len(universe),
|
| 151 |
+
"scanned": len(universe) - len(errors),
|
| 152 |
+
"params": {
|
| 153 |
+
"account_size": params.account_size,
|
| 154 |
+
"max_buying_power_pct": params.max_buying_power_pct,
|
| 155 |
+
"credit_short_delta": params.credit_short_delta,
|
| 156 |
+
"condor_short_delta": params.condor_short_delta,
|
| 157 |
+
"min_oi": params.min_oi, "max_rel_spread": params.max_rel_spread,
|
| 158 |
+
"allow_undefined_risk": params.allow_undefined_risk,
|
| 159 |
+
"avoid_earnings": params.avoid_earnings,
|
| 160 |
+
},
|
| 161 |
+
"top_candidates": results,
|
| 162 |
+
"errors": errors,
|
| 163 |
+
"runtime_seconds": round(time.time() - started, 1),
|
| 164 |
+
}
|
| 165 |
+
with open(args.output, "w") as f:
|
| 166 |
+
json.dump(payload, f, indent=1)
|
| 167 |
+
print(f"[scan] wrote {args.output}: {len(results)} candidates, "
|
| 168 |
+
f"{len(errors)} errors, {payload['runtime_seconds']}s", flush=True)
|
| 169 |
+
if args.csv:
|
| 170 |
+
if results:
|
| 171 |
+
with open(args.csv, "w", newline="") as f:
|
| 172 |
+
w = csv.DictWriter(f, fieldnames=list(results[0].keys()))
|
| 173 |
+
w.writeheader()
|
| 174 |
+
w.writerows(results)
|
| 175 |
+
print(f"[scan] wrote {args.csv}", flush=True)
|
| 176 |
+
return 0
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
sys.exit(main())
|