Source code · Python

pricing.py

124 lines · Part of ES trading: edge and risk · All code · Read only; the files run as published

"""One option, several prices: a one-week put on the ES contract. ES options are options on the futures contract, so Black-76 applies (thequarterly options are American-style, but early exercise is worth almostnothing on a one-week futures option; the weeklies are European). The sameput is priced with the volatility each model gives, and once by simulationfrom the fitted GJR-GARCH with skewed Student t errors (the one model thatpasses every VaR backtest in market_risk.py), which has fat tails, negativeskew and a bigger response to falls than to rises. The spread between theprices is the model risk."""import math import numpy as npfrom arch import arch_modelfrom arch.univariate import SkewStudentfrom scipy import optimize, stats POINT = 50DAYS = 5            # trading days to expiryCAL_DAYS = 7        # calendar days to expirySIMS = 200000MONTH = 21          # trading days in the path chartsPATH_SIMS = 50000   # simulations behind the path bands and distributionsSHOW = 60           # paths drawn individually  def black76_put(f: float, k: float, t: float, r: float, vol: float) -> float:    d1 = (math.log(f / k) + 0.5 * vol ** 2 * t) / (vol * math.sqrt(t))    d2 = d1 - vol * math.sqrt(t)    return math.exp(-r * t) * (k * stats.norm.cdf(-d2) - f * stats.norm.cdf(-d1))  def implied_vol(price: float, f: float, k: float, t: float, r: float) -> float:    return optimize.brentq(lambda v: black76_put(f, k, t, r, v) - price, 1e-4, 5.0)  def month_paths(res, futures: float, realised: float, vix: float) -> dict:    """One month (21 trading days) of ES price paths under three views of risk,    for the path charts: normal returns at the last year's volatility, normal    returns at the VIX, and the fitted GJR-GARCH with skewed t, started from its    state on the pricing date. Drift is removed from all three, so only the    shape of risk differs."""    rng = np.random.default_rng(21)    out = {}    garch = res.forecast(horizon=MONTH, method="simulation", simulations=PATH_SIMS, reindex=False,                         random_state=np.random.RandomState(21)).simulations.values[-1]    daily = {        "constant": rng.standard_normal((PATH_SIMS, MONTH)) * realised / math.sqrt(252) * 100,        "vix": rng.standard_normal((PATH_SIMS, MONTH)) * vix / math.sqrt(252) * 100,        "garch": garch - res.params["mu"],    }    labels = {"constant": f"Normal, last year's volatility ({realised:.1%})",              "vix": f"Normal, VIX ({vix:.1%})",              "garch": "GJR-GARCH, skewed t"}    total = {k: v.sum(axis=1) for k, v in daily.items()}    lo = min(np.percentile(t, 0.1) for t in total.values())    hi = max(np.percentile(t, 99.9) for t in total.values())    edges = np.linspace(lo, hi, 61)    for k, v in daily.items():        level = futures * np.exp(np.concatenate([np.zeros((PATH_SIMS, 1)), np.cumsum(v, axis=1)], axis=1) / 100)        t = total[k]        out[k] = {            "label": labels[k],            "paths": level[:SHOW].round(2).tolist(),            "bands": {str(q): row.round(2).tolist() for q, row in zip((5, 50, 95), np.percentile(level, (5, 50, 95), axis=0))},            "counts": np.histogram(np.clip(t, lo, hi), edges)[0].tolist(),            "p1_pct": float(np.expm1(np.percentile(t, 1) / 100)),            "p_down_10": float((t < 100 * math.log(0.9)).mean()),            "sd_pct": float(t.std() / 100),        }    return {"days": MONTH, "sims": PATH_SIMS, "start": futures, "edges_pct": np.expm1(edges / 100).round(5).tolist(), "models": out}  def price_put(r_pct, futures: float, vix: float, rf: float, as_of: str) -> dict:    """r_pct: daily S&P 500 log returns in percent up to the pricing date."""    t = CAL_DAYS / 365    strikes = {"At the money": round(futures / 5) * 5, "3% out of the money": round(futures * 0.97 / 5) * 5}     res = arch_model(r_pct, mean="Constant", vol="GARCH", p=1, o=1, q=1, dist="skewt").fit(disp="off")    p = res.params    fc = res.forecast(horizon=DAYS, reindex=False)    garch_week = math.sqrt(fc.variance.iloc[-1].mean() * 252) / 100    long_run = math.sqrt(p["omega"] / (1 - p["alpha[1]"] - p["gamma[1]"] / 2 - p["beta[1]"]) * 252) / 100    realised = float(r_pct.iloc[-252:].std() * math.sqrt(252) / 100)     sim = res.forecast(horizon=DAYS, method="simulation", simulations=SIMS, reindex=False,                       random_state=np.random.RandomState(11))    week = sim.simulations.values[-1].sum(axis=1) / 100    week = week - np.log(np.mean(np.exp(week)))  # the futures price is a martingale under the pricing measure     vols = {        "Constant volatility (last 252 days)": realised,        "GARCH long-run volatility": long_run,        "GJR-GARCH forecast for the week": garch_week,        "VIX (market implied, 30 days)": vix / 100,    }    rows = []    for name, v in vols.items():        rows.append({"model": name, "vol": v, **{            label: {"pts": black76_put(futures, k, t, rf, v), "usd": black76_put(futures, k, t, rf, v) * POINT}            for label, k in strikes.items()}})    mc = {"model": "Simulated GJR-GARCH paths (fat tails, skew)", "vol": None}    for label, k in strikes.items():        pts = math.exp(-rf * t) * np.maximum(k - futures * np.exp(week), 0).mean()        mc[label] = {"pts": float(pts), "usd": float(pts * POINT), "implied_vol": implied_vol(pts, futures, k, t, rf)}    rows.append(mc)     # One-day 99% VaR for one contract held overnight, constant versus GARCH.    z99 = stats.norm.ppf(0.01)    q_s = float(SkewStudent().ppf(0.01, p[["eta", "lambda"]].to_numpy()))    sd250 = r_pct.iloc[-250:].std()    g1 = math.sqrt(fc.variance.iloc[-1]["h.1"])    var = {        "Normal, constant volatility": -math.expm1(z99 * sd250 / 100) * futures * POINT,        "GJR-GARCH, skewed t": -math.expm1((p["mu"] + q_s * g1) / 100) * futures * POINT,    }    return {        "as_of": as_of, "futures": futures, "strikes": strikes, "days": DAYS, "calendar_days": CAL_DAYS, "rf": rf, "sims": SIMS,        "rows": rows, "var_1d_99_usd": var,        "paths": month_paths(res, futures, realised, vix / 100),        "spread_atm_pct": (max(x["At the money"]["usd"] for x in rows) / min(x["At the money"]["usd"] for x in rows) - 1),        "spread_otm_pct": (max(x["3% out of the money"]["usd"] for x in rows) / min(x["3% out of the money"]["usd"] for x in rows) - 1),    }