Conditional volatility: ARCH and GARCH
Financial returns can have little predictability in the mean while volatility clusters. This lesson develops stylized facts, martingale differences, ARCH and GARCH, stationarity and moment conditions, quasi-maximum likelihood estimation, asymmetric variants and Student-t innovations, and volatility forecasting and evaluation against realized volatility.
After this lesson you can
- Check stylized facts in return data using ACFs of levels, squares and absolute values, and tail behavior.
- Derive moments, stationarity conditions and the ARMA representation of ε_t² in GARCH(1,1).
- Implement Gaussian and Student-t GARCH(1,1) quasi-likelihood from scratch and estimate it with constraints.
- Compare GARCH, EGARCH and GJR using news impact curves and information criteria.
- Forecast the volatility term structure and evaluate it with QLIKE against intraday realized volatility.
Before you start
- 26White noise and its variantsAutocorrelation functionPortmanteau tests (Box-Pierce and Ljung-Box)ARMA modelMartingaleResidual diagnostics
- 05Maximum likelihood estimator (MLE)M-estimators and Z-estimatorsSandwich variance estimatorNormal sampling theory: chi-squared, Student t and F distributionsNumerically stable maximum likelihood
- 04Heavy-tailed distributions
- 06Projected gradient descent
Uncertainty has memory too
Tomorrow’s return can have a small conditional mean and uncertainty that changes considerably between calm and turbulent days. Pricing options or sizing a position requires distinguishing these two questions. In the figure, innovations are unpredictable in the mean, but the size of their fluctuations depends on history.
Stylized facts and dependent noise
The stylized facts of returns include episodes of volatility clustering, heavier tails than a comparable normal distribution, and persistent dependence in magnitudes or squares. These are empirical patterns that vary by asset, period and frequency, not exact laws for every sample. Calculate autocorrelations of returns, squares and absolute values; the absence of linear autocorrelation does not prove independence or rule out predictability in the mean.
A martingale difference satisfies . If it has a finite second moment, values at different times are uncorrelated, even though its conditional variance and squares can depend on the past. Model the mean first: residual autocorrelation can contaminate volatility diagnostics.
ARCH y GARCH
An ARCH() model writes and , with , and iid innovations that are centered, have variance one and are independent of the past. An ARCH-LM test fits an auxiliary regression of squared residuals on a constant and lags; under the null and regularity conditions, has asymptotic reference distribution . Lag choice and prior mean estimation matter. Engle introduced the ARCH family.
GARCH(1,1) adds a lagged variance:
If , the stationary solution has finite variance . This condition is not equivalent to strict stationarity: under the usual integrability assumptions, the random recursion criterion is . A strictly stationary solution can exist without finite variance. In a simulation initialized with finite , each finite horizon can still have finite variance even when no finite stationary unconditional variance exists. Bollerslev develops GARCH.
For normal innovations, the fourth moment is finite if . Then kurtosis, without subtracting three, is
Even with normal , the mixture of variances can produce heavier tails. The population ACF of requires that fourth moment; a sample ACF can always be drawn if its denominators are finite, but that does not prove its population counterpart exists.
Define . Under the necessary moment assumptions, is white noise and
This is an ARMA representation of the squares, not a claim that returns are ARMA with the same persistence. For , a deviation of the variance forecast halves in steps. Estimated persistence near one does not prove long memory: a regime break can produce apparent persistence.
Estimation without assuming normality is the truth
Gaussian quasi-maximum likelihood minimizes, up to a constant, using the recursion for each parameter value. The mean is estimated or removed consistently. Initialization of affects the fit, particularly with short samples and high persistence; compare initializations and do not treat the first value as observed.
For , and one can optimize transformed parameters or impose constraints. The finite-variance condition restricts the estimated model, although it does not cover every strictly stationary process. The normal can be used as a quasi-likelihood when it does not describe the full distribution; robust uncertainty uses the sandwich form under applicable consistency, identifiability and moment conditions. Without those assumptions the label “robust” is insufficient. A Student with must be rescaled to variance one; the fourth moment requires .
Positive and negative news
In symmetric GARCH, a shock of or with the same magnitude produces the same next . GJR-GARCH adds ; a sufficient parameterization for positivity is , and . EGARCH models log variance and can capture asymmetry without imposing positivity directly on each coefficient.
In an EGARCH(1,1) specification, with ,
Exponentiation guarantees ; with , two standardized innovations of equal magnitude have a greater log-variance impact when the innovation is negative. For a standard normal, . A skewed Student innovation can also model asymmetry in the return distribution: it must be standardized to mean zero and variance one, and its parameters estimated consistently. With asymmetric innovations, GJR second-moment persistence is ; replacing the final factor by requires symmetry and unit variance. The arch documentation describes its standardized distributions.
The figure uses three models fitted to the same index and holds the previous variance at a common level: it compares news impacts at a common state, not a historical reconstruction of the three filters. The local code reproduces their parameters from the indicated series.
Forecasting variance and evaluating forecasts
Volatility forecasting starts from , which is known with information through . For ,
The square root of that expectation is a risk scale, not necessarily . If the future mean is deterministic and innovations are martingale differences with sufficient moments, the conditional variance of cumulative returns is the sum of forecast variances. With a random dynamic mean or additional autocovariances, their effects must be included. A 21-session month is a convention, not a universal calendar.
Latent variance is not directly observed. A daily squared return is a noisy proxy; intraday realized variance sums squared returns at a higher frequency, with caveats about microstructure and time coverage. For a positive forecast and nonnegative proxy , use the QLIKE form . If the proxy is conditionally unbiased for the target variance and the comparison assumptions hold, the expected QLIKE difference between two forecasts measurable with available information preserves their ordering with latent variance. Absolute error does not have that general property. MSE can also preserve expected ordering under suitable conditions; QLIKE and MSE rankings can differ because they weight errors differently. Patton specifies these conditions.
GARCH is a univariate conditional variance filter; DCC models conditional correlations among several series, while stochastic volatility models introduce latent volatility and require other inference methods. Realized volatility models explicitly incorporate intraday information.
Lab: stylized facts with historical data
The fixed sample is the same as in the stationarity lesson: 503 S&P 500 closes from January 2, 2018 to December 31, 2019, included in Vega Datasets. We reproduce the data inside the cell to avoid depending on a download. These are index levels excluding dividends; returns are log differences in percentage points between consecutive sessions.
import numpy as np
from scipy.stats import chi2, kurtosis
from scipy.special import gammaln
from scipy.optimize import minimize
from scipy.signal import lfilter
from statsmodels.stats.diagnostic import het_arch
precios = np.array([2695.810059,2713.060059,2723.989990,2743.149902,2747.709961,2751.290039,2748.229980,2767.560059,2786.239990,2776.419922,2802.560059,2798.030029,2810.300049,2832.969971,2839.129883,2837.540039,2839.250000,2872.870117,2853.530029,2822.429932,2823.810059,2821.979980,2762.129883,2648.939941,2695.139893,2681.659912,2581.000000,2619.550049,2656.000000,2662.939941,2698.629883,2731.199951,2732.219971,2716.260010,2701.330078,2703.959961,2747.300049,2779.600098,2744.280029,2713.830078,2677.669922,2691.250000,2720.939941,2728.120117,2726.800049,2738.969971,2786.570068,2783.020020,2765.310059,2749.479980,2747.330078,2752.010010,2712.919922,2716.939941,2711.929932,2643.689941,2588.260010,2658.550049,2612.620117,2605.000000,2640.870117,2581.879883,2614.449951,2644.689941,2662.840088,2604.469971,2613.159912,2656.870117,2642.189941,2663.989990,2656.300049,2677.840088,2706.389893,2708.639893,2693.129883,2670.139893,2670.290039,2634.560059,2639.399902,2666.939941,2669.909912,2648.050049,2654.800049,2635.669922,2629.729980,2663.419922,2672.629883,2671.919922,2697.790039,2723.070068,2727.719971,2730.129883,2711.449951,2722.459961,2720.129883,2712.969971,2733.010010,2724.439941,2733.290039,2727.760010,2721.330078,2689.860107,2724.010010,2705.270020,2734.620117,2746.870117,2748.800049,2772.350098,2770.370117,2779.030029,2782.000000,2786.850098,2775.629883,2782.489990,2779.659912,2773.750000,2762.590088,2767.320068,2749.760010,2754.879883,2717.070068,2723.060059,2699.629883,2716.310059,2718.370117,2726.709961,2713.219971,2736.610107,2759.820068,2784.169922,2793.840088,2774.020020,2798.290039,2801.310059,2798.429932,2809.550049,2815.620117,2804.489990,2801.830078,2806.979980,2820.399902,2846.070068,2837.439941,2818.820068,2802.600098,2816.290039,2813.360107,2827.219971,2840.350098,2850.399902,2858.449951,2857.699951,2853.580078,2833.280029,2821.929932,2839.959961,2818.370117,2840.689941,2850.129883,2857.050049,2862.959961,2861.820068,2856.979980,2874.689941,2896.739990,2897.520020,2914.040039,2901.129883,2901.520020,2896.719971,2888.600098,2878.050049,2871.679932,2877.129883,2887.889893,2888.919922,2904.179932,2904.979980,2888.800049,2904.310059,2907.949951,2930.750000,2929.669922,2919.370117,2915.560059,2905.969971,2914.000000,2913.979980,2924.590088,2923.429932,2925.510010,2901.610107,2885.570068,2884.429932,2880.340088,2785.679932,2728.370117,2767.129883,2750.790039,2809.919922,2809.209961,2768.780029,2767.780029,2755.879883,2740.689941,2656.100098,2705.570068,2658.689941,2641.250000,2682.629883,2711.739990,2740.370117,2723.060059,2738.310059,2755.449951,2813.889893,2806.830078,2781.010010,2726.219971,2722.179932,2701.580078,2730.199951,2736.270020,2690.729980,2641.889893,2649.929932,2632.560059,2673.449951,2682.169922,2743.790039,2737.800049,2760.169922,2790.370117,2700.060059,2695.949951,2633.080078,2637.719971,2636.780029,2651.070068,2650.540039,2599.949951,2545.939941,2546.159912,2506.959961,2467.419922,2416.620117,2351.100098,2467.699951,2488.830078,2485.739990,2506.850098,2510.030029,2447.889893,2531.939941,2549.689941,2574.409912,2584.959961,2596.639893,2596.260010,2582.610107,2610.300049,2616.100098,2635.959961,2670.709961,2632.899902,2638.699951,2642.330078,2664.760010,2643.850098,2640.000000,2681.050049,2704.100098,2706.530029,2724.870117,2737.699951,2731.610107,2706.050049,2707.879883,2709.800049,2744.729980,2753.030029,2745.729980,2775.600098,2779.760010,2784.699951,2774.879883,2792.669922,2796.110107,2793.899902,2792.379883,2784.489990,2803.689941,2792.810059,2789.649902,2771.449951,2748.929932,2743.070068,2783.300049,2791.520020,2810.919922,2808.479980,2822.479980,2832.939941,2832.570068,2824.229980,2854.879883,2800.709961,2798.360107,2818.459961,2805.370117,2815.439941,2834.399902,2867.189941,2867.239990,2873.399902,2879.389893,2892.739990,2895.770020,2878.199951,2888.209961,2888.320068,2907.409912,2905.580078,2907.060059,2900.449951,2905.030029,2907.969971,2933.679932,2927.250000,2926.169922,2939.879883,2943.030029,2945.830078,2923.729980,2917.520020,2945.639893,2932.469971,2884.050049,2879.419922,2870.719971,2881.399902,2811.870117,2834.409912,2850.959961,2876.320068,2859.530029,2840.229980,2864.360107,2856.270020,2822.239990,2826.060059,2802.389893,2783.020020,2788.860107,2752.060059,2744.449951,2803.270020,2826.149902,2843.489990,2873.340088,2886.729980,2885.719971,2879.840088,2891.639893,2886.979980,2889.669922,2917.750000,2926.459961,2954.179932,2950.459961,2945.350098,2917.379883,2913.780029,2924.919922,2941.760010,2964.330078,2973.010010,2995.820068,2990.409912,2975.949951,2979.629883,2993.070068,2999.909912,3013.770020,3014.300049,3004.040039,2984.419922,2995.110107,2976.610107,2985.030029,3005.469971,3019.560059,3003.669922,3025.860107,3020.969971,3013.179932,2980.379883,2953.560059,2932.050049,2844.739990,2881.770020,2883.979980,2938.090088,2918.649902,2882.699951,2926.320068,2840.600098,2847.600098,2888.679932,2923.649902,2900.510010,2924.429932,2922.949951,2847.110107,2878.379883,2869.159912,2887.939941,2924.580078,2926.459961,2906.270020,2937.780029,2976.000000,2978.709961,2978.429932,2979.389893,3000.929932,3009.570068,3007.389893,2997.959961,3005.699951,3006.729980,3006.790039,2992.070068,2991.780029,2966.600098,2984.870117,2977.620117,2961.790039,2976.739990,2940.250000,2887.610107,2910.629883,2952.010010,2938.790039,2893.060059,2919.399902,2938.129883,2970.270020,2966.149902,2995.679932,2989.689941,2997.949951,2986.199951,3006.719971,2995.989990,3004.520020,3010.290039,3022.550049,3039.419922,3036.889893,3046.770020,3037.560059,3066.909912,3078.270020,3074.620117,3076.780029,3085.179932,3093.080078,3087.010010,3091.840088,3094.040039,3096.629883,3120.459961,3122.030029,3120.179932,3108.459961,3103.540039,3110.290039,3133.639893,3140.520020,3153.629883,3140.979980,3113.870117,3093.199951,3112.760010,3117.429932,3145.909912,3135.959961,3132.520020,3141.629883,3168.570068,3168.800049,3191.449951,3192.520020,3191.139893,3205.370117,3221.219971,3224.010010,3223.379883,3239.909912,3240.020020,3221.290039,3230.780029], dtype=float)
r = 100*np.diff(np.log(precios))
def acf_muestra(x, H):
z = np.asarray(x)-np.mean(x)
return np.array([z[h:]@z[:-h]/(z@z) for h in range(1,H+1)])
resid = r-r.mean()
lm, p_lm, _, _ = het_arch(resid,nlags=5,ddof=1)
print("cierres y rendimientos:", len(precios),len(r))
print("ACF r, r² y |r| para retardos 1 a 3:",
acf_muestra(resid,3),acf_muestra(resid**2,3),acf_muestra(abs(resid),3))
print("curtosis muestral no corregida y ARCH-LM:", kurtosis(resid,fisher=False,bias=True),lm,p_lm)The test diagnoses the chosen specification; it does not prove a particular GARCH model is correct. Descriptive estimates and the test vary with the window; the index is not a sample of every asset class.
Lab: recursion and likelihood
The manual recursion initializes with sample variance and uses the previous return to calculate each subsequent variance. To speed optimization of the same recurrence, the filtered function applies a linear filter to ; both are compared numerically before fitting. The Student parameter is degrees of freedom, and the density uses a rescaled so that has variance one.
def garch_varianza(omega, alpha, beta, eps, h0):
h = np.empty(len(eps))
h[0] = h0
for t in range(1,len(eps)):
h[t] = omega+alpha*eps[t-1]**2+beta*h[t-1]
return h
def garch_filtrada(omega, alpha, beta, eps, h0):
if len(eps) == 1:
return np.array([h0])
entradas = omega+alpha*eps[:-1]**2
resto, _ = lfilter([1.],[1.,-beta],entradas,zi=[beta*h0])
return np.r_[h0,resto]
def aportaciones(params, datos, dist="normal"):
mu, omega, alpha, beta = params[:4]
if omega <= 0 or min(alpha,beta) < 0 or alpha+beta >= 1:
return None
eps = datos-mu
h0 = np.var(datos)
if h0 <= 0:
return None
h = garch_filtrada(omega,alpha,beta,eps,h0)
if dist == "normal":
return .5*(np.log(2*np.pi)+np.log(h)+eps**2/h)
if dist == "t":
nu = params[4]
if nu <= 2:
return None
constante = gammaln(nu/2)-gammaln((nu+1)/2)+.5*np.log(np.pi*(nu-2))
return constante+.5*np.log(h)+.5*(nu+1)*np.log1p(eps**2/(h*(nu-2)))
raise ValueError("distribución desconocida")
def neglog(params,datos,dist="normal"):
partes = aportaciones(params,datos,dist)
return 1e100 if partes is None else partes.sum()
h0 = np.var(resid)
hm = garch_varianza(.04,.12,.82,resid,h0)
hf = garch_filtrada(.04,.12,.82,resid,h0)
print("diferencia máxima entre recursiones:", np.max(abs(hm-hf)))
print("neglog normal y t de prueba:",
neglog([r.mean(),.04,.12,.82],r),
neglog([r.mean(),.04,.12,.82,8.],r,"t"))We optimize with explicit constraints and check convergence. Compare distributions with care: includes an additional parameter, and normal QMLE does not mean declaring all innovations normal.
def ajustar_garch(datos, dist="normal"):
v = np.var(datos)
inicial = [np.mean(datos), .05*v, .08, .85]
limites = [(None,None), (1e-8,None), (0,.999), (0,.999)]
if dist == "t":
inicial += [8.]
limites += [(2.05,100.)]
restricciones = [{"type":"ineq","fun":lambda p: .999-p[2]-p[3]}]
ajuste = minimize(neglog,inicial,args=(datos,dist),method="SLSQP",
bounds=limites,constraints=restricciones,
options={"maxiter":200,"ftol":1e-7})
if not ajuste.success:
raise RuntimeError(ajuste.message)
return ajuste
normal = ajustar_garch(r)
student = ajustar_garch(r,"t")
print("parámetros normal μ, ω, α, β:", normal.x)
print("parámetros t μ, ω, α, β, ν:", student.x)
print("log-verosimilitudes normal y t:", -normal.fun,-student.fun)For the sandwich estimator, we numerically approximate the matrix of second derivatives and individual score contributions, retaining the same initialization. The matrix can be unstable near boundaries or if the sample does not identify parameters well. This estimate is a local diagnostic, not a coverage certificate.
def sandwich(params, datos):
p = np.asarray(params,dtype=float)
paso = 1e-4*np.maximum(1,abs(p))
if (len(p) != 4 or not np.all(np.isfinite(p)) or
p[1] <= 2*paso[1] or p[2] <= 2*paso[2] or p[3] <= 2*paso[3] or
p[2]+p[3]+2*(paso[2]+paso[3]) >= 1):
raise ValueError("esténcil fuera del interior: el sándwich numérico no es aplicable")
k = len(p)
score = np.empty((len(datos),k))
H = np.empty((k,k))
for i in range(k):
ei = np.zeros(k); ei[i] = paso[i]
score[:,i] = (aportaciones(p+ei,datos)-aportaciones(p-ei,datos))/(2*paso[i])
for j in range(k):
ej = np.zeros(k); ej[j] = paso[j]
H[i,j] = (neglog(p+ei+ej,datos)-neglog(p+ei-ej,datos)
-neglog(p-ei+ej,datos)+neglog(p-ei-ej,datos))/(4*paso[i]*paso[j])
Hinv = np.linalg.inv(H)
cov = Hinv@(score.T@score)@Hinv.T
return np.sqrt(np.maximum(np.diag(cov),0)), np.linalg.cond(H)
se, condicion = sandwich(normal.x,r)
print("errores sándwich y condición del Hessiano:", se,condicion)
try:
sandwich([0.,.04,0.,.9],r)
except ValueError as exc:
print("control de frontera:", exc)
else:
raise AssertionError("debería rechazarse un esténcil en la frontera")The following comparison requires a local environment with arch and its dependencies; it does not run in Pyodide. It repeats the sample to be self-contained. If a recent version of pandas requires the new argument of the decorator used by an older version of arch, the adapter operates only in this process. The earlier figure uses these constant-mean and normal-innovation fits, with the sample variance of returns as the common state. Numerical optimization differences can change the last decimal places.
import inspect
import numpy as np
import pandas.util._decorators as decoradores
original = decoradores.deprecate_kwarg
if list(inspect.signature(original).parameters)[0] == "klass":
def compatible(*args, **kwargs):
if args and isinstance(args[0],str):
return original(FutureWarning,*args,**kwargs)
return original(*args,**kwargs)
decoradores.deprecate_kwarg = compatible
from arch import arch_model
precios = np.array([2695.810059,2713.060059,2723.989990,2743.149902,2747.709961,2751.290039,2748.229980,2767.560059,2786.239990,2776.419922,2802.560059,2798.030029,2810.300049,2832.969971,2839.129883,2837.540039,2839.250000,2872.870117,2853.530029,2822.429932,2823.810059,2821.979980,2762.129883,2648.939941,2695.139893,2681.659912,2581.000000,2619.550049,2656.000000,2662.939941,2698.629883,2731.199951,2732.219971,2716.260010,2701.330078,2703.959961,2747.300049,2779.600098,2744.280029,2713.830078,2677.669922,2691.250000,2720.939941,2728.120117,2726.800049,2738.969971,2786.570068,2783.020020,2765.310059,2749.479980,2747.330078,2752.010010,2712.919922,2716.939941,2711.929932,2643.689941,2588.260010,2658.550049,2612.620117,2605.000000,2640.870117,2581.879883,2614.449951,2644.689941,2662.840088,2604.469971,2613.159912,2656.870117,2642.189941,2663.989990,2656.300049,2677.840088,2706.389893,2708.639893,2693.129883,2670.139893,2670.290039,2634.560059,2639.399902,2666.939941,2669.909912,2648.050049,2654.800049,2635.669922,2629.729980,2663.419922,2672.629883,2671.919922,2697.790039,2723.070068,2727.719971,2730.129883,2711.449951,2722.459961,2720.129883,2712.969971,2733.010010,2724.439941,2733.290039,2727.760010,2721.330078,2689.860107,2724.010010,2705.270020,2734.620117,2746.870117,2748.800049,2772.350098,2770.370117,2779.030029,2782.000000,2786.850098,2775.629883,2782.489990,2779.659912,2773.750000,2762.590088,2767.320068,2749.760010,2754.879883,2717.070068,2723.060059,2699.629883,2716.310059,2718.370117,2726.709961,2713.219971,2736.610107,2759.820068,2784.169922,2793.840088,2774.020020,2798.290039,2801.310059,2798.429932,2809.550049,2815.620117,2804.489990,2801.830078,2806.979980,2820.399902,2846.070068,2837.439941,2818.820068,2802.600098,2816.290039,2813.360107,2827.219971,2840.350098,2850.399902,2858.449951,2857.699951,2853.580078,2833.280029,2821.929932,2839.959961,2818.370117,2840.689941,2850.129883,2857.050049,2862.959961,2861.820068,2856.979980,2874.689941,2896.739990,2897.520020,2914.040039,2901.129883,2901.520020,2896.719971,2888.600098,2878.050049,2871.679932,2877.129883,2887.889893,2888.919922,2904.179932,2904.979980,2888.800049,2904.310059,2907.949951,2930.750000,2929.669922,2919.370117,2915.560059,2905.969971,2914.000000,2913.979980,2924.590088,2923.429932,2925.510010,2901.610107,2885.570068,2884.429932,2880.340088,2785.679932,2728.370117,2767.129883,2750.790039,2809.919922,2809.209961,2768.780029,2767.780029,2755.879883,2740.689941,2656.100098,2705.570068,2658.689941,2641.250000,2682.629883,2711.739990,2740.370117,2723.060059,2738.310059,2755.449951,2813.889893,2806.830078,2781.010010,2726.219971,2722.179932,2701.580078,2730.199951,2736.270020,2690.729980,2641.889893,2649.929932,2632.560059,2673.449951,2682.169922,2743.790039,2737.800049,2760.169922,2790.370117,2700.060059,2695.949951,2633.080078,2637.719971,2636.780029,2651.070068,2650.540039,2599.949951,2545.939941,2546.159912,2506.959961,2467.419922,2416.620117,2351.100098,2467.699951,2488.830078,2485.739990,2506.850098,2510.030029,2447.889893,2531.939941,2549.689941,2574.409912,2584.959961,2596.639893,2596.260010,2582.610107,2610.300049,2616.100098,2635.959961,2670.709961,2632.899902,2638.699951,2642.330078,2664.760010,2643.850098,2640.000000,2681.050049,2704.100098,2706.530029,2724.870117,2737.699951,2731.610107,2706.050049,2707.879883,2709.800049,2744.729980,2753.030029,2745.729980,2775.600098,2779.760010,2784.699951,2774.879883,2792.669922,2796.110107,2793.899902,2792.379883,2784.489990,2803.689941,2792.810059,2789.649902,2771.449951,2748.929932,2743.070068,2783.300049,2791.520020,2810.919922,2808.479980,2822.479980,2832.939941,2832.570068,2824.229980,2854.879883,2800.709961,2798.360107,2818.459961,2805.370117,2815.439941,2834.399902,2867.189941,2867.239990,2873.399902,2879.389893,2892.739990,2895.770020,2878.199951,2888.209961,2888.320068,2907.409912,2905.580078,2907.060059,2900.449951,2905.030029,2907.969971,2933.679932,2927.250000,2926.169922,2939.879883,2943.030029,2945.830078,2923.729980,2917.520020,2945.639893,2932.469971,2884.050049,2879.419922,2870.719971,2881.399902,2811.870117,2834.409912,2850.959961,2876.320068,2859.530029,2840.229980,2864.360107,2856.270020,2822.239990,2826.060059,2802.389893,2783.020020,2788.860107,2752.060059,2744.449951,2803.270020,2826.149902,2843.489990,2873.340088,2886.729980,2885.719971,2879.840088,2891.639893,2886.979980,2889.669922,2917.750000,2926.459961,2954.179932,2950.459961,2945.350098,2917.379883,2913.780029,2924.919922,2941.760010,2964.330078,2973.010010,2995.820068,2990.409912,2975.949951,2979.629883,2993.070068,2999.909912,3013.770020,3014.300049,3004.040039,2984.419922,2995.110107,2976.610107,2985.030029,3005.469971,3019.560059,3003.669922,3025.860107,3020.969971,3013.179932,2980.379883,2953.560059,2932.050049,2844.739990,2881.770020,2883.979980,2938.090088,2918.649902,2882.699951,2926.320068,2840.600098,2847.600098,2888.679932,2923.649902,2900.510010,2924.429932,2922.949951,2847.110107,2878.379883,2869.159912,2887.939941,2924.580078,2926.459961,2906.270020,2937.780029,2976.000000,2978.709961,2978.429932,2979.389893,3000.929932,3009.570068,3007.389893,2997.959961,3005.699951,3006.729980,3006.790039,2992.070068,2991.780029,2966.600098,2984.870117,2977.620117,2961.790039,2976.739990,2940.250000,2887.610107,2910.629883,2952.010010,2938.790039,2893.060059,2919.399902,2938.129883,2970.270020,2966.149902,2995.679932,2989.689941,2997.949951,2986.199951,3006.719971,2995.989990,3004.520020,3010.290039,3022.550049,3039.419922,3036.889893,3046.770020,3037.560059,3066.909912,3078.270020,3074.620117,3076.780029,3085.179932,3093.080078,3087.010010,3091.840088,3094.040039,3096.629883,3120.459961,3122.030029,3120.179932,3108.459961,3103.540039,3110.290039,3133.639893,3140.520020,3153.629883,3140.979980,3113.870117,3093.199951,3112.760010,3117.429932,3145.909912,3135.959961,3132.520020,3141.629883,3168.570068,3168.800049,3191.449951,3192.520020,3191.139893,3205.370117,3221.219971,3224.010010,3223.379883,3239.909912,3240.020020,3221.290039,3230.780029], dtype=float)
rend = 100*np.diff(np.log(precios))
for nombre, opciones in (
("GARCH", dict(vol="GARCH",p=1,o=0,q=1)),
("GJR", dict(vol="GARCH",p=1,o=1,q=1)),
("EGARCH", dict(vol="EGARCH",p=1,o=1,q=1))
):
modelo = arch_model(rend,mean="Constant",dist="normal",**opciones)
ajuste = modelo.fit(disp="off")
print(nombre,"convergencia",ajuste.convergence_flag,"parámetros",ajuste.params.to_dict(),
"log-verosimilitud",ajuste.loglikelihood,"AIC",ajuste.aic)
if nombre == "GARCH":
par = ajuste.params
eps = rend-par["mu"]
backcast = modelo.volatility.backcast(modelo.resids(modelo.starting_values()))
h = np.empty(len(eps))
h[0] = par["omega"]+(par["alpha[1]"]+par["beta[1]"])*backcast
for t in range(1,len(eps)):
h[t] = par["omega"]+par["alpha[1]"]*eps[t-1]**2+par["beta[1]"]*h[t-1]
ll = -.5*np.sum(np.log(2*np.pi)+np.log(h)+eps**2/h)
print("diferencia máxima de varianza y de log-verosimilitud:",
np.max(abs(h-ajuste.conditional_volatility**2)),ll-ajuste.loglikelihood)
print("varianza muestral común, ddof=0:", np.var(rend))npm run lab and open the connection link.The browser cell and arch may yield slightly different parameters and log-likelihoods because they use different initializations. The comparison on the last line fixes arch’s backcast and checks the recursion and likelihood under exactly the same initialization.
Lab: sample size and bias
We simulate Gaussian GARCH with known parameters and estimate each trajectory without using its true values for initialization. The few replicates are a quick trial, not a precise bias estimate or a guarantee of recovering parameters within one standard error. Compare the distribution of errors and increase the number of replicates for a serious analysis.
def simular_garch(n, omega, alpha, beta, rng, burn=300):
z = rng.normal(size=n+burn)
eps = np.zeros(n+burn)
h = np.empty(n+burn)
h[0] = omega/(1-alpha-beta)
eps[0] = np.sqrt(h[0])*z[0]
for t in range(1,n+burn):
h[t] = omega+alpha*eps[t-1]**2+beta*h[t-1]
eps[t] = np.sqrt(h[t])*z[t]
return eps[burn:]
def ensayo(n, replicas, seed):
rng = np.random.default_rng(seed)
verdad = np.array([0.,.04,.08,.88])
estimaciones = []
for _ in range(replicas):
muestra = simular_garch(n,*verdad[1:],rng)
estimaciones.append(ajustar_garch(muestra).x)
estimaciones = np.array(estimaciones)
return estimaciones.mean(axis=0)-verdad, estimaciones.std(axis=0,ddof=1)
sesgo_500, dispersion_500 = ensayo(500,8,181)
print("sesgo y dispersión con n=500, 8 réplicas:", sesgo_500,dispersion_500)sesgo_5000, dispersion_5000 = ensayo(5000,8,182)
print("sesgo y dispersión con n=5000, 8 réplicas:", sesgo_5000,dispersion_5000)In an additional trajectory we compare the true parameters with the estimate’s sandwich standard error. An approximate two-standard-error interval does not guarantee coverage in every realization; if a value falls outside, the output shows it.
muestra = simular_garch(5000,.04,.08,.88,np.random.default_rng(184))
estimado = ajustar_garch(muestra)
error_est, condicion_est = sandwich(estimado.x,muestra)
verdadero = np.array([0.,.04,.08,.88])
print("verdadero y estimado:", verdadero,estimado.x)
print("errores sándwich y diferencias en unidades de error:",
error_est,(estimado.x-verdadero)/error_est)
print("condición del Hessiano:",condicion_est)Lab: rolling-origin forecasts
We construct a synthetic market with GJR volatility and 24 normal intraday increments per session. Their sum is the daily return and their sum of squares is a realized variance proxy. In this design the proxy’s conditional expectation equals latent daily variance: it does not represent microstructure, jumps or historical intraday data.
We train on a rolling window and recalibrate every 50 sessions. At each origin the model uses only previous observations; the evaluated day’s proxy enters only after the forecast is generated. The experiment compares GARCH, GJR, fixed-factor EWMA and HAR on the proxy. One synthetic window, seed and fixed parameters do not determine which method will win in other markets.
rng = np.random.default_rng(183)
N, intradia = 700, 24
retornos = np.zeros(N)
realizada = np.zeros(N)
var_latente = np.empty(N)
var_latente[0] = 1.
for t in range(N):
if t:
previo = retornos[t-1]
var_latente[t] = .04+(.06+.12*(previo<0))*previo**2+.84*var_latente[t-1]
tramos = np.sqrt(var_latente[t]/intradia)*rng.normal(size=intradia)
retornos[t] = tramos.sum()
realizada[t] = tramos@tramos
print("observaciones, proxy medio y varianza latente media:",
N,realizada.mean(),var_latente.mean())The GJR fit uses an additional term for negative shocks and constrains , the second-moment condition under symmetric unit-variance innovations. For GARCH we use the previous fit. Their means are estimated within each window.
def gjr_varianza(omega, alpha, gamma, beta, eps, h0):
insumos = omega+(alpha+gamma*(eps[:-1]<0))*eps[:-1]**2
resto, _ = lfilter([1.],[1.,-beta],insumos,zi=[beta*h0])
return np.r_[h0,resto]
def gjr_neglog(p,datos):
mu, omega, alpha, gamma, beta = p
if omega <= 0 or min(alpha,gamma,beta)<0 or alpha+.5*gamma+beta>=1:
return 1e100
eps = datos-mu
h = gjr_varianza(omega,alpha,gamma,beta,eps,np.var(datos))
return .5*np.sum(np.log(2*np.pi)+np.log(h)+eps**2/h)
def ajustar_gjr(datos):
v = np.var(datos)
inicial = [np.mean(datos),.05*v,.05,.08,.84]
limites = [(None,None),(1e-8,None),(0,.999),(0,1.998),(0,.999)]
restricciones = [{"type":"ineq","fun":lambda p: .999-p[2]-.5*p[3]-p[4]}]
ajuste = minimize(gjr_neglog,inicial,args=(datos,),method="SLSQP",
bounds=limites,constraints=restricciones,
options={"maxiter":200,"ftol":1e-7})
if not ajuste.success:
raise RuntimeError(ajuste.message)
return ajuste.xinicio, ventana, frecuencia = 450, 400, 50
pred_garch, pred_gjr = [], []
for t in range(inicio,N):
if (t-inicio)%frecuencia == 0:
muestra = retornos[t-ventana:t]
pg = ajustar_garch(muestra).x
pj = ajustar_gjr(muestra)
hg = garch_filtrada(*pg[1:],muestra-pg[0],np.var(muestra))[-1]
hj = gjr_varianza(*pj[1:],muestra-pj[0],np.var(muestra))[-1]
eg, ej = retornos[t-1]-pg[0], retornos[t-1]-pj[0]
hg = pg[1]+pg[2]*eg**2+pg[3]*hg
hj = pj[1]+(pj[2]+pj[3]*(ej<0))*ej**2+pj[4]*hj
pred_garch.append(hg)
pred_gjr.append(hj)
print("predicciones y mínimos positivos:",len(pred_garch),min(pred_garch),min(pred_gjr))EWMA updates variance with the previous return. HAR uses a regression with daily proxy, weekly average and average of the previous 22 sessions; nonpositive predictions are clipped to a declared positive minimum so QLIKE can be evaluated. This HAR is a simple implementation, not a universal recommendation.
def har_at(t):
return [1.,realizada[t-1],realizada[t-5:t].mean(),realizada[t-22:t].mean()]
ewma = np.var(retornos[:inicio])
for j in range(1,inicio):
ewma = .94*ewma+.06*retornos[j-1]**2
pred_ewma, pred_har = [], []
for t in range(inicio,N):
ewma = .94*ewma+.06*retornos[t-1]**2
pred_ewma.append(ewma)
if (t-inicio)%frecuencia == 0:
filas = np.arange(max(22,t-ventana),t)
diseño = np.array([har_at(j) for j in filas])
bh = np.linalg.lstsq(diseño,realizada[filas],rcond=None)[0]
pred_har.append(max(1e-8,float(np.array(har_at(t))@bh)))
proxy = realizada[inicio:]
predicciones = {"GARCH":pred_garch,"GJR":pred_gjr,"EWMA":pred_ewma,"HAR":pred_har}
for nombre, pred in predicciones.items():
f = np.asarray(pred)
qlike = np.mean(np.log(f)+proxy/f)
mse = np.mean((proxy-f)**2)
print(nombre,"QLIKE y MSE:",qlike,mse)
print("promedio del proxy y varianza latente en prueba:",
proxy.mean(),var_latente[inicio:].mean())
print("semividas en una rejilla de persistencias entre 0.8 y 0.99:",
[np.log(.5)/np.log(q) for q in np.linspace(.8,.99,20)])
print("curtosis ARCH normal en una rejilla de α entre 0.05 y 0.45:",
[3*(1-a*a)/(1-3*a*a) for a in np.linspace(.05,.45,9)])In this run, GJR obtains the lowest QLIKE of the four and HAR the lowest MSE. This compares a finite window with a simulated proxy; it proves no universal advantage and does not contradict the robustness of each loss’s expected ordering under its own assumptions. In an applied analysis retain the dates, compare across origins and quantify uncertainty in the loss difference.
Exercises
Step 1 of 3. Why does vₜ have conditional mean zero?
import numpy as np
from scipy.special import gammaln
def garch11_negloglik(params, r, dist):
pass
def score_garch(params, r, dist):
passGARCH converts past shocks and previous variance into a conditional forecast. Strict existence, the second moment and the fourth moment are different questions; forecast evaluation also depends on how variance is measured and which loss is chosen.