"""Translate a multi-asset allocation into EUR, estimate historical VaR and Expected Shortfall, and inspect high-VIX observations.

Research example. Live observations can change.
"""

from datetime import UTC, datetime
from decimal import Decimal
from textwrap import fill

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

AS_OF = datetime.now(UTC).date()
NAVY, BLUE, PINK = "#132244", "#8fb9ff", "#e7a2cc"


def fetch(qj):
    return {
        "prices": qj.domains.call(
            "equity.pricing.get_historical_prices",
            provider="eod",
            symbols=["SPY", "TLT", "GLD", "DBC", "UUP"],
            start_date="2020-01-01",
            end_date="2025-12-31",
            frequency="1d",
        ),
        "ecb_fx": qj.domains.call(
            "macro.eu.get_ecb_series",
            provider="ecb",
            series_id="EXR.D.USD.EUR.SP00.A",
            start_date="2020-01-01",
            end_date="2025-12-31",
        ),
        "vix_history": qj.domains.call(
            "macro.indicators.get_fred_data_series_by_id",
            provider="fred",
            search_id="VIXCLS",
            start="2020-01-01",
            end="2025-12-31",
        ),
    }


def analyze(raw):
    usd = portfolio_returns(raw).rename("USD return")
    # Use exact daily FX boundaries; do not fill missing reference rates.
    fx = frame(raw["ecb_fx"]).set_index("date")["value"].map(decimal).reindex(usd.index)
    fx_change = change(fx)
    euro = ((1 + usd) / (1 + fx_change) - 1).rename("EUR return")
    vix = macro(raw["vix_history"], "VIXCLS").reindex(usd.index).shift(1).rename("Prior VIX")
    data = pd.concat([usd, euro, vix], axis=1).dropna()
    if len(data) < 252:
        raise ValueError("Insufficient common portfolio, FX and VIX observations")
    stressed = data.loc[data["Prior VIX"] >= data["Prior VIX"].quantile(0.85), "EUR return"]
    rows = []
    for name, returns in [("USD", data["USD return"]), ("EUR", data["EUR return"]), ("EUR · high VIX", stressed)]:
        losses = -returns.to_numpy()
        var = np.quantile(losses, 0.95)
        es = losses[losses >= var].mean()
        rows.append(
            {"Sample": name, "95% VaR %": 100 * var, "Expected shortfall %": 100 * es, "Observations": len(losses)}
        )
    result = pd.DataFrame(rows)
    fig, (top, bottom) = canvas("Portfolio · currency and tail risk", "Observed daily loss frequency", panels=2)
    for column, label in [("USD return", "USD investor"), ("EUR return", "EUR investor")]:
        top.hist(-100 * data[column], bins=65, histtype="step", lw=1.7, label=label)
    top.set_xlabel("One-day loss %")
    legend(top)
    x = np.arange(len(result))
    bottom.bar(x - 0.18, result["95% VaR %"], 0.36, label="95% VaR")
    bottom.bar(x + 0.18, result["Expected shortfall %"], 0.36, label="Expected shortfall")
    bottom.set_xticks(x, result["Sample"])
    bottom.set_ylabel("Historical one-day loss %")
    legend(bottom)
    return result, fig


def payload(response):
    if hasattr(response, "to_dict"):
        response = response.to_dict()
    while isinstance(response, dict):
        if response.get("error") or response.get("error_code") or response.get("success") is False:
            raise ValueError("Provider request failed")
        if "data" in response:
            response = response["data"]
        elif "value" in response:
            response = response["value"]
        else:
            break
    return response


def frame(response, date="date"):
    rows = payload(response)
    if not isinstance(rows, list) or not rows:
        raise ValueError("No provider observations returned")
    result = pd.DataFrame(rows)
    if date:
        result[date] = pd.to_datetime(result[date], utc=True)
        result = result.sort_values(date)
    return result


def decimal(value):
    if pd.isna(value):
        raise ValueError("Required monetary value or quantity is missing")
    return Decimal(str(value))


def ratio(numerator, denominator):
    denominator = decimal(denominator)
    if denominator == 0:
        raise ValueError("Required denominator is zero")
    return float(decimal(numerator) / denominator)


def change(values, periods=1):
    previous = values.shift(periods)
    return pd.Series(
        [ratio(x, y) - 1 if pd.notna(x) and pd.notna(y) else np.nan for x, y in zip(values, previous, strict=True)],
        index=values.index,
    )


def history(response, symbol, adjusted=True):
    values = payload(response)
    if not isinstance(values, dict) or symbol not in values:
        raise ValueError(f"No price coverage for {symbol}")
    result = frame(values[symbol]).set_index("date")
    field = "adjusted_close" if adjusted else "close"
    result["price"] = result[field].map(decimal)
    result["volume"] = result["volume"].map(decimal)
    if result.index.has_duplicates:
        raise ValueError("Duplicate trading dates")
    return result


def macro(response, column):
    values = frame(response).set_index("date")[column]
    values = pd.to_numeric(values, errors="coerce").dropna()
    if values.empty:
        raise ValueError(f"No numeric observations for {column}")
    return values


def canvas(title, ylabel, panels=1):
    plt.rcParams.update(
        {
            "figure.facecolor": NAVY,
            "axes.facecolor": NAVY,
            "savefig.facecolor": NAVY,
            "text.color": "#e9eef8",
            "axes.labelcolor": "#afc1dc",
            "xtick.color": "#afc1dc",
            "ytick.color": "#afc1dc",
            "axes.edgecolor": "#34486b",
            "grid.color": "#34486b",
            "font.size": 10,
            "axes.prop_cycle": plt.cycler(color=[BLUE, PINK, "#ba9dea"]),
        }
    )
    fig, axes = plt.subplots(panels, 1, figsize=(9, 6.1), squeeze=False, layout="constrained")
    fig.suptitle(fill(title, width=58), fontsize=17, x=0.04, ha="left", weight="medium")
    for ax in axes.flat:
        ax.grid(axis="y", alpha=0.45)
        ax.set_axisbelow(True)
        ax.spines[["top", "right"]].set_visible(False)
    axes.flat[0].set_ylabel(ylabel)
    return fig, list(axes.flat)


def legend(ax):
    ax.legend(frameon=False, labelcolor="#e9eef8", fontsize=9)


def run():
    from quantjourney.sdk import QuantJourneyAPI

    qj = QuantJourneyAPI.from_env()
    raw = fetch(qj)
    table, fig = analyze(raw)
    print(table.to_string(index=False))
    fig.savefig(OUTPUT, dpi=180)
    plt.show()


def portfolio_returns(raw):
    weights = {
        "SPY": Decimal("0.42"),
        "TLT": Decimal("0.22"),
        "GLD": Decimal("0.14"),
        "DBC": Decimal("0.12"),
        "UUP": Decimal("0.10"),
    }
    if sum(weights.values()) != Decimal(1):
        raise ValueError("Portfolio weights must sum to one")
    returns = pd.DataFrame({symbol: change(history(raw["prices"], symbol)["price"]) for symbol in weights}).dropna()
    if len(returns) < 252:
        raise ValueError("Need at least one year of common daily portfolio observations")
    return returns.dot(pd.Series({symbol: float(weight) for symbol, weight in weights.items()}))


OUTPUT = "sdk_portfolio_var.png"

if __name__ == "__main__":
    run()
