"""Discrete delta hedging of a short call under simulated Heston paths.

Reproduces the tables in "04 换一个模型，对冲会怎样变？".  The same
simulated paths are hedged with five different hedge ratios:

  * three Black--Scholes rules that differ only in the assumed skew
    stickiness ratio R (0: sticky moneyness, 1: sticky strike, 2: the
    short-maturity local-volatility value);
  * the Heston spot delta with the variance state treated as observed;
  * the Heston minimum-variance delta.

The data-generating process is Heston with P = Q (no volatility risk
premium), so that the option is sold at its model value and every hedge
starts from the same premium.  Run:  python heston_hedging_experiment.py
Requires numpy.
"""

from __future__ import annotations

import numpy as np
from math import erf, exp, log, sqrt

PARAMS = dict(s0=100.0, v0=0.04, kappa=2.0, theta=0.04, xi=0.6, rho=-0.7,
              rate=0.02, dividend=0.0)
STRIKE, MATURITY, DAYS_PER_YEAR = 100.0, 0.25, 252
N_PATHS, SUBSTEPS, SEED = 4000, 8, 20261125

# Gauss--Legendre nodes on (0, Y] in a scaled variable y = u * sqrt(w),
# where w approximates the integrated variance.  A fixed cutoff in u fails at
# short maturities and low variance (the integrand then decays very slowly),
# so every path gets its own cutoff U = Y / sqrt(w), with w the expected
# integrated variance (floored).  The scheme is checked against a dense
# trapezoid reference in check_pricer().
_Y_MAX, _N_NODES, _W_SMALL = 12.0, 1024, 1e-7
_x, _w = np.polynomial.legendre.leggauss(_N_NODES)
Y_NODES = 0.5 * _Y_MAX * (_x + 1.0)
Y_WEIGHTS = 0.5 * _Y_MAX * _w


def _cf_parts(u, tau, kappa, theta, xi, rho):
    # u may be any complex array; broadcasting follows numpy rules
    """C(u, tau) and D(u, tau) of the Heston log-price characteristic function."""
    iu = 1j * u
    b = kappa - rho * xi * iu
    d = np.sqrt(b * b + xi * xi * (iu + u * u))
    g = (b - d) / (b + d)
    e = np.exp(-d * tau)
    C = kappa * theta / xi**2 * ((b - d) * tau - 2.0 * np.log((1.0 - g * e) / (1.0 - g)))
    D = (b - d) / xi**2 * (1.0 - e) / (1.0 - g * e)
    return C, D


def heston_call(s, v, tau, strike=STRIKE, p=PARAMS):
    """Heston call price and spot delta, vectorised over arrays s and v."""
    s = np.atleast_1d(np.asarray(s, float))
    v = np.atleast_1d(np.asarray(v, float))
    s, v = np.broadcast_arrays(s, v)
    r, q = p["rate"], p["dividend"]
    if tau <= 0.0:
        return np.maximum(s - strike, 0.0), (s > strike).astype(float)
    kappa, theta = p["kappa"], p["theta"]
    # expected integrated variance E[int_t^T v_s ds | v_t = v]
    w_int = theta * tau + (v - theta) * (1.0 - exp(-kappa * tau)) / kappa
    w_safe = np.maximum(w_int, _W_SMALL)
    scale = 1.0 / np.sqrt(w_safe)                     # (N,)
    u = scale[:, None] * Y_NODES[None, :]              # (N, M)
    wts = scale[:, None] * Y_WEIGHTS[None, :]
    lnk = log(strike)
    C2, D2 = _cf_parts(u, tau, p["kappa"], p["theta"], p["xi"], p["rho"])
    C1, D1 = _cf_parts(u - 1j, tau, p["kappa"], p["theta"], p["xi"], p["rho"])
    x = np.log(s)[:, None] + (r - q) * tau
    phi2 = np.exp(1j * u * x + C2 + D2 * v[:, None])
    # phi(u - i) / phi(-i): the stock-measure characteristic function
    phi1 = np.exp(1j * (u - 1j) * x + C1 + D1 * v[:, None] - x)
    kern = np.exp(-1j * u * lnk) / (1j * u)
    p1 = 0.5 + np.sum(np.real(kern * phi1) * wts, axis=1) / np.pi
    p2 = 0.5 + np.sum(np.real(kern * phi2) * wts, axis=1) / np.pi
    price = s * exp(-q * tau) * p1 - strike * exp(-r * tau) * p2
    delta = exp(-q * tau) * p1
    return price, delta


def heston_vega_v(s, v, tau, h=1e-4):
    """dV/dv by central differences in the variance state."""
    up, _ = heston_call(s, v + h, tau)
    dn, _ = heston_call(s, np.maximum(v - h, 1e-8), tau)
    return (up - dn) / (2.0 * h)


def _ncdf(x):
    return 0.5 * (1.0 + np.vectorize(erf)(np.asarray(x) / sqrt(2.0)))


def bs_call(s, k, tau, r, q, sig):
    s = np.asarray(s, float)
    sig = np.asarray(sig, float)
    st = sig * np.sqrt(tau)
    d1 = (np.log(s / k) + (r - q + 0.5 * sig * sig) * tau) / st
    return s * np.exp(-q * tau) * _ncdf(d1) - k * np.exp(-r * tau) * _ncdf(d1 - st)


def bs_delta_vega(s, k, tau, r, q, sig):
    s = np.asarray(s, float)
    st = sig * np.sqrt(tau)
    d1 = (np.log(s / k) + (r - q + 0.5 * sig * sig) * tau) / st
    pdf = np.exp(-0.5 * d1 * d1) / sqrt(2.0 * np.pi)
    return np.exp(-q * tau) * _ncdf(d1), s * np.exp(-q * tau) * pdf * np.sqrt(tau)


def implied_vol(price, s, k, tau, r, q, lo=1e-4, hi=3.0):
    for _ in range(120):
        mid = 0.5 * (lo + hi)
        if bs_call(s, k, tau, r, q, mid) > price:
            hi = mid
        else:
            lo = mid
    return 0.5 * (lo + hi)


def smile_snapshot(tau, p=PARAMS, h=0.01):
    """ATM-forward implied vol, skew dsigma/dlnK and SSR implied by Heston at time 0."""
    s, v, r, q = p["s0"], p["v0"], p["rate"], p["dividend"]
    fwd = s * exp((r - q) * tau)

    def iv(k, var=v):
        price = heston_call(s, var, tau, strike=k)[0][0]
        return implied_vol(price, s, k, tau, r, q)

    atm = iv(fwd)
    skew = (iv(fwd * exp(h)) - iv(fwd * exp(-h))) / (2.0 * h)
    dv = 1e-4
    datm_dv = (iv(fwd, v + dv) - iv(fwd, v - dv)) / (2.0 * dv)
    # dsigma_ATM = (dsigma_ATM/dv) dv and Cov(dv, dlnS)/Var(dlnS) = rho * xi
    ssr = p["rho"] * p["xi"] * datm_dv / skew
    return atm, skew, ssr


def simulate_paths(p=PARAMS, n=N_PATHS, days=int(round(MATURITY * DAYS_PER_YEAR)),
                   substeps=SUBSTEPS, seed=SEED):
    """Full-truncation Euler; returns spot and variance on the hedge dates."""
    rng = np.random.default_rng(seed)
    dt = 1.0 / DAYS_PER_YEAR / substeps
    s = np.full(n, p["s0"])
    v = np.full(n, p["v0"])
    S, V = [s.copy()], [v.copy()]
    for _ in range(days):
        for _ in range(substeps):
            z1 = rng.standard_normal(n)
            z2 = p["rho"] * z1 + sqrt(1.0 - p["rho"] ** 2) * rng.standard_normal(n)
            vp = np.maximum(v, 0.0)
            s = s * np.exp((p["rate"] - p["dividend"] - 0.5 * vp) * dt + np.sqrt(vp * dt) * z1)
            v = v + p["kappa"] * (p["theta"] - vp) * dt + p["xi"] * np.sqrt(vp * dt) * z2
        S.append(s.copy())
        V.append(np.maximum(v, 0.0))
    return np.array(S), np.array(V)


def hedge_ratios(rule, s, v, tau, sigma0, skew, p=PARAMS):
    r, q = p["rate"], p["dividend"]
    if rule.startswith("R="):
        R = float(rule[2:])
        sig = np.maximum(sigma0 + (R - 1.0) * skew * np.log(s / p["s0"]), 1e-3)
        delta, vega = bs_delta_vega(s, STRIKE, tau, r, q, sig)
        return delta + vega * (R - 1.0) * skew / s
    _, delta = heston_call(s, v, tau)
    if rule == "heston":
        return delta
    if rule == "heston-mv":
        return delta + p["rho"] * p["xi"] / s * heston_vega_v(s, v, tau)
    raise ValueError(rule)


def run(rules=("R=0", "R=1", "R=2", "heston", "heston-mv"), p=PARAMS):
    S, V = simulate_paths(p)
    days = S.shape[0] - 1
    dt = 1.0 / DAYS_PER_YEAR
    premium = heston_call(p["s0"], p["v0"], MATURITY)[0][0]
    sigma0 = implied_vol(premium, p["s0"], STRIKE, MATURITY, p["rate"], p["dividend"])
    _, skew, _ = smile_snapshot(MATURITY, p)
    payoff = np.maximum(S[-1] - STRIKE, 0.0)
    results = {}
    states = {}
    for rule in rules:
        cash = np.full(S.shape[1], premium)
        held = np.zeros(S.shape[1])
        for i in range(days):
            tau = MATURITY - i * dt
            if rule.startswith("heston"):
                if i not in states:
                    states[i] = heston_call(S[i], V[i], tau)[1]
                target = states[i]
                if rule == "heston-mv":
                    target = target + p["rho"] * p["xi"] / S[i] * heston_vega_v(S[i], V[i], tau)
            else:
                target = hedge_ratios(rule, S[i], V[i], tau, sigma0, skew, p)
            cash -= (target - held) * S[i]
            held = target
            cash *= exp(p["rate"] * dt)
        pnl = cash + held * S[-1] - payoff
        results[rule] = pnl
    return premium, sigma0, skew, results


def check_pricer(cases=((0.0, 1 / 252, 100.0), (0.002, 0.02, 98.0), (0.04, 0.25, 102.0)), n=400001):
    """Compare heston_call with a dense trapezoid rule; returns max |error|."""
    p = PARAMS
    worst = 0.0
    for v, tau, s in cases:
        w = p["theta"] * tau + (v - p["theta"]) * (1 - exp(-p["kappa"] * tau)) / p["kappa"]
        u = np.linspace(1e-6, min(16.0 / sqrt(max(w, 1e-8)), 60000.0), n)
        C2, D2 = _cf_parts(u, tau, p["kappa"], p["theta"], p["xi"], p["rho"])
        C1, D1 = _cf_parts(u - 1j, tau, p["kappa"], p["theta"], p["xi"], p["rho"])
        x = log(s) + (p["rate"] - p["dividend"]) * tau
        kern = np.exp(-1j * u * log(STRIKE)) / (1j * u)
        p1 = 0.5 + np.trapezoid(np.real(kern * np.exp(1j * (u - 1j) * x + C1 + D1 * v - x)), u) / np.pi
        price, delta = heston_call(s, v, tau)
        worst = max(worst, abs(delta[0] - exp(-p["dividend"] * tau) * p1))
    return worst


if __name__ == "__main__":
    print(f"max delta error vs dense reference: {check_pricer():.2e}")
    for tau in (0.05, 0.25, 1.0):
        atm, skew, ssr = smile_snapshot(tau)
        print(f"T={tau:4.2f}  ATM IV {atm:.4f}  skew {skew:+.4f}  SSR {ssr:.3f}")
    premium, sigma0, skew, res = run()
    print(f"\npremium {premium:.4f}  sigma0 {sigma0:.4f}  skew {skew:+.4f}")
    print(f"{'rule':>10} {'mean':>8} {'std':>8} {'5%':>8} {'std/prem':>9}")
    for rule, pnl in res.items():
        print(f"{rule:>10} {pnl.mean():8.4f} {pnl.std():8.4f} "
              f"{np.quantile(pnl, .05):8.4f} {pnl.std() / premium:9.3f}")
