# Portfolio Greeks check: Net delta, theta and vega for a small book, then the same book through the standard stress scenarios.
# https://apexvol.com/developers/recipes/portfolio-greeks-check
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"]


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

put = get("/options-by-delta/SPY", delta=0.30, option_type="put")
spot = put["stock_price"]
positions = [
    {"ticker": "SPY", "position_type": "STOCK", "quantity": 100, "current_price": spot},
    {"ticker": "SPY", "position_type": "PUT", "quantity": -1, "strike": put["strike"],
     "expiration": put["expiration"], "current_price": put["mid"],
     "delta": -abs(put["actual_delta"]), "iv": put["iv"]},
]
greeks = post("/portfolio-greeks", {"positions": positions})
ps = greeks["portfolio_summary"]
print(f"Book: long 100 SPY at {spot:,.2f}, short 1 SPY {put['strike']:,.0f} put {put['expiration']} at {put['mid']:.2f}")
print(f"net delta {ps['total_delta']:,.1f}   theta {ps['total_theta']:,.2f}/day   vega {ps['total_vega']:,.1f}   "
      f"value ${ps['total_value']:,.0f}   risk {ps['risk_level']}")
print()
stress = post("/stress-tests", {"positions": positions})
print(f"{'scenario':26}{'stock':>7}{'IV':>6}{'days':>5}{'P&L $':>11}{'P&L %':>8}")
for sc in stress["scenarios"]:
    print(f"{sc['scenario_name']:26}{sc['stock_move_pct']:>+7.0f}{sc['iv_change_pct']:>+6.0f}{sc['days_forward']:>5}"
          f"{sc['estimated_pnl']:>11,.0f}{sc['estimated_pnl_pct']:>8.1f}")
