GARCH Volatility Forecasting in Python: Fitting, Checking, and Sizing Positions with arch

GARCH models turn the one quantity every quant actually trades around — tomorrow’s variance — into an estimable object. This post walks through fitting GARCH(1,1), GJR-GARCH, and EGARCH on S&P 500 daily returns with the arch package, running the residual diagnostics that tell you whether the fit is usable, producing multi-step and rolling one-step forecasts, and converting forecasts into position sizes. The math is kept to the two variance equations that matter; everything else is code you can paste and run.

How This Guide Was Built

This guide is built on the official arch 8.0.0 documentation and package source, the linked arXiv papers, and reproductions on the package’s bundled S&P 500 dataset (5,030 daily observations, 1999–2018). No live trading was run; all results shown are in-sample fits or backtest-style reproductions, and outputs labeled “this run” come from those reproductions.

Fitting a First GARCH(1,1) on S&P 500 Returns

GARCH(1,1) models conditional variance as a function of last period’s squared shock and last period’s variance, and it remains the default first fit for daily equity returns. The arch volatility-process reference documents the parameterization used below:

r_t     = mu + eps_t
eps_t   = sigma_t * z_t
sigma_t^2 = omega + alpha * eps_{t-1}^2 + beta * sigma_{t-1}^2

with constraints omega > 0, alpha ≥ 0, beta ≥ 0, and alpha + beta < 1 for covariance stationarity. When alpha + beta = 1 you have IGARCH and no finite long-run variance. Persistence is p = alpha + beta, and the half-life of a variance shock is ln(0.5)/ln(alpha+beta) — as a generic illustration, persistence 0.98 gives about 34 trading days, while the two fits below (0.9874 on Normal innovations and 0.9995 on Student-t) imply roughly 55 and 1,468 days respectively.

Load the bundled data first. The arch notebook on univariate volatility modeling uses the same dataset scaled to percentage returns; if you prefer your own data, yfinance SPY adjusted closes are a drop-in alternative.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from arch import arch_model
from arch.data.sp500 import load

data = load()
rets = 100 * data["Adj Close"].pct_change().dropna()   # percentage returns
print(rets.shape)
print(rets.index.min(), "to", rets.index.max())

This prints the sample size (5,030 observations on the bundled dataset) and the date range, which runs from January 1999 to December 2018.

Before fitting, confirm there is ARCH structure to model at all. Note that statsmodels has no GARCH-family estimator — it appears here only for Engle’s ARCH-LM test (het_arch) and the Ljung–Box test:

from statsmodels.stats.diagnostic import het_arch, acorr_ljungbox

lm_stat, lm_p, f_stat, f_p = het_arch(rets)
print(f"ARCH-LM statistic: {lm_stat:.2f}, p-value: {lm_p:.4g}")
lb = acorr_ljungbox(rets**2, lags=[10], return_df=True)
print(lb)

This prints the ARCH-LM statistic and p-value plus a Ljung–Box table on squared returns; on daily equity data both reject the no-ARCH null overwhelmingly, which is the signal that a volatility model is warranted.

Now the fit. Fit on 100× percentage returns — this scale convention keeps the optimizer well-conditioned — and use a Student-t distribution, the standard upgrade for risk work because daily returns have fat tails. (A normal distribution often converges faster if you only care about the variance path, and arch also offers skewed-t; the arch notebook shows t-distributed fits with full parameter tables.)

am = arch_model(rets, mean="Constant", vol="GARCH", p=1, q=1, dist="t")
res = am.fit(disp="off")
assert res.convergence_flag == 0

print(res.params)
print(f"log-likelihood: {res.loglikelihood:.2f}")
print(f"AIC: {res.aic:.2f}   BIC: {res.bic:.2f}")

omega = res.params["omega"]
alpha = res.params["alpha[1]"]
beta  = res.params["beta[1]"]
persistence = alpha + beta
half_life = np.log(0.5) / np.log(persistence)
uncond_var = omega / (1 - persistence)
print(f"persistence: {persistence:.4f}")
print(f"half-life (trading days): {half_life:.1f}")
print(f"unconditional daily variance (pct^2): {uncond_var:.4f}")

res.plot(annualize="D")

This prints the parameter vector, log-likelihood, AIC/BIC, the computed persistence and half-life, and the unconditional variance omega/(1−alpha−beta); res.plot(annualize='D') shows the annualized conditional volatility path. The arch notebook estimates these same 5,030 observations with Normal innovations and reports omega 0.0175, alpha 0.1022, beta 0.8852 (persistence ≈ 0.987) and log-likelihood −6936.72. Refitting that sample with Student-t, as this block does, changes the answer: this run returns log-likelihood −6834.74 and persistence ≈ 0.9995, so the innovation choice has to be reported alongside the parameters rather than assumed away. The annualization convention used throughout: variance × 252, volatility × √252.

Diagnosing the Fit with Standardized Residuals

Standardized residuals z = eps_t / sigma_t should be roughly iid(0,1) if the volatility model has absorbed the conditional heteroskedasticity, so checking their mean, variance, and leftover autocorrelation is the pass/fail test for the fit. The Ljung–Box test on z² probes remaining ARCH structure, and het_arch re-checks adequacy after fitting exactly as it did before; the volatility-modeling notebook walks the same sequence with printed parameter tables:

z = res.resid / res.conditional_volatility
print(f"mean of z: {z.mean():.4f}   variance of z: {z.var():.4f}")

lb_z2 = acorr_ljungbox(z**2, lags=[10], return_df=True)
print(lb_z2)

lm_z, lm_z_p, _, _ = het_arch(z.dropna())
print(f"ARCH-LM on z: statistic {lm_z:.2f}, p-value {lm_z_p:.4g}")

This prints the mean and variance of z (you want ≈ 0 and ≈ 1), the Ljung–Box table on z², and the post-fit ARCH-LM result; comparing the pre-fit and post-fit statistics side by side shows how much ARCH structure the model absorbed. One explicit caveat: AIC and BIC compare in-sample fit on the same data and likelihood only — a lower information criterion with significant residual ARCH is still a bad model, and neither statistic says anything about out-of-sample forecast quality.

GJR-GARCH and EGARCH: Asymmetric Alternatives

GJR-GARCH adds one parameter, gamma, that lets negative shocks raise future variance more than positive shocks of equal size — the leverage effect — while EGARCH models ln(sigma²) directly and therefore imposes no positivity constraints on its parameters. The GJR equation:

sigma_t^2 = omega + (alpha + gamma * I[eps_{t-1} < 0]) * eps_{t-1}^2 + beta * sigma_{t-1}^2

with gamma > 0 meaning the leverage effect is present. EGARCH (Nelson 1991) enters the standardized shock z and an |z| term in the log-variance equation instead. In arch, GJR is the GARCH process with the asymmetry order switched on (o=1) and EGARCH is a separate vol string, so both are one-line changes; the package also ships 'HARCH', 'FIGARCH', and 'APARCH' volatility processes and ConstantMean, ZeroMean, ARX, HARX, and ARCHInMean mean models (volatility reference, mean-model reference).

gjr    = arch_model(rets, mean="Constant", vol="GARCH", p=1, o=1, q=1, dist="t").fit(disp="off")
egarch = arch_model(rets, mean="Constant", vol="EGARCH", p=1, o=1, q=1, dist="t").fit(disp="off")

print(pd.DataFrame({"GARCH(1,1)": res.params, "GJR-GARCH": gjr.params, "EGARCH": egarch.params}))
print(f"GARCH(1,1) loglik: {res.loglikelihood:.2f}")
print(f"GJR-GARCH  loglik: {gjr.loglikelihood:.2f}")
print(f"EGARCH     loglik: {egarch.loglikelihood:.2f}")

This prints a side-by-side parameter table (indices differ, so pandas fills gaps with NaN) and the three log-likelihoods on this sample. The arch notebook reports its GJR fit on the same 5,030 observations — again with Normal innovations — as gamma 0.1831 with log-likelihood −6822.88, up from −6936.72 for plain GARCH(1,1), so the asymmetric term improves the fit substantially and is highly significant. With Student-t on this run the same comparison gives gamma ≈ 0.1856 and log-likelihood −6744.43 against the t-GARCH −6834.74; the level shifts with the distribution, the ordering does not.

Model What it captures Extra params vs GARCH(1,1) Parameter constraints arch call Multi-step forecast method Log-lik in arch notebook (Normal innovations)
GARCH(1,1) Volatility clustering, mean reversion to omega/(1−alpha−beta) — omega > 0, alpha ≥ 0, beta ≥ 0, alpha+beta < 1 arch_model(r, vol="GARCH", p=1, q=1, dist="t") Analytic (also simulation, bootstrap) −6936.72
GJR-GARCH Leverage effect: negative shocks raise variance more 1 (gamma) GARCH constraints plus gamma ≥ 0 arch_model(r, vol="GARCH", p=1, o=1, q=1, dist="t") Analytic (linear in squared residuals), simulation, bootstrap −6822.88
EGARCH Asymmetry in log-variance, no positivity constraints 1 (asymmetry term) No positivity constraints imposed arch_model(r, vol="EGARCH", p=1, o=1, q=1, dist="t") Simulation or bootstrap only Not reported in the notebook example

Multi-Step Forecasts: Analytic vs Simulation

Multi-step variance forecasts come from res.forecast(horizon=h, ...), choosing method='analytic', 'simulation', or 'bootstrap' and align='origin' or 'target'; the returned object carries .variance, .mean, and .residual_variance as DataFrames with columns h.1 … h.h (forecasting reference). Analytic multi-step forecasts exist only for models linear in squared residuals (GARCH, HARCH); EGARCH needs simulation or bootstrap. Because forecasts converge geometrically to the unconditional variance omega/(1−alpha−beta), at the 0.9874 persistence of the Normal-innovation fit there is little information past roughly 10–20 days for daily equity data.

fc = res.forecast(horizon=21, align="origin")
var_daily_dec = fc.variance.iloc[-1] / 100**2      # percent^2 -> decimal variance
ann_var = var_daily_dec * 252                      # annualization: variance x 252
uncond_ann = uncond_var / 100**2 * 252

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(range(1, 22), ann_var.values, marker="o", label="GARCH(1,1) forecast variance")
ax.axhline(uncond_ann, linestyle="--", color="gray", label="unconditional variance")
ax.set_xlabel("horizon (trading days)")
ax.set_ylabel("annualized variance")
ax.legend()

This plots the 21-day annualized forecast variance path from the last origin, divided by 100² to return to decimal units, with a horizontal line at the annualized unconditional variance — the flat line the forecast path decays toward. On the Student-t fit above, persistence is so close to one that the implied unconditional variance sits far above the entire forecast path: a near-unit-root symptom worth noticing before you trust the long-run level as an anchor.

For EGARCH, switch to simulation:

fc_sim = egarch.forecast(horizon=21, method="simulation", align="origin")
sim_ann = fc_sim.variance.iloc[-1] / 100**2 * 252
print(sim_ann.round(4))

This prints the simulated 21-day annualized variance path for the EGARCH fit; the analytic multi-step method is unavailable for this model class, so simulation (or bootstrap) is the documented route (forecasting reference).

Evaluating Forecasts: QLIKE, Diebold–Mariano, and Look-Ahead Traps

Out-of-sample forecast evaluation requires a realized-variance proxy, a proper loss function, and a test for whether the difference between two models’ losses is real. Squared daily returns are a very noisy proxy for realized variance; realized variance built from 5-minute intraday squared returns is far better, and the estimators behind it are covered in the site’s guide to realized volatility estimators in Python. Recent work on autoencoder-enhanced realised GARCH (arXiv) builds directly on this proxy-and-model pairing.

The standard loss is QLIKE = RV/σ̂² − ln(RV/σ̂²) − 1, which penalizes under-prediction of variance asymmetrically and is robust to a noisy proxy. HAR-RV (Corsi 2009), which regresses realized variance on daily, weekly, and monthly lags, is the out-of-sample benchmark a GARCH should beat; HAR-type extensions to realized covariance are surveyed on arXiv.

The rolling design below refits every 5 trading days with parameters frozen in between — the standard trade-off between daily refits (more responsive, slower) and infrequent refits (cheaper, staler). Using arch’s .fix() keeps parameters frozen while still filtering new observations through the volatility recursion:

def rolling_one_step(rets, vol_kwargs, refit_every=5, min_obs=1000):
    params, out, dates = None, [], []
    for t in range(min_obs, len(rets)):
        if params is None or (t - min_obs) % refit_every == 0:
            res_fit = arch_model(rets.iloc[:t], mean="Constant", **vol_kwargs).fit(disp="off")
            assert res_fit.convergence_flag == 0
            params = res_fit.params
        fixed = arch_model(rets.iloc[: t + 1], mean="Constant", **vol_kwargs).fix(params)
        f = fixed.forecast(horizon=1, reindex=False)
        out.append(float(f.variance.iloc[0, 0]))
        dates.append(rets.index[t])
    return pd.Series(out, index=dates)

sig2_garch = rolling_one_step(rets, dict(vol="GARCH", p=1, q=1, dist="t"))
sig2_gjr   = rolling_one_step(rets, dict(vol="GARCH", p=1, o=1, q=1, dist="t"))
print(sig2_garch.describe())

This prints summary statistics for the two rolling one-step variance series — note they are in percent² units, because the model was fitted on 100× returns, so the scoring block below divides by 100² before computing losses. Expect the loop to take a few minutes since it refits roughly 800 times on the 5,030-observation sample.

Then score both series against the squared-return proxy and test the loss differential. The Diebold–Mariano statistic (Diebold and Mariano, 1995) tests whether the mean loss differential differs from zero, with a Newey–West HAC standard error computed in-code:

import math

def newey_west_se(x, lags):
    x = np.asarray(x, dtype=float)
    n = x.size
    e = x - x.mean()
    s = np.dot(e, e) / n
    for l in range(1, lags + 1):
        w = 1.0 - l / (lags + 1)
        s += 2.0 * w * np.dot(e[l:], e[:-l]) / n
    return math.sqrt(s / n)

idx = sig2_garch.index
r2 = (rets.loc[idx] / 100) ** 2          # squared decimal returns: noisy RV proxy
sig2_g_dec = sig2_garch / 100**2         # rolling series is in percent^2 -> decimal variance
sig2_j_dec = sig2_gjr   / 100**2

qlike_g = r2 / sig2_g_dec - np.log(r2 / sig2_g_dec) - 1
qlike_j = r2 / sig2_j_dec - np.log(r2 / sig2_j_dec) - 1
print(f"QLIKE mean  GARCH: {qlike_g.mean():.6f}   GJR: {qlike_j.mean():.6f}")
print(f"MSE   mean  GARCH: {((r2 - sig2_g_dec)**2).mean():.3e}   "
      f"GJR: {((r2 - sig2_j_dec)**2).mean():.3e}")

d = (qlike_g - qlike_j).dropna()         # negative mean favors GJR
dm = d.mean() / newey_west_se(d.values, lags=5)
pval = math.erfc(abs(dm) / math.sqrt(2)) # two-sided normal p-value
print(f"Diebold-Mariano statistic: {dm:.3f}, HAC p-value: {pval:.4f}")

The QLIKE means, MSE means, DM statistic, and p-value printed here come from this run on the bundled sample — report your own numbers from your own run rather than quoting anyone else’s, and treat squared returns as the weak proxy they are.

The look-ahead traps that invalidate this kind of exercise, all easy to commit accidentally: choosing p, q, and the distribution on the full sample and then calling the same-sample run “out-of-sample”; setting the volatility target after seeing the backtest; and evaluating on the fitting window. A systematic treatment of these failure modes is in the site’s guide to detecting backtest overfitting in Python.

Position Sizing with Volatility Targeting

GARCH forecasts variance, not direction: a high forecast volatility justifies a smaller position, never a short position. The standard conversion is volatility targeting, w_t = clip(target_vol / sigma_hat_t, 0, cap), with the target and cap fixed a priori and the result compared against a constant-volatility baseline, so the forecast has to earn its place against a benchmark that ignores it. The site’s fuller treatment is the guide to volatility targeting in Python; for the complementary question of how large the average position should be, see the Kelly criterion methodology.

target_vol = 0.15   # 15% annualized, fixed before any backtest
cap = 2.0           # leverage cap, fixed before any backtest

sigma_ann = np.sqrt(sig2_garch / 100**2 * 252)   # percent^2 -> decimal var, then annualize
w_garch = np.clip(target_vol / sigma_ann, 0.0, cap)

sample_vol = rets.loc[sig2_garch.index].std() / 100 * np.sqrt(252)
w_const = pd.Series(target_vol / sample_vol, index=sig2_garch.index)

print(f"fraction of days at the cap: {(w_garch >= cap).mean():.2%}")

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(w_garch.index, w_garch, label="GARCH vol-target weight")
ax.plot(w_const.index, w_const, linestyle="--", label="constant-vol baseline")
ax.set_ylabel("weight multiple")
ax.legend()

This prints the fraction of days the vol-target weight spends pinned at the 2.0 cap and plots the GARCH-driven weight against the constant-vol baseline; the cap fraction is a property of your sample and forecast, not a fixed number, so read it as a diagnostic of how often the sizing rule binds.

Caveats That Change the Answer

GARCH output is only as good as its assumptions, and three caveats routinely overturn naive conclusions. First, regime breaks such as the 2020 crash and the August 2024 volatility shock make persistence and omega window-specific estimates, which is why regime-aware alternatives such as the site’s HMM regime detection methodology exist and why hybrid approaches like GARCH-informed neural networks are an active research direction. Second, daily close-to-close returns embed overnight gaps that intraday realized variance can exclude, so the proxy and the model measure slightly different objects. Third, multi-step forecasts carry little information past ~10–20 days at persistence ≈ 0.98, so long-horizon “GARCH forecasts” are mostly the unconditional variance wearing a hat.

FAQ

How does a GARCH volatility forecast relate to the VIX?

They measure different things: GARCH forecasts variance from realized returns, while the VIX is an implied-volatility index built from option prices. The Cboe VIX page showed a spot level of 20.71 on 2026-11-03, and the close series is downloadable from FRED. Comparing the two is informative, but they are not substitutes.

Why fit on percentage returns instead of raw decimals?

Scaling returns by 100 keeps the optimizer well-conditioned — raw decimal scales make omega and the variance intercept tiny and numerically awkward. The documented convention is to fit on 100× returns and then divide variance forecasts by 100² to return to decimal units, which is exactly what the forecast blocks above do (arch forecasting reference).

How far ahead is a GARCH forecast actually useful?

Barely past two to three weeks for daily equity data. Multi-step forecasts converge geometrically to the unconditional variance omega/(1−alpha−beta), and at the 0.9874 persistence this sample’s Normal-innovation fit reports — a variance-shock half-life of roughly 55 trading days — there is little information beyond roughly 10–20 trading days (arch forecasting reference).

Can statsmodels estimate GARCH models?

No — statsmodels has no GARCH-family estimator. In this workflow statsmodels supplies only the het_arch ARCH-LM test and acorr_ljungbox for diagnostics, while all variance-model estimation runs through the arch package, which exists precisely to fill that gap.

Which error distribution should I use?

Student-t is the standard upgrade for risk work because daily returns are fat-tailed, and skewed-t adds asymmetry; the normal often converges faster when you only need the variance path. The arch modeling notebook shows t-distributed fits with parameter tables you can compare against normal-distribution fits on the same data.

Does high forecast volatility mean I should go short?

No. GARCH forecasts variance, not direction, so a high forecast justifies a smaller gross position, not a directional bet. The correct use is sizing — clip(target_vol / sigma_hat, 0, cap) with the target and cap fixed in advance — as laid out in the site’s volatility targeting guide.

The Bottom Line

Fit GARCH(1,1) first, add the GJR asymmetry term when the leverage effect matters for your market, and reach for EGARCH when you want asymmetry without positivity constraints. Trust the standardized-residual diagnostics more than the log-likelihood, evaluate rolling one-step forecasts with QLIKE against a HAR-RV benchmark rather than trusting in-sample AIC/BIC, and consume the forecasts through a volatility-targeting rule with the target and cap frozen before the backtest. At persistence ≈ 0.98, treat anything past a few weeks as the unconditional variance, and remember throughout that the model speaks about variance — never about direction.

← Back to all posts