Source code · Python
market_risk.py
"""The market the trades sit in: ES risk, the FOMC filter and overnight gaps. Returns are daily log returns of the S&P 500 index (^GSPC), the index the EScontract is cash-settled against, in percent. Yahoo's continuous ES series(ES=F) is not back-adjusted, so it jumps at each quarterly roll; tracking()measures how closely the two move and how large the roll jumps are. Dollarfigures are for one ES contract at $50 per index point."""import math import numpy as npimport pandas as pdfrom arch import arch_modelfrom arch.univariate import SkewStudentfrom scipy import optimize, special, statsfrom statsmodels.stats.diagnostic import acorr_ljungbox, het_archfrom statsmodels.tsa.stattools import adfuller POINT = 50OOS_START = "2010-01-04" # first day of the out-of-sample VaR backtestREFIT = 21 # refit the GARCH models every 21 trading daysEVENT_START = "2008-01-02" # index opens are reliable from 2008 on Yahoo def log_returns(close: pd.Series) -> pd.Series: return (100 * np.log(close).diff()).dropna() # ---------------------------------------------------------------------------# Data checks# --------------------------------------------------------------------------- def third_fridays(years) -> list[pd.Timestamp]: out = [] for y in years: for m in (3, 6, 9, 12): first = pd.Timestamp(y, m, 1) out.append(first + pd.Timedelta(days=(4 - first.weekday()) % 7 + 14)) return out def tracking(es: pd.DataFrame, spx: pd.DataFrame) -> dict: r = pd.DataFrame({"es": log_returns(es.close), "spx": log_returns(spx.close)}).dropna().loc[OOS_START:] expiries = pd.DatetimeIndex(third_fridays(range(r.index[0].year, r.index[-1].year + 1))) gap = np.abs(r.index.values[:, None] - expiries.values[None, :]).min(axis=1) near = gap <= np.timedelta64(10, "D") d = (r.es - r.spx).abs() return { "days": len(r), "corr_all": float(r.es.corr(r.spx)), "corr_ex_roll": float(r[~near].es.corr(r[~near].spx)), "median_abs_diff_ex_roll": float(d[~near].median()), "roll_days_over_half_pct": int((d[near] > 0.5).sum()), "max_roll_jump": float(d[near].max()), "max_roll_jump_date": d[near].idxmax().date().isoformat(), } def pretests(r: pd.Series, close: pd.Series) -> dict: adf_p = adfuller(np.log(close.loc[r.index[0]:]), autolag="AIC") adf_r = adfuller(r, autolag="AIC") lb = acorr_ljungbox(r, lags=[10], return_df=True) lb2 = acorr_ljungbox(r ** 2, lags=[10], return_df=True) lm = het_arch(r, nlags=5) jb = stats.jarque_bera(r) return { "from": r.index[0].date().isoformat(), "to": r.index[-1].date().isoformat(), "days": len(r), "annual_vol": float(r.std() * math.sqrt(252)), "adf_log_price": {"stat": float(adf_p[0]), "p": float(adf_p[1])}, "adf_returns": {"stat": float(adf_r[0]), "p": float(adf_r[1])}, "ljung_box_returns_10": {"q": float(lb.lb_stat.iloc[0]), "p": float(lb.lb_pvalue.iloc[0])}, "ljung_box_squared_10": {"q": float(lb2.lb_stat.iloc[0]), "p": float(lb2.lb_pvalue.iloc[0])}, "arch_lm_5": {"lm": float(lm[0]), "p": float(lm[1])}, "jarque_bera": {"stat": float(jb.statistic), "p": float(jb.pvalue)}, "skew": float(stats.skew(r)), "excess_kurtosis": float(stats.kurtosis(r)), "worst_day": {"date": r.idxmin().date().isoformat(), "pct": float(np.expm1(r.min() / 100) * 100)}, } # ---------------------------------------------------------------------------# Volatility models# --------------------------------------------------------------------------- SPECS = { "GARCH(1,1), normal": dict(vol="GARCH", p=1, o=0, q=1, dist="normal"), "GARCH(1,1), Student t": dict(vol="GARCH", p=1, o=0, q=1, dist="t"), "GJR-GARCH(1,1), Student t": dict(vol="GARCH", p=1, o=1, q=1, dist="t"), "EGARCH(1,1), Student t": dict(vol="EGARCH", p=1, o=1, q=1, dist="t"), "GJR-GARCH(1,1), skewed t": dict(vol="GARCH", p=1, o=1, q=1, dist="skewt"),} def fit_family(r: pd.Series) -> tuple[dict, object]: rows, fits = [], {} for name, spec in SPECS.items(): res = arch_model(r, mean="Constant", **spec).fit(disp="off") fits[name] = res p = res.params if spec["vol"] == "EGARCH": persistence = float(p["beta[1]"]) else: persistence = float(p["alpha[1]"] + p["beta[1]"] + 0.5 * p.get("gamma[1]", 0.0)) rows.append({ "model": name, "loglik": float(res.loglikelihood), "aic": float(res.aic), "bic": float(res.bic), "alpha": float(p["alpha[1]"]), "gamma": float(p.get("gamma[1]", np.nan)), "beta": float(p["beta[1]"]), "nu": float(p.get("nu", p.get("eta", np.nan))), "persistence": persistence, "half_life_days": float(math.log(0.5) / math.log(persistence)) if persistence < 1 else None, }) best = min(rows, key=lambda x: x["bic"])["model"] return {"models": rows, "best_bic": best}, fits def residual_checks(res) -> dict: z = (res.resid / res.conditional_volatility).dropna() lb = acorr_ljungbox(z, lags=[10], return_df=True) lb2 = acorr_ljungbox(z ** 2, lags=[10], return_df=True) lm = het_arch(z, nlags=5) # Compare the standardised residuals with the fitted error distribution. if "lambda" in res.params: shape = res.params[["eta", "lambda"]].to_numpy() ks = stats.kstest(z, lambda v: SkewStudent().cdf(np.asarray(v), shape)) dist = {"dist": "skewed t", "nu": float(shape[0]), "lambda": float(shape[1])} else: nu = float(res.params["nu"]) scale = math.sqrt((nu - 2) / nu) ks = stats.kstest(z, lambda v: stats.t.cdf(np.asarray(v) / scale, nu)) dist = {"dist": "Student t", "nu": nu} return { **dist, "ljung_box_z_10": {"q": float(lb.lb_stat.iloc[0]), "p": float(lb.lb_pvalue.iloc[0])}, "ljung_box_z2_10": {"q": float(lb2.lb_stat.iloc[0]), "p": float(lb2.lb_pvalue.iloc[0])}, "arch_lm_5": {"lm": float(lm[0]), "p": float(lm[1])}, "jarque_bera_z": float(stats.jarque_bera(z).statistic), "ks": {"stat": float(ks.statistic), "p": float(ks.pvalue)}, "excess_kurtosis_z": float(stats.kurtosis(z)), } # ---------------------------------------------------------------------------# Out-of-sample VaR backtest# --------------------------------------------------------------------------- def t_quantile(a: float, nu: float) -> float: return float(stats.t.ppf(a, nu) * math.sqrt((nu - 2) / nu)) def t_es(a: float, nu: float) -> float: """Expected value of a unit-variance Student t below its a-quantile (negative).""" q = stats.t.ppf(a, nu) return float(-(nu + q ** 2) / (nu - 1) * stats.t.pdf(q, nu) / a * math.sqrt((nu - 2) / nu)) def garch_forecasts(r: pd.Series, spec: dict, targets: pd.DatetimeIndex) -> pd.DataFrame: """One-day-ahead mean, volatility and standardised residuals for each target day, refitting every REFIT days on all data before the block.""" am = arch_model(r, mean="Constant", **spec) pos = r.index.get_indexer(targets) out = [] for k in range(0, len(pos), REFIT): block = pos[k:k + REFIT] res = am.fit(last_obs=r.index[block[0]], disp="off") f = res.forecast(horizon=1, start=r.index[block[0] - 1], reindex=False) mean = f.mean["h.1"].iloc[: len(block)].to_numpy() vol = np.sqrt(f.variance["h.1"].iloc[: len(block)].to_numpy()) z = (res.resid / res.conditional_volatility).dropna() nu = float(res.params.get("nu", res.params.get("eta", np.nan))) shape = tuple(res.params[[c for c in ("eta", "lambda") if c in res.params]].to_numpy()) for i, j in enumerate(block): out.append((r.index[j], mean[i], vol[i], nu, shape, z)) df = pd.DataFrame(out, columns=["date", "mu", "sigma", "nu", "shape", "z"]).set_index("date") return df def skewt_quantile_es(a: float, shape: tuple) -> tuple[float, float]: """Hansen's skewed t (unit variance): the a-quantile and the mean below it, the latter by averaging the quantile function over (0, a).""" dist = SkewStudent() q = float(dist.ppf(a, np.array(shape))) u = (np.arange(400) + 0.5) / 400 * a return q, float(np.mean(dist.ppf(u, np.array(shape)))) def christoffersen(hits: np.ndarray) -> float: h0, h1 = hits[:-1], hits[1:] n00 = int(((h0 == 0) & (h1 == 0)).sum()); n01 = int(((h0 == 0) & (h1 == 1)).sum()) n10 = int(((h0 == 1) & (h1 == 0)).sum()); n11 = int(((h0 == 1) & (h1 == 1)).sum()) def ll(n_stay, n_move, p): return (n_stay * math.log(1 - p) if n_stay else 0) + (n_move * math.log(p) if n_move else 0) p01 = n01 / max(n00 + n01, 1) p11 = n11 / max(n10 + n11, 1) p = (n01 + n11) / max(n00 + n01 + n10 + n11, 1) if p in (0, 1): return 0.0 return -2 * (ll(n00 + n10, n01 + n11, p) - ll(n00, n01, p01) - ll(n10, n11, p11)) def kupiec(x: int, t: int, p: float) -> float: phat = x / t l0 = (t - x) * math.log(1 - p) + (x * math.log(p) if x else 0) l1 = ((t - x) * math.log(1 - phat) if x < t else 0) + (x * math.log(phat) if x else 0) return -2 * (l0 - l1) def basel_zone(breaches: int) -> str: return "green" if breaches <= 4 else "yellow" if breaches <= 9 else "red" def var_backtest(r: pd.Series, price: pd.Series) -> dict: targets = r.loc[OOS_START:].index realised = r.loc[targets] pos = r.index.get_indexer(targets) a99, a975 = 0.01, 0.025 # Constant volatility, normal: the last 250 days' standard deviation. sd250 = r.rolling(250).std().shift(1).loc[targets] # Historical simulation on the last 500 days. hs99 = np.array([np.quantile(r.iloc[j - 500:j], a99) for j in pos]) hs975 = np.array([np.quantile(r.iloc[j - 500:j], a975) for j in pos]) hs_es = np.array([r.iloc[j - 500:j][r.iloc[j - 500:j] <= q].mean() for j, q in zip(pos, hs975)]) # EWMA (RiskMetrics, lambda 0.94), normal. ew = r.pow(2).ewm(alpha=0.06, adjust=False).mean().shift(1).loc[targets] ** 0.5 g_n = garch_forecasts(r, SPECS["GARCH(1,1), normal"], targets) g_t = garch_forecasts(r, SPECS["GJR-GARCH(1,1), Student t"], targets) g_s = garch_forecasts(r, SPECS["GJR-GARCH(1,1), skewed t"], targets) sk = {sh: (skewt_quantile_es(a99, sh)[0], *skewt_quantile_es(a975, sh)) for sh in set(g_s["shape"])} fhs99 = np.array([g_t.mu.iloc[i] + g_t.sigma.iloc[i] * np.quantile(g_t.z.iloc[i], a99) for i in range(len(g_t))]) fhs975 = np.array([g_t.mu.iloc[i] + g_t.sigma.iloc[i] * np.quantile(g_t.z.iloc[i], a975) for i in range(len(g_t))]) fhs_es = np.array([g_t.mu.iloc[i] + g_t.sigma.iloc[i] * g_t.z.iloc[i][g_t.z.iloc[i] <= np.quantile(g_t.z.iloc[i], a975)].mean() for i in range(len(g_t))]) zn99, zn975 = stats.norm.ppf(a99), stats.norm.ppf(a975) en975 = -stats.norm.pdf(zn975) / a975 models = { "Normal, constant volatility (250 days)": (sd250 * zn99, sd250 * zn975, sd250 * en975), "Historical simulation (500 days)": (hs99, hs975, hs_es), "EWMA (RiskMetrics, 0.94), normal": (ew * zn99, ew * zn975, ew * en975), "GARCH(1,1), normal": (g_n.mu + g_n.sigma * zn99, g_n.mu + g_n.sigma * zn975, g_n.mu + g_n.sigma * en975), "GJR-GARCH(1,1), Student t": ( g_t.mu + g_t.sigma * np.array([t_quantile(a99, v) for v in g_t.nu]), g_t.mu + g_t.sigma * np.array([t_quantile(a975, v) for v in g_t.nu]), g_t.mu + g_t.sigma * np.array([t_es(a975, v) for v in g_t.nu]), ), "GJR-GARCH(1,1), skewed t": ( g_s.mu + g_s.sigma * np.array([sk[sh][0] for sh in g_s["shape"]]), g_s.mu + g_s.sigma * np.array([sk[sh][1] for sh in g_s["shape"]]), g_s.mu + g_s.sigma * np.array([sk[sh][2] for sh in g_s["shape"]]), ), "Filtered historical simulation (GJR-GARCH)": (fhs99, fhs975, fhs_es), } px = price.shift(1).loc[targets].to_numpy() rows, series = [], {} last250 = slice(len(targets) - 250, len(targets)) for name, (v99, v975, es975) in models.items(): v99, v975, es975 = map(lambda a: np.asarray(a, dtype=float), (v99, v975, es975)) hit99 = (realised.to_numpy() < v99).astype(int) hit975 = (realised.to_numpy() < v975).astype(int) t = len(hit99) lr_pof = kupiec(int(hit99.sum()), t, a99) lr_ind = christoffersen(hit99) tail = realised.to_numpy()[hit975 == 1] rows.append({ "model": name, "days": t, "breaches_99": int(hit99.sum()), "expected_99": a99 * t, "rate_99": hit99.mean(), "kupiec_p": float(stats.chi2.sf(lr_pof, 1)), "christoffersen_ind_p": float(stats.chi2.sf(lr_ind, 1)), "conditional_coverage_p": float(stats.chi2.sf(lr_pof + lr_ind, 2)), "breaches_975": int(hit975.sum()), "rate_975": hit975.mean(), "es_ratio_975": float(tail.mean() / es975[hit975 == 1].mean()) if len(tail) else None, "last250_breaches_99": int(hit99[last250].sum()), "basel_zone": basel_zone(int(hit99[last250].sum())), "avg_var99_usd": float(np.mean(-np.expm1(v99 / 100) * px * POINT)), "breach_clusters": int(((hit99[1:] == 1) & (hit99[:-1] == 1)).sum()), }) series[name] = v99 by_year = {} for name in ("Normal, constant volatility (250 days)", "GJR-GARCH(1,1), Student t", "GJR-GARCH(1,1), skewed t"): hits = pd.Series((realised.to_numpy() < series[name]).astype(int), index=targets) by_year[name] = {str(y): int(v) for y, v in hits.groupby(hits.index.year).sum().items()} chart_from = targets[targets >= pd.Timestamp(targets[-1].year - 1, 1, 1)][0] sel = targets >= chart_from chart = { "dates": [d.date().isoformat() for d in targets[sel]], "returns": realised[sel].round(3).tolist(), "garch_t": np.round(series["GJR-GARCH(1,1), Student t"][sel], 3).tolist(), "garch_skewt": np.round(series["GJR-GARCH(1,1), skewed t"][sel], 3).tolist(), "constant": np.round(np.asarray(series["Normal, constant volatility (250 days)"], dtype=float)[sel], 3).tolist(), } return {"from": targets[0].date().isoformat(), "to": targets[-1].date().isoformat(), "refit_days": REFIT, "models": rows, "by_year": by_year, "chart": chart} # ---------------------------------------------------------------------------# The FOMC filter# --------------------------------------------------------------------------- def gjr_x_loglik(theta, r, d): """Negative log-likelihood of a GJR-GARCH(1,1) with Student t errors and a dummy in the variance equation: sigma2_t = w + (a + g*1[e<0]) e2_{t-1} + b sigma2_{t-1} + delta * D_t.""" mu, w, a, g, b, delta, nu = theta e = r - mu u = np.empty_like(r) u[0] = e.var() u[1:] = w + (a + g * (e[:-1] < 0)) * e[:-1] ** 2 u[1:] += delta * d[1:] s2 = np.empty_like(r) s2[0] = u[0] # sigma2_t = u_t + b * sigma2_{t-1}: a first-order linear filter. from scipy.signal import lfilter s2[1:] = lfilter([1.0], [1.0, -b], u[1:], zi=[b * s2[0]])[0] if np.any(s2 <= 0) or nu <= 2.05: return 1e10 c = special.gammaln((nu + 1) / 2) - special.gammaln(nu / 2) - 0.5 * math.log(math.pi * (nu - 2)) ll = c - 0.5 * np.log(s2) - (nu + 1) / 2 * np.log1p(e ** 2 / (s2 * (nu - 2))) return -ll.sum() def fit_gjr_x(r: np.ndarray, d: np.ndarray, with_dummy: bool) -> tuple[np.ndarray, float]: x0 = np.array([0.05, 0.02, 0.02, 0.15, 0.88, 0.3 if with_dummy else 0.0, 6.0]) bounds = [(-1, 1), (1e-6, 1), (0, 0.5), (0, 0.5), (0.5, 0.9999), (-1, 10) if with_dummy else (0, 0), (2.1, 50)] res = optimize.minimize(gjr_x_loglik, x0, args=(r, d), method="L-BFGS-B", bounds=bounds) return res.x, -res.fun def fomc_study(spx: pd.DataFrame, fomc: pd.Series, year: int) -> dict: df = spx.loc[EVENT_START:].copy() df["prev"] = df.close.shift(1) df = df.dropna() df["range_pct"] = (df.high - df.low) / df.open * 100 df["range_pts"] = df.high - df.low df["oc_abs"] = (df.close / df.open - 1).abs() * 100 df["cc_abs"] = (df.close / df.prev - 1).abs() * 100 days = set(pd.DatetimeIndex(fomc)) df["fomc"] = df.index.isin(days) df["before"] = df.fomc.shift(-1, fill_value=False) df["after"] = df.fomc.shift(1, fill_value=False) other = df[~(df.fomc | df.before | df.after)] groups = {"FOMC day": df[df.fomc], "Day before": df[df.before], "Day after": df[df.after], "Other days": other} rng = np.random.default_rng(7) def ratio_ci(a, b, draws=10000): ra = rng.choice(a, (draws, len(a))).mean(axis=1) rb = rng.choice(b, (draws, len(b))).mean(axis=1) return np.percentile(ra / rb, [2.5, 97.5]).tolist() table = [] for name, g in groups.items(): table.append({"group": name, "days": len(g), "range_pct": float(g.range_pct.mean()), "oc_abs": float(g.oc_abs.mean()), "cc_abs": float(g.cc_abs.mean()), "top_decile_share": float((g.range_pct >= df.range_pct.quantile(0.9)).mean())}) f, o = groups["FOMC day"], other tests = { "range_ratio": float(f.range_pct.mean() / o.range_pct.mean()), "range_ratio_ci": ratio_ci(f.range_pct.to_numpy(), o.range_pct.to_numpy()), "range_mw_p": float(stats.mannwhitneyu(f.range_pct, o.range_pct, alternative="greater").pvalue), "oc_ratio": float(f.oc_abs.mean() / o.oc_abs.mean()), "oc_ratio_ci": ratio_ci(f.oc_abs.to_numpy(), o.oc_abs.to_numpy()), "oc_mw_p": float(stats.mannwhitneyu(f.oc_abs, o.oc_abs, alternative="greater").pvalue), "cc_ratio": float(f.cc_abs.mean() / o.cc_abs.mean()), "cc_mw_p": float(stats.mannwhitneyu(f.cc_abs, o.cc_abs, alternative="greater").pvalue), "before_range_ratio": float(groups["Day before"].range_pct.mean() / o.range_pct.mean()), } # GARCH-X: does an FOMC day add variance once volatility clustering is # allowed for? Close-to-close returns, 2008 on. rr = log_returns(spx.close).loc[EVENT_START:] dd = rr.index.isin(days).astype(float) th_u, ll_u = fit_gjr_x(rr.to_numpy(), dd, True) th_r, ll_r = fit_gjr_x(rr.to_numpy(), dd, False) lr = 2 * (ll_u - ll_r) mu, w, a, g, b, delta, nu = th_u uncond = w / (1 - a - g / 2 - b) # The same model on open-to-close (session) returns, which is what an # intraday trader holds. oc = (100 * np.log(spx.close / spx.open)).loc[EVENT_START:].dropna() do = oc.index.isin(days).astype(float) tho, llo = fit_gjr_x(oc.to_numpy(), do, True) thr, llr = fit_gjr_x(oc.to_numpy(), do, False) uo = tho[1] / (1 - tho[2] - tho[3] / 2 - tho[4]) garch_x = { "close_to_close": {"delta": float(delta), "lr": float(lr), "p": float(stats.chi2.sf(lr, 1)), "vol_multiple": float(math.sqrt((uncond + delta) / uncond)), "nu": float(nu)}, "open_to_close": {"delta": float(tho[5]), "lr": float(2 * (llo - llr)), "p": float(stats.chi2.sf(2 * (llo - llr), 1)), "vol_multiple": float(math.sqrt((uo + tho[5]) / uo))}, } this_year = df.loc[str(year)] fy = this_year[this_year.fomc] ref = this_year[~(this_year.fomc | this_year.before | this_year.after)] year_rows = [{"date": i.date().isoformat(), "range_pts": float(row.range_pts), "range_usd": float(row.range_pts * POINT), "oc_pts": float(row.close - row.open)} for i, row in fy.iterrows()] return { "from": df.index[0].date().isoformat(), "to": df.index[-1].date().isoformat(), "table": table, "tests": tests, "garch_x": garch_x, "year": {"fomc_days": year_rows, "median_other_range_pts": float(ref.range_pts.median()), "mean_fomc_range_pts": float(fy.range_pts.mean()) if len(fy) else None, "mean_other_range_pts": float(ref.range_pts.mean())}, } # ---------------------------------------------------------------------------# Flat into the close: overnight gaps# --------------------------------------------------------------------------- def overnight(spx: pd.DataFrame, year: int, capital: float, largest_loss: float) -> dict: df = spx.loc[EVENT_START:].copy() df["prev"] = df.close.shift(1) df = df.dropna() gap = 100 * np.log(df.open / df.prev) sess = 100 * np.log(df.close / df.open) cc = 100 * np.log(df.close / df.prev) pts = df.open - df.prev y = df.loc[str(year)] ypts = (y.open - y.prev) yrange = y.high - y.low worst = pts.abs().sort_values(ascending=False).head(5) return { "from": df.index[0].date().isoformat(), "to": df.index[-1].date().isoformat(), "variance_share_overnight": float(gap.var() / (gap.var() + sess.var())), "corr_gap_session": float(gap.corr(sess)), "cc_var": float(cc.var()), "year": { "days": len(y), "median_abs_gap_pts": float(ypts.abs().median()), "max_gap_pts": float(ypts.abs().max()), "max_gap_date": ypts.abs().idxmax().date().isoformat(), "gaps_over_capital": int((ypts.abs() * POINT > capital).sum()), "gaps_over_largest_loss": int((ypts.abs() * POINT > abs(largest_loss)).sum()), "median_range_pts": float(yrange.median()), "largest_loss_pts": abs(largest_loss) / POINT, }, "worst_gaps": [{"date": i.date().isoformat(), "pts": float(pts.loc[i]), "pct": float(gap.loc[i]), "usd": float(pts.loc[i] * POINT)} for i in worst.index], } # ---------------------------------------------------------------------------# Monthly link between the trading result and the market# --------------------------------------------------------------------------- def monthly_market(spx: pd.DataFrame, vix: pd.DataFrame, year: int, months: list[str]) -> pd.DataFrame: c = spx.close r = log_returns(c) rows = [] for k, name in enumerate(months, start=1): prev = c.loc[: pd.Timestamp(year, k, 1) - pd.Timedelta(days=1)].iloc[-1] m = c.loc[f"{year}-{k:02d}"] rows.append({"month": name, "spx": float(m.iloc[-1] / prev - 1), "rv": float(r.loc[f"{year}-{k:02d}"].std() * math.sqrt(252)), "vix": float(vix.close.loc[f"{year}-{k:02d}"].mean())}) out = pd.DataFrame(rows).set_index("month") out["spx_abs"] = out.spx.abs() return out