# Term structure watch: Front versus back implied vol for a few names, flagging the ones in backwardation.
# https://apexvol.com/developers/recipes/term-structure-watch
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"]


SYMBOLS = ["SPY", "NVDA", "TSLA"]
for sym in SYMBOLS:
    d = get(f"/term-structure/{sym}", num_expirations=6)
    ts = [r for r in d["term_structure"] if r.get("atm_iv")]
    if len(ts) < 2:
        print(f"{sym}: fewer than two priced expirations")
        continue
    slope = ts[-1]["atm_iv"] - ts[0]["atm_iv"]
    shape = "backwardation (front richer)" if slope < 0 else "contango (back richer)"
    print(f"{sym} spot {d['stock_price']:,.2f}: {shape}, slope {slope:+.1f} vol pts "
          f"from {ts[0]['expiration']} to {ts[-1]['expiration']}")
    for r in ts[:4]:
        print(f"   {r['expiration']}  {r['dte']:>3}d  ATM IV {r['atm_iv']:>5.1f}%  straddle {r['straddle_price']:>7.2f}  "
              f"move {r['expected_move_pct']:.2f}%")
    print()
