GARCH Model in Python: A 36-Day Shock Half-Life

Fit a GARCH model in Python with NumPy and SciPy, verify it against arch, and compare volatility forecasts with EWMA on pinned S&P 500 returns.

Cover Image for GARCH Model in Python: A 36-Day Shock Half-Life

A risk estimate built from the last month of market returns can change sharply when one bad day leaves the window. That matters when the estimate determines how much exposure a portfolio can carry. During the March 2020 sell-off, the S&P 500's daily moves grew several times larger than they had been a month earlier. A useful volatility model needs to respond to those shocks and describe how their effect persists after they pass.

GARCH gives that persistence an explicit parameter. Its central equation combines a baseline, yesterday's squared return and yesterday's variance. In the experiment below, a GARCH(1,1) model produces lower forecast loss than a 20-day rolling estimate and RiskMetrics EWMA, both for tomorrow and for the next 20 trading days. By the end of this post, you'll be able to fit a GARCH model in Python, check the implementation against arch, and evaluate forecasts without letting future returns enter the fit.

ht+1=ω+αrt2+βhth_{t+1}=\omega+\alpha r_t^2+\beta h_t

Here hth_t is the variance of today's return conditional on yesterday's information. We use a zero-mean return model, so the observed return is also its residual. A model with a fitted mean would put the squared residual in the same equation.

Quick Win

Open In Colab

The animation shows the maximum-likelihood fit improving through feasible SLSQP iterates. The upper panel shows its changing volatility estimate during the financial crisis, while the lower panel records the best negative log-likelihood reached so far. The optimiser can try worse points along the way. The animation displays the best feasible point reached at each accepted iterate.

GARCH volatility estimates during 2008 changing as constrained likelihood optimisation improves.

Install numpy, scipy, pandas, matplotlib and yfinance, then run the example. The notebook embeds the exact price snapshot behind the article, so you can reproduce the results even if Yahoo revises historical values. This shorter example downloads the same date range directly.

import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
from scipy.optimize import minimize
from scipy.signal import lfilter

prices = yf.download("^GSPC", start="2000-01-01", end="2026-10-01",
                     auto_adjust=True, progress=False)["Close"].squeeze()
returns = (100 * np.log(prices.dropna()).diff()).dropna()
r = returns.to_numpy()
weights = 0.94 ** np.arange(min(75, len(r)))
initial = weights @ r[:len(weights)]**2 / weights.sum()

def variance_path(p):
    omega, alpha, beta = p
    inputs = omega + alpha * np.r_[initial, r[:-1]**2]
    return lfilter([1.0], [1.0, -beta], inputs,
                   zi=[beta * initial])[0]

def negative_loglikelihood(p):
    h = variance_path(p)
    return 0.5 * np.sum(np.log(2 * np.pi * h) + r**2 / h)

fits = []
for alpha, beta in [(0.08, 0.90), (0.15, 0.80)]:
    start = [(1 - alpha - beta) * np.mean(r**2), alpha, beta]
    fit = minimize(
        negative_loglikelihood, start, method="SLSQP",
        bounds=[(1e-9, 10 * np.mean(r**2)), (0, 1), (0, 1)],
        constraints={"type": "ineq", "fun": lambda p: 0.999999-p[1]-p[2]},
        options={"ftol": 1e-8, "maxiter": 300},
    )
    if fit.success:
        fits.append(fit)
if not fits:
    raise RuntimeError("Both likelihood fits failed")
fit = min(fits, key=lambda result: result.fun)
omega, alpha, beta = fit.x
h = variance_path(fit.x)
first = omega + alpha * r[-1]**2 + beta * h[-1]
long_run = omega / (1 - alpha - beta)
forecasts = long_run + (alpha + beta)**np.arange(20) * (first-long_run)
print("omega, alpha, beta:", np.round(fit.x, 6))
print("Shock half-life:", np.log(0.5) / np.log(alpha + beta))

fig, ax = plt.subplots(figsize=(11, 4))
ax.plot(returns.index, abs(r), alpha=0.25, label="Absolute daily return")
ax.plot(returns.index, np.sqrt(h), label="GARCH conditional volatility")
ax.set(ylabel="Daily return / volatility (%)")
ax.legend()
plt.show()

Absolute S&P 500 returns and fitted conditional volatility from January 2000 to September 2026, with stress dates marked.

The pinned snapshot contains 6,726 closes and 6,725 returns. Its Gaussian fit gives ω=0.024395\omega=0.024395, α=0.115515\alpha=0.115515 and β=0.865269\beta=0.865269. Their sum is about 0.981, which gives a shock half-life of roughly 36 trading days. The forecasts array holds expected daily variances for the next 20 days, in squared percentage-return units.

The smooth line is a conditional standard deviation. Each day's absolute return remains a noisy observation, so a large move can exceed the line by a wide margin. This full-sample fit illustrates the model's behaviour. The forecast comparison later in the post refits on past data only.

Volatility Clustering

The return series contains much less serial structure than its squared values. Squaring removes direction and keeps magnitude. A sequence of large positive and negative returns then becomes a sequence of large positive values, which makes clusters visible.

An autocorrelation function, or ACF, measures how a series relates to its own past. Lag one compares today's value with yesterday's. Lag 20 compares it with the value 20 trading days earlier. The following chart uses the complete pinned sample.

Autocorrelations of returns and squared returns, with persistent positive correlations in squared returns.

The return ACF is small at most lags, although its first lag is about -0.099. Calling returns completely uncorrelated would overstate this result. The squared-return ACF is about 0.313 at lag one and still 0.165 at lag 20. Return magnitude retains information for considerably longer than direction in this sample.

The pale band is the conventional white-noise reference of ±1.96/n\pm1.96/\sqrt{n}. It provides a visual guide. Financial returns with changing variance do not meet the independent white-noise assumptions behind a literal significance test using that band.

GARCH models this persistence by keeping a running variance state. A large squared return pushes the state upwards. Later updates retain a fraction of that state, so yesterday's shock continues to affect tomorrow's risk estimate even after individual daily moves have become smaller.

This differs from changepoint detection, which asks whether the data-generating regime changed. Bayesian online changepoint detection maintains a distribution over the time since a change. GARCH maintains a continuously updated scale within one specified variance model. Both can react to a crisis, but their outputs answer different questions.

The Variance Update

The three terms in the recursion have distinct jobs. The intercept ω\omega supplies a positive baseline on every update. The coefficient α\alpha sets how strongly the latest observed shock changes the estimate. The coefficient β\beta carries yesterday's estimated variance forward.

For the fitted parameters, a squared return of 4 contributes about 0.462 to tomorrow's variance through the shock term. That corresponds to a daily return of either +2% or -2%. The symmetric model gives both the same effect.

The update uses variance because its terms add naturally. Standard deviation is the square root of variance. Taking square roots before adding these terms would define a different model, and squaring a rolling standard deviation after the fact would not recover the GARCH recursion.

The implementation's first fitted variance is ω+(α+β)b\omega+(\alpha+\beta)b, where bb is the initial backcast. We construct bb from a weighted average of the first 75 squared returns, using exponentially declining weights. The reference library uses the same initialisation. Those early observations are part of the training sample, and every rolling fit computes its backcast from its own training window.

lfilter evaluates the recurrence in compiled code. Its feedback coefficient is -beta in the denominator, so the resulting equation adds beta * h[t-1]. The initial filter state supplies the pre-sample contribution. The mathematical model remains a three-term update regardless of which routine evaluates it.

Parameter Constraints

We constrain ω>0\omega>0, α≥0\alpha\geq0 and β≥0\beta\geq0 to keep variances positive. The additional condition α+β<1\alpha+\beta<1 gives a finite unconditional variance for the stationary GARCH(1,1) model. The optimiser uses an upper bound of 0.999999 on that sum.

These conditions have different purposes. Positivity prevents invalid conditional variances. The persistence condition controls the existence of the long-run second moment. A near-unit sum can still make the estimated long-run variance sensitive to a small parameter change.

Returns in the example use percentage units. A daily decimal return of 0.01 becomes 1.0. Multiplying returns by 100 multiplies the variance and its intercept by 10,000, while leaving α\alpha and β\beta unchanged in the corresponding model. This scaling makes the optimisation easier to handle numerically.

Long-Run Variance

Taking unconditional expectations of the update gives a fixed point. Under stationarity, today's and tomorrow's variance have the same expectation, and the expected squared return equals that variance:

hˉ=ω+(α+β)hˉ,hˉ=ω1−α−β.\bar h=\omega+(\alpha+\beta)\bar h, \qquad \bar h=\frac{\omega}{1-\alpha-\beta}.

Our fitted long-run daily standard deviation is about 1.127%. This level comes from the model fitted over the full sample. A shorter rolling window can estimate a different level and persistence, which is why the forecast evaluation refits the parameters as time advances.

The long-run variance is a model expectation. It does not describe a value the market must return to on a particular date. New shocks arrive during the forecast horizon, and structural changes can make yesterday's parameter estimates unsuitable for tomorrow's market.

Maximum Likelihood

The Gaussian observation model writes rt=htztr_t=\sqrt{h_t}z_t, with zt∼N(0,1)z_t\sim N(0,1). Conditional on the past, the model assigns a Gaussian density to the observed return. The variance sequence depends on the parameters, so changing a parameter changes every later density in the sample.

The negative log-likelihood is:

−ℓ(ω,α,β)=12∑t=1T[log⁡(2π)+log⁡ht+rt2ht].-\ell(\omega,\alpha,\beta) =\frac12\sum_{t=1}^{T} \left[\log(2\pi)+\log h_t+\frac{r_t^2}{h_t}\right].

The logarithmic term penalises making the variance large everywhere. The squared-return ratio penalises assigning too little variance to observations with large moves. Their combination prevents the fit from explaining every observation merely by increasing its scale.

The calculation follows the same likelihood principle as maximum likelihood estimation. The extra work comes from recomputing the variance path for each parameter candidate. SciPy's SLSQP optimiser handles the parameter bounds and the persistence constraint together.

Two starting points reduce dependence on one initial guess. The code retains successful fits and chooses the smaller objective. An optimiser success flag is only part of the check: the notebook also verifies agreement with a separate implementation and checks the resulting forecast path.

Reference Agreement

The arch comparison uses mean="Zero", GARCH order (1,1), Gaussian innovations and the same backcast. Matching those choices matters. Comparing a zero-mean custom model with the library's default constant-mean model would compare different likelihoods.

ParameterNumPy/SciPyarch
ω0.024395490.02439547
α0.115514610.11551451
β0.865269340.86526946

The notebook checks the fitted parameters to numerical tolerance. It then fixes the library model at our exact parameters and compares every conditional variance and a 60-step forecast, with relative tolerance 10−710^{-7}. Fixing the parameters separates agreement on the recursion from tiny differences in numerical optimisation.

The library has additional safeguards, including bounds on the variance path during estimation. They do not alter our fitted path on this dataset, as the independent path comparison verifies. For other datasets, a discrepancy can identify an initialisation, scaling or numerical-handling difference before it identifies an algebra error.

Forecast Horizons

Tomorrow's squared shock is unknown today. Its conditional expectation is tomorrow's variance, so forecasts beyond the first day replace the unknown squared return with its expected value:

h^t+1∣t=ω+αrt2+βht,h^t+k∣t=ω+(α+β)h^t+k−1∣t(k≥2).\hat h_{t+1\mid t}=\omega+\alpha r_t^2+\beta h_t, \qquad \hat h_{t+k\mid t}=\omega+(\alpha+\beta)\hat h_{t+k-1\mid t} \quad(k\geq2).

The closed form is:

h^t+k∣t=hˉ+(α+β)k−1(h^t+1∣t−hˉ).\hat h_{t+k\mid t} =\bar h+(\alpha+\beta)^{k-1} \left(\hat h_{t+1\mid t}-\bar h\right).

Every additional forecast step shrinks the expected deviation from the long-run level by α+β\alpha+\beta. For a high starting variance, the expected path declines. For a low starting variance, it rises. The arch forecasting documentation derives this analytical recursion for models that evolve in squared residuals.

Calm and stressed GARCH variance forecasts converging towards the fitted long-run level, shown on separate vertical scales.

These two illustrative paths start after the closes on 1 November 2017 and 16 March 2020. They use the full-sample parameters to isolate the effect of the starting state. They are retrospective illustrations of the forecast equation, rather than forecasts a researcher could have issued on those dates using this full-sample fit.

The panels have separate vertical scales because the stressed starting variance is much larger. Both dashed lines represent the same long-run variance. These curves show expected variance paths, with no uncertainty band. Simulated future shocks would produce a distribution of realised paths around those expectations.

Shock Half-Life

The expected deviation halves after kk additional steps when (α+β)k=1/2(\alpha+\beta)^k=1/2. Solving gives:

k1/2=log⁡(1/2)log⁡(α+β).k_{1/2}=\frac{\log(1/2)}{\log(\alpha+\beta)}.

The fitted persistence gives 35.72 trading days. This half-life describes the expected decay of a variance deviation while parameters stay fixed. It does not mean volatility will fall by half over the next 36 observed days, because intervening returns update the state.

The sum α+β\alpha+\beta controls this expected decay. The coefficient β\beta alone controls how the recursion propagates an already observed variance state when a realised shock sequence is held fixed. Those are different calculations, which explains why reading the half-life directly from β\beta gives the wrong forecast interpretation.

Forecast Comparison

A well-fitting volatility curve does not establish that GARCH forecasts future risk better than simpler methods. We evaluate forecasts at 5,446 common origins, from 7 January 2005 through 1 September 2026. The final origin leaves 20 trading days for the longest target.

At each origin, the GARCH training window contains the latest 1,260 returns, roughly five trading years. Parameters are refitted every 20 trading days. Between refits, each newly observed return updates the variance state with the current parameters. Every forecast is issued after observing the origin day's close.

The rolling baseline averages the last 20 squared returns. Under the fixed zero-mean assumption this is a variance estimate. A demeaned rolling standard deviation estimates a slightly different quantity, so we use the same mean assumption across all three methods.

RiskMetrics EWMA updates variance with ht+1=0.06rt2+0.94hth_{t+1}=0.06r_t^2+0.94h_t. It shares GARCH's recursive memory but has no positive intercept, and its two weights sum to one. Its expected future daily variance remains flat at the current forecast. The decay parameter is the conventional daily RiskMetrics value, documented in the 1996 Technical Document.

QLIKE Loss

True conditional variance is unobserved. A squared daily return is a noisy proxy under the zero-mean assumption. For the 20-day horizon, the target is the average squared return over the next 20 trading days, and the forecast is the average of the next 20 predicted daily variances.

We use Patton's QLIKE loss:

L(x,h^)=log⁡h^+xh^.L(x,\hat h)=\log\hat h+\frac{x}{\hat h}.

For positive targets, this differs from the normalised expression x/h^−log⁡(x/h^)−1x/\hat h-\log(x/\hat h)-1 by a target-only constant. The two forms therefore rank methods identically on the same observations. The expression we use also remains defined on a day with exactly zero return.

Changing return units shifts the reported loss level, so absolute QLIKE scores need their units stated. Differences between methods on the same targets retain their interpretation. A percentage improvement calculated by dividing these loss scores would depend on the arbitrary unit choice.

Out-of-sample mean QLIKE loss for GARCH, EWMA and a 20-day rolling baseline at one-day and 20-day horizons.

Forecast targetGARCHEWMA20-day rolling
Next trading day's variance0.8370.8760.938
Next 20 days' average variance1.0541.1291.202

GARCH has the lowest average loss in this comparison. Its advantage over EWMA is about 0.039 at one day and 0.076 over the next 20 days. Longer horizons expose the difference between GARCH's mean-reverting expected path and EWMA's flat expected path, although this experiment does not separately identify which fitted parameter causes the improvement.

The approximate 95% intervals for GARCH minus EWMA are [-0.063, -0.014] and [-0.142, -0.010]. They use a Bartlett heteroskedasticity and autocorrelation consistent estimate with 40 lags. Overlapping 20-day targets share observations, so treating all loss differences as independent would give misleading precision.

These intervals describe this forecasting protocol and sample. Their coverage depends on the large-sample approximation and dependence assumptions. We have not tested a collection of window lengths to pick the one with the best score. A different asset, evaluation period or refit policy needs its own comparison.

Innovation Distributions

GARCH with Gaussian innovations can produce heavy-tailed unconditional returns because its conditional scale changes over time. Mixing narrow calm-day distributions with wide stress-day distributions creates more extreme observations than a single fixed-variance Gaussian would predict.

That mechanism does not require standardised residuals to be Gaussian in real data. Divide each return by its fitted conditional standard deviation, then compare the resulting quantiles with the assumed innovation distribution. Residual tail differences point to a remaining distributional mismatch after the volatility scale has been modelled.

QQ plots of standardised GARCH residuals against Gaussian and unit-variance Student-t theoretical quantiles.

The second panel refits the likelihood using Student-t innovations. We scale a conventional Student-t random variable by (ν−2)/ν\sqrt{(\nu-2)/\nu} so the innovations have variance one. Without that scaling, the recursion's variance would no longer be the conditional variance attributed to the return.

The fitted degrees of freedom are about 6.64. The Student-t log-likelihood is -9,110.76, compared with -9,249.10 for the Gaussian fit. That is an in-sample comparison with an extra fitted parameter. The QQ plot still contains deviations, and the out-of-sample table above evaluates Gaussian GARCH only.

Changing the innovation distribution can also change the variance parameters, because it changes how the likelihood scores large residuals. The notebook implements and checks both likelihoods. Adding Student-t GARCH to the walk-forward table is an exercise, so the in-sample tail fit cannot be mistaken for measured forecasting superiority.

Model Limits

The symmetric recursion responds equally to a positive and negative return of the same magnitude. Financial markets can respond differently to falls and rises. An asymmetric model such as GJR-GARCH or EGARCH provides a candidate when residual diagnostics indicate that sign carries additional information.

Persistence estimated near one can reflect long-lived shocks, parameter uncertainty or unmodelled structural changes. A single long-run variance then becomes hard to interpret. Comparing rolling estimates and checking residual dependence can reveal whether the fixed specification is missing systematic structure.

Annualising a daily standard deviation with 252\sqrt{252} gives a conventional annualised scale. A forecast of variance over a particular future holding period instead sums that period's conditional variance forecasts, under the model's zero return-autocovariance assumption. Near a stress event, multiplying tomorrow's variance by the horizon can differ substantially from summing a mean-reverting path.

GARCH supplies a scale forecast. Portfolio use also requires a mean model, cross-asset dependence estimates and a sizing rule. Modern portfolio theory develops the covariance part, while multivariate BOCD examines changes across assets. A univariate forecast alone leaves those other quantities unspecified.

Foundations

Engle's ARCH Model

Engle (1982) introduced autoregressive conditional heteroscedasticity, or ARCH. The model lets the conditional variance depend on earlier squared errors. Engle's empirical application concerned UK inflation uncertainty, showing that changing variance could be part of a regression model's specification.

For ARCH with qq shock lags, the conditional variance is:

ht=ω+∑i=1qαiϵt−i2.h_t=\omega+\sum_{i=1}^{q}\alpha_i\epsilon_{t-i}^2.

The residual ϵt\epsilon_t is the observation minus its conditional mean. In our zero-mean return example, it equals rtr_t. This keeps the notebook focused on the variance calculation while preserving the distinction needed for a regression or autoregressive mean model.

An ARCH model stores past squared residuals explicitly. To describe effects that last a long time, it can require many lag terms. Estimating those coefficients introduces additional constraints and parameters. The next development compresses that history into a recursively updated state.

ARCH, GARCH and EWMA diagrams contrasting explicit shock lags, stored variance and the absence of a baseline in EWMA.

Bollerslev's GARCH Extension

Bollerslev (1986) added lagged conditional variances to the ARCH equation. The paper describes this as allowing “a more parsimonious description in many situations.” Its GARCH(1,1) case uses one squared-residual lag and one variance lag.

Expanding our recursion backwards gives:

ht=ω1−β+α∑j=1∞βj−1rt−j2,β<1,h_t=\frac{\omega}{1-\beta} +\alpha\sum_{j=1}^{\infty}\beta^{j-1}r_{t-j}^2, \qquad \beta<1,

with the initial-state contribution vanishing in the stationary expansion. One recursive variance state represents an infinite sequence of geometrically declining shock weights. This identity connects the compact implementation to a long-memory-shaped ARCH lag pattern, without claiming that geometric decay is statistical long memory in the strict sense.

The paper's finite-second-moment condition becomes α+β<1\alpha+\beta<1 in this case. Our optimiser enforces that restriction explicitly. The notebook's backcast approximates the unobserved pre-sample state needed to start the finite-sample recursion.

EWMA and the Unit-Persistence Boundary

Setting ω=0\omega=0, α=1−λ\alpha=1-\lambda and β=λ\beta=\lambda recovers EWMA directly. The sum of the two coefficients is then one, so the stationary long-run-variance formula has no finite identified mean-reversion level. EWMA still produces conditional variance forecasts from its initial state.

Repeated substitution makes its observation weights explicit. The most recent squared return receives weight 1−λ1-\lambda, the previous one receives (1−λ)λ(1-\lambda)\lambda, and older weights decay geometrically. A rolling window instead gives equal weight to its last 20 observations and then removes each observation completely.

This algebra explains the practical comparison. All three methods can respond to a new shock. The rolling estimate removes it abruptly after 20 observations, EWMA gradually forgets individual observations, and GARCH additionally specifies a long-run expected level. The measured table assesses the resulting forecasts on common future targets.

Patton's Forecast Evaluation

Patton (2011) analyses forecast comparison when the underlying conditional variance cannot be observed directly. A noisy volatility proxy can change the rankings produced by some loss functions, even when the proxy is conditionally unbiased.

Under the paper's assumptions, QLIKE preserves expected rankings when a conditionally unbiased proxy replaces the latent variance. This is an expectation result. A finite sample of squared daily returns can still produce a noisy comparison, which is why the experiment reports paired uncertainty alongside average loss.

The distinction also explains our choice of target. The expected squared return equals conditional variance under the zero-mean model. The expected absolute return generally does not equal conditional standard deviation. Comparing a volatility line with absolute returns by eye is useful for inspection, but it does not define an unbiased standard-deviation target for a forecasting contest.

For the 20-day calculation, averaging both future squared returns and forecast daily variances keeps the quantities aligned. Predicting the variance of the return on day 20, the average variance over 20 days, and the variance of a 20-day cumulative return are three different tasks. The notebook implements the middle one explicitly.

Interactive Tools

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions