# Earnings-week straddles: This week's reporters with the market's implied move next to what they usually do.
# https://apexvol.com/developers/recipes/earnings-week-straddles
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"]


cal = get("/earnings-calendar", days_ahead=7)
rows = [r for r in cal["earnings"] if r.get("implied_move") and r.get("hist_avg_move")]
rows.sort(key=lambda r: -(r.get("market_cap") or 0))
rows = rows[:8]
if not rows:
    sys.exit("no priced reporters in the next seven days")

moves = get("/batch/expected-move", tickers=",".join(r["symbol"] for r in rows))
print(f"Earnings {cal['from_date']} to {cal['to_date']}, {cal['total_count']} reporters, largest {len(rows)} shown")
print()
print(f"{'':7}{'date':>11}{'timing':>8}{'implied %':>11}{'hist avg %':>12}{'ratio':>7}{'straddle move %':>17}")
for r in sorted(rows, key=lambda r: -(r.get("move_ratio") or 0)):
    em = moves["results"].get(r["symbol"]) or {}
    live = f"{em['expected_move_percent']:.2f}" if em else "n/a"
    print(f"{r['symbol']:7}{r['date']:>11}{(r.get('timing') or '?'):>8}{r['implied_move']:>11.2f}"
          f"{r['hist_avg_move']:>12.2f}{r['move_ratio']:>7.2f}{live:>17}")
print()
print("ratio = implied move over the average of past reported moves; above 1.2 the event is rich, below 0.8 cheap.")
