# Watchlist IV rank screen: Your watchlist ranked by IV rank in one call, with the names worth selling premium on at the top.
# https://apexvol.com/developers/recipes/watchlist-iv-rank-screen
import os
import sys

import requests

# One token, any paid or trial plan: Account, then API Access.
TOKEN = os.environ.get("APEXVOL_API_TOKEN") or sys.exit("set APEXVOL_API_TOKEN")
BASE = os.environ.get("APEXVOL_API_URL", "https://apexvol.com") + "/api/mcp/data"
S = requests.Session()
S.headers["Authorization"] = f"Bearer {TOKEN}"


def get(path, **params):
    r = S.get(BASE + path, params=params, timeout=90)
    body = r.json()
    if not body.get("success"):
        sys.exit(f"{path}: HTTP {r.status_code}: {body.get('error')}")
    return body["data"]


WATCHLIST = "NVDA,AMD,TSLA,AVGO,MU,PLTR,COIN,NFLX,CRWD,SMCI"
data = get("/batch/iv-rank", tickers=WATCHLIST)

rows = sorted(data["results"].items(), key=lambda kv: -(kv[1].get("iv_rank") or 0))
print(f"{'':7}{'IV rank':>8}{'IV pct':>8}{'IV 30d':>8}{'52w low':>9}{'52w high':>10}  read")
for sym, d in rows:
    rank = d.get("iv_rank") or 0
    read = "rich: lean to selling" if rank >= 50 else ("cheap: lean to buying" if rank <= 20 else "middle: no edge")
    print(f"{sym:7}{rank:>8.1f}{(d.get('iv_percentile') or 0):>8.1f}{d['current_iv']:>8.1f}"
          f"{d['iv_min_52w']:>9.1f}{d['iv_max_52w']:>10.1f}  {read}")
for sym, err in data["errors"].items():
    print(f"{sym:7} {err}")
print()
print("IV rank places today's 30-day implied vol inside its 52-week range; percentile is the share of days below it.")
