Stationarity, autocovariance and autocorrelation
With one observed path, inference requires that dependence structure remain stable over time. Distinguish strict and weak stationarity; study autocovariance and the ACF as nonnegative-definite objects; distinguish iid, martingale-difference and weak white noise; and study sample ACF with Bartlett's formula, portmanteau tests and the ergodicity that allows estimation by time averages.
After this lesson you can
- Decide whether a process is strictly or weakly stationary and construct counterexamples separating the notions.
- Prove that autocovariance is nonnegative definite and use this to reject candidate functions.
- Calculate and interpret sample ACF with appropriate Bartlett bands, distinguishing iid noise from MA(q).
- Apply Ljung-Box to residuals and squared returns and explain their different results.
- Calculate the variance of the sample mean of a dependent series and its effective sample size.
Before you start
- 26Stochastic processFinite-dimensional distributionsMartingaleMarkov chain central limit theorem and asymptotic variance
- 04Covariance matrixPearson correlation
- 05Hypothesis testp-valueNormal sampling theory: chi-squared, Student t and F distributions
- 00Datetime indexes, time zones and frequenciesResamplingLook-ahead bias prevention
Learning from a single history
In an experiment you can repeat a measurement under the same conditions. The history of a stock index is observed only once. Averaging its values as if they were independent replications can give fictitious precision: neighboring observations share information and their distributions can change.
A stochastic process jointly describes possible values at different times. Its covariance matrix summarizes linear dependence, while a martingale expresses a conditional-expectation constraint.
Compare a trend, a random walk and a process with clustered volatility. Autocorrelation of levels and of their squares answer different questions. A band calculated for independent noise is not automatically valid for dependent data.
What stationary means
A process is strictly stationary if, for every finite set of times and integer shift ,
It does not require finite moments. Weak stationarity requires a finite second moment, constant mean and covariance depending only on separation: . The former implies the latter when the second moment exists, but the converse is false without further assumptions, such as joint Gaussianity: then mean and covariance determine every finite-dimensional distribution.
Two counterexamples separate the concepts. An iid Cauchy sequence is strictly stationary but has no finite variance. For the other direction, take independent variables with mean zero and variance one, normal at even times and Rademacher at odd times. Their covariance is , but the marginal distribution changes with parity. The process is weakly stationary but not strictly stationary.
A deterministic trend with changes the mean; a random walk started at zero has increasing variance if increments have positive variance. Nonconstant deterministic seasonality changes the mean by phase; subtracting a known component can leave a stationary series. One path alone never proves those distributions are invariant.
Autocovariance has constraints
The autocovariance function of a weakly stationary process is . It is even, , and by Cauchy-Schwarz. When , the autocorrelation is .
The stronger condition is nonnegative definiteness: for any times and real coefficients ,
Therefore every Toeplitz matrix built with must be positive semidefinite. Conversely, an even nonnegative-definite function on the integers is the autocovariance of some second-order stationary process; a Gaussian one can be constructed. This characterization does not say every bounded even function works. The exercise tests a candidate satisfying the individual bound but failing for a combination of five times.
White does not mean independent
Weak white noise has constant mean, constant finite variance and zero covariance at nonzero lags. A martingale difference satisfies and, with finite second moment, is uncorrelated with the past; to be weak white noise it must also have constant unconditional variance. An iid sequence with mean zero and finite variance satisfies both properties.
The converse implications fail. If are iid standard normal, is a martingale difference and white noise, but and share and are dependent. In stationary GARCH, returns can be uncorrelated while their squares exhibit dependence: absence of linear autocorrelation does not eliminate volatility clustering. To claim stationary GARCH, verify parameter conditions rather than merely plotting a path.
Estimate the ACF and its bands
The sample ACF and Bartlett bands start from a specific definition. Given , with , use for
The divisor introduces bias but preserves nonnegative definiteness: extend the centered sample with zeros outside its interval and write each quadratic combination as a sum of squares. Replacing it with does not guarantee that property; nor does it make unbiased.
For iid noise with finite positive variance and a fixed lag, the approximate reference is . These are pointwise bands, not a simultaneous guarantee for all lags. Now consider a stationary invertible MA() with centered iid innovations, positive variance and finite fourth moment. With and fixed, Bartlett’s formula gives approximately
Replace unknown autocorrelations with estimates. This formula applies under the MA model and its assumptions; it is not a generic correction for every series, nor necessarily for fitted residuals or heteroskedastic squares. The statsmodels ACF documentation distinguishes residual bands from Bartlett bands calculated on original data.
Partial autocorrelation at is the correlation between linear-projection errors of and on intermediate lags. It is calculated by solving Yule-Walker equations; it is not the simple correlation at that lag. Ideal patterns help select models, but sampling noise and later choices complicate interpretation.
Portmanteau tests and diagnostics
The Box-Pierce and Ljung-Box tests combine several lags:
The original papers by Box and Pierce and Ljung and Box study joint diagnosis of residual autocorrelations.
For iid noise and fixed , they are compared asymptotically with . For residuals of a well-specified ARMA model, the usual adjustment reduces degrees of freedom to , provided they are positive and asymptotic assumptions hold. Do not arbitrarily subtract a parameter from a series to which no model was fitted. A high value does not prove independence; rejection does not identify the responsible lag. With changing conditional volatility, iid calibration may be incorrect, so consider robust methods or simulation under the model.
Applying the test to returns and their squares asks about linear dependence and persistence of magnitudes. It can also reveal structural changes: rejection on squares does not by itself identify GARCH.
Averages, ergodicity and effective size
Mean-square ergodicity of a weakly stationary process means converges to in . Since its expectation is , this is equivalent to
The identity counts the pairs separated by . Absolute summability of is sufficient for convergence, not necessary. Stationarity alone is insufficient: if for every and has positive variance, each average is . With absolutely summable covariances, tends to .
For a stationary AR(1) , , with iid innovations of variance , and . Define by equating the actual variance to . At finite size use the previous sum; when is large relative to the dependence scale,
For , cancellation between neighbors can make . This quantity depends on the statistic and model: it is not a literal count of independent data and does not automatically apply to other estimators.
Cross-correlation and spurious relationships
For jointly stationary processes define . Fixing this convention matters: swapping the series reverses the lag sign. High correlation between two independent random walks can arise from their persistent levels; neither prediction nor causality follows from that plot. To study relationships, plot levels and differences, investigate trends and possible equilibrium relationships, and separate fitting from evaluation periods. Selecting lags after seeing results also affects uncertainty.
In the next cell, and both noise sources are independent. The maximum should appear near under the chosen convention: lags by two steps. Knowing the mechanism in this simulation does not mean a peak observed in other data proves causality.
import numpy as np
rng = np.random.default_rng(108)
x_cruz = rng.normal(size=1002)
y_cruz = x_cruz[:-2] + 0.4*rng.normal(size=1000)
x_cruz = x_cruz[2:]
retardos = np.arange(-5, 6)
def correlacion_cruzada(x, y, h):
if h >= 0:
return np.corrcoef(x[:len(x)-h], y[h:])[0, 1]
return np.corrcoef(x[-h:], y[:len(y)+h])[0, 1]
valores = np.array([correlacion_cruzada(x_cruz, y_cruz, h) for h in retardos])
print("retardos:", retardos)
print("correlaciones:", np.round(valores, 3))
print("retardo del máximo:", retardos[np.argmax(valores)])Lab: from summation to FFT
The cell calculates autocovariance with zero padding to avoid circular convolution, PACF by Yule-Walker, and both tests. It checks degenerate cases instead of dividing by zero. Run cells in order to retain the functions.
import numpy as np
from scipy.stats import chi2
def acov(x, m, fft=True):
x = np.asarray(x, dtype=float)
n = len(x)
if not 0 <= m < n or not np.isfinite(x).all():
raise ValueError("retardos o datos inválidos")
z = x - x.mean()
if fft:
size = 1 << (2*n-1).bit_length()
spec = np.fft.rfft(z, n=size)
return np.fft.irfft(spec * spec.conj(), n=size)[:m+1] / n
return np.array([z[:n-h] @ z[h:] / n for h in range(m+1)])
def acf_propia(x, m, fft=True):
g = acov(x, m, fft)
if g[0] <= 0:
raise ValueError("la serie debe tener varianza positiva")
return g / g[0]
def pacf_yw(x, m):
r = acf_propia(x, m)
out = [1.]
for h in range(1, m+1):
toeplitz = r[np.abs(np.arange(h)[:, None] - np.arange(h))]
out.append(np.linalg.solve(toeplitz, r[1:h+1])[-1])
return np.array(out)
def ljung_box(x, m, fitted_params=0):
n = len(x)
if not isinstance(m, (int, np.integer)) or not isinstance(fitted_params, (int, np.integer)) or not 0 <= fitted_params < m < n:
raise ValueError("se requiere 0 <= fitted_params < m < n")
r = acf_propia(x, m)[1:]
h = np.arange(1, m+1)
q = n*(n+2)*np.sum(r*r/(n-h))
return q, chi2.sf(q, m-fitted_params)
def box_pierce(x, m, fitted_params=0):
if not isinstance(m, (int, np.integer)) or not isinstance(fitted_params, (int, np.integer)) or not 0 <= fitted_params < m < len(x):
raise ValueError("grados de libertad inválidos")
r = acf_propia(x, m)[1:]
q = len(x) * np.sum(r*r)
return q, chi2.sf(q, m-fitted_params)
rng = np.random.default_rng(26)
x = rng.normal(size=800)
print("diferencia FFT y suma:", np.max(np.abs(acov(x, 20)-acov(x, 20, False))))
print("ACF retardos 1 a 3:", np.round(acf_propia(x, 3)[1:], 4))
print("PACF retardos 1 a 3:", np.round(pacf_yw(x, 3)[1:], 4))
print("Ljung-Box, 10 retardos:", np.round(ljung_box(x, 10), 4))
print("Box-Pierce, 10 retardos:", np.round(box_pierce(x, 10), 4))The FFT calculates all lags with one convolution; it does not change the definition. Solving PACF matrices requires invertible autocorrelation matrices. Comparison with a library also checks conventions and degrees of freedom.
The following short sample shows why changing the divisor can break positive definiteness. Compare the smallest eigenvalue of both matrices; it does not interpret the negative value as a possible variance.
ejemplo = np.array([1., 2., 3., 4., 5.])
z = ejemplo-ejemplo.mean()
n_ejemplo = len(z)
g_n = acov(ejemplo, n_ejemplo-1, False)
g_ajustada = np.array([z[:n_ejemplo-h] @ z[h:] / (n_ejemplo-h)
for h in range(n_ejemplo)])
indice = np.abs(np.arange(n_ejemplo)[:, None]-np.arange(n_ejemplo))
print("menor autovalor, divisor n:", np.linalg.eigvalsh(g_n[indice])[0])
print("menor autovalor, divisor n-h:", np.linalg.eigvalsh(g_ajustada[indice])[0])from statsmodels.tsa.stattools import acf, pacf
from statsmodels.stats.diagnostic import acorr_ljungbox
ref_acf = acf(x, nlags=20, adjusted=False, fft=True)
ref_pacf = pacf(x, nlags=10, method="ywm")
ref_q = acorr_ljungbox(x, lags=[10], model_df=0, boxpierce=True)
print("error ACF:", np.max(np.abs(acf_propia(x, 20)-ref_acf)))
print("error PACF:", np.max(np.abs(pacf_yw(x, 10)-ref_pacf)))
print("propio / statsmodels Q:", ljung_box(x, 10)[0], ref_q["lb_stat"].iloc[0])
print("propio / statsmodels p:", ljung_box(x, 10)[1], ref_q["lb_pvalue"].iloc[0])
print("Box-Pierce propio / statsmodels:", box_pierce(x, 10)[0], ref_q["bp_stat"].iloc[0])The next experiment generates an MA(1) with . In that model . The Bartlett band for lags greater than one is wider than the iid band; both numbers are calculated from the model and observed series.
rng = np.random.default_rng(19)
e = rng.normal(size=1201)
ma = e[1:] + 0.8*e[:-1]
rho1 = 0.8/(1+0.8**2)
iid = 1.96/np.sqrt(len(ma))
bartlett = iid*np.sqrt(1+2*rho1**2)
estimada = iid*np.sqrt(1+2*acf_propia(ma, 1)[1]**2)
print("rho(1) teórica y estimada:", rho1, acf_propia(ma, 1)[1])
print("bandas iid, Bartlett teórica y estimada:", iid, bartlett, estimada)A real index and its squares
The Vega Datasets file contains S&P 500 closing prices. To run this cell offline, a fixed selection from January 2, 2018 through December 31, 2019 is included, without turning non-trading days into artificial observations. These are index prices, not dividend-inclusive total returns. Calculate log differences between consecutive closes and retain trading dates in an applied analysis.
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 = np.diff(np.log(precios))
print("número de rendimientos:", len(rend))
print("ACF niveles y cuadrados, retardos 1 a 3:",
np.round(acf_propia(rend, 3)[1:], 4),
np.round(acf_propia(rend**2, 3)[1:], 4))
print("Ljung-Box niveles y cuadrados, m=10:",
ljung_box(rend, 10),
ljung_box(rend**2, 10))
for serie in (rend, rend**2):
ref = acorr_ljungbox(serie, lags=[10])
print("discrepancia con statsmodels:", abs(ljung_box(serie, 10)[0] - ref["lb_stat"].iloc[0]))In this sample of 502 returns, the cell obtains and for levels, versus for squares. The result applies only to that period and ten lags chosen in advance. The squared-return test can be affected by tails and regime changes; it does not establish that returns are independent or that a particular GARCH model is correct.
Does fitting affect calibration?
In this experiment repeat iid samples and, separately, AR(1) samples fitted by least squares with an intercept. Calculate residuals using the same sample and compare 5% rejection with and without subtracting the autoregressive parameter. The observed proportion fluctuates between experiments; it does not prove exact equality with the nominal level. We do not subtract a parameter for the iid sample because no AR model is fitted there.
rng = np.random.default_rng(91)
reps, n, m = 300, 400, 10
innov = rng.normal(size=(reps, n+1))
series = np.empty_like(innov)
series[:, 0] = innov[:, 0]/np.sqrt(1-0.6**2)
for t in range(1, n+1):
series[:, t] = 0.6*series[:, t-1]+innov[:, t]
prev, actual = series[:, :-1], series[:, 1:]
prev_c = prev-prev.mean(axis=1, keepdims=True)
actual_c = actual-actual.mean(axis=1, keepdims=True)
phi_hat = np.sum(prev_c*actual_c, axis=1)/np.sum(prev_c**2, axis=1)
residuos = actual_c-phi_hat[:, None]*prev_c
iid = rng.normal(size=(reps, n))
rechazo_iid = np.mean([ljung_box(z, m)[1] < 0.05 for z in iid])
sin = np.mean([ljung_box(z, m, 0)[1] < 0.05 for z in residuos])
con = np.mean([ljung_box(z, m, 1)[1] < 0.05 for z in residuos])
print("fracción de rechazos iid, residuos sin corrección y con corrección:",
rechazo_iid, sin, con)
print("réplicas:", reps, "error Monte Carlo aproximado si p=0.05:",
np.sqrt(0.05*0.95/reps))The usual degrees-of-freedom adjustment approximates the residual law under a correctly specified model. If you estimate other parameters, choose lags using the same data, or the model is incorrect, calibration must be studied again.
The last cell generates independent pairs of random walks. Compare the fraction with absolute correlation above 0.8 in levels with the same measure on increments. This is neither a causal test nor a universal probability: it depends on the chosen length, distribution and threshold.
rng = np.random.default_rng(17)
dx = rng.normal(size=(300, 200))
dy = rng.normal(size=(300, 200))
def correlaciones_filas(a, b):
a = a-a.mean(axis=1, keepdims=True)
b = b-b.mean(axis=1, keepdims=True)
return np.sum(a*b, axis=1)/np.sqrt(np.sum(a*a, axis=1)*np.sum(b*b, axis=1))
niveles = correlaciones_filas(np.cumsum(dx, axis=1), np.cumsum(dy, axis=1))
incrementos = correlaciones_filas(dx, dy)
print("fracción |r| > 0.8 en niveles e incrementos:",
np.mean(np.abs(niveles)>0.8), np.mean(np.abs(incrementos)>0.8))Exercises
Step 1 of 3. What does the double sum with coefficients aᵢ represent?
Step 1 of 2. If Zₜ are independent standard normals, what alternating transformation preserves mean zero and variance one while changing the marginals?
import numpy as np
from scipy.stats import chi2
def ljung_box(x, m, fitted_params=0):
pass
def tamano(generar, reps, m, fitted_params=0):
passStationarity restricts distributions or moments; ergodicity connects a long path with an expectation. The ACF summarizes linear dependence, its matrices must be positive semidefinite, and uncertainty in a mean depends on the entire covariance sequence.