"""PRISM Forecasting API — Python quick start.
Docs: https://www.prismforecasting.com/api.php

1) Get your API key: sign in at www.prismforecasting.com -> My account -> API access
   (API access is included from the Quant plan).
2) pip install requests
3) Put your key below and run:  python prism_api_example.py
"""
import csv
import sys

import requests

API_KEY = "pk_PASTE_YOUR_KEY_HERE"          # <- your key from My account -> API access
BASE    = "https://www.prismforecasting.com"

SYMBOLS    = ["XAUUSD", "XAGUSD", "EURUSD", "GBPUSD", "USDJPY", "USDCHF",
              "NZDUSD", "US500", "US30", "WTI", "BTCUSD"]
TIMEFRAMES = ["M15", "H1", "H4", "D1"]       # 192 / 48 / 12 / 2 candles = the same 2 days


def get_forecast(symbol: str, timeframe: str = "H1") -> dict:
    """One API call -> the full forecast for a symbol/timeframe as a dict.

    Response shape:
      {
        "symbol": "XAUUSD", "timeframe": "H1",
        "anchor_utc": "2026-07-04T23:00:00Z",      # forecast start ("now" at prediction time)
        "horizon_hours": 48,
        "candles": [                                # first candle = currently forming bar
          {"t": "...Z", "kind": "forming"|"future",
           "o":..., "h":..., "l":..., "c":...,      # predicted OHLC (online-source price basis)
           "dir_prob": 0.46,                        # P(candle closes above the anchor price)
           "sigma": 8.41},                          # model confidence, +- price units
          ...
        ],
        "summary": {"bias_pct": -0.52,              # predicted % move to end of horizon
                    "p_up_end": 0.29,               # P(price above today's level in 2 days)
                    "confidence_sigma": 4.12}
      }
    """
    r = requests.get(
        f"{BASE}/v1/forecast",
        params={"symbol": symbol, "timeframe": timeframe},
        headers={"Authorization": f"Bearer {API_KEY}"},
        timeout=20,
    )
    if r.status_code in (401, 403):
        sys.exit(f"Access problem ({r.status_code}): {r.json().get('error')}")
    r.raise_for_status()
    return r.json()


def demo():
    fc = get_forecast("XAUUSD", "H1")
    s = fc["summary"]
    print(f"{fc['symbol']} {fc['timeframe']}  anchored {fc['anchor_utc']}  ({fc['model']})")
    print(f"  bias to horizon end : {s['bias_pct']:+.2f}%")
    print(f"  P(up in 2 days)     : {s['p_up_end']:.0%}")
    print(f"  mean confidence     : +-{s['confidence_sigma']}")
    print()
    print("  first 5 predicted candles:")
    for c in fc["candles"][:5]:
        print(f"    {c['t']}  {c['kind']:<7}  O {c['o']:>10.2f}  H {c['h']:>10.2f}  "
              f"L {c['l']:>10.2f}  C {c['c']:>10.2f}  P(up) {c['dir_prob']:.0%}  ±{c['sigma']:.2f}")

    # save the whole forecast as CSV — ready for pandas / Excel / a backtest
    out = f"prism_{fc['symbol']}_{fc['timeframe']}.csv"
    with open(out, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(fc["candles"][0].keys()))
        w.writeheader()
        w.writerows(fc["candles"])
    print(f"\n  full forecast saved to {out}")


if __name__ == "__main__":
    demo()
