Module contents
Lesson 9 of 31Core 100 min

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

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.

InteractiveFrom a path to dependence

Xₜ = φXₜ₋₁ + √(1−φ²)Zₜ, with a normal start of variance one. Marginal variance is one for |φ| < 1.

One finite path

Time

Sample level ACF

Lag

Sample squared-value ACF

Lag
  • Sample correlations
  • Squares
  • Pointwise IID reference

Each ACF uses its own series mean and the same divisor n at every lag. The ±1.96/√n lines are a pointwise asymptotic reference for an IID series with suitable moments, not a simultaneous band or universal criterion. With dependence or heteroskedasticity, even when levels are uncorrelated their variance may differ and these lines are not a valid unadjusted test. For trends and walks the sample ACF describes the path, not a stationary process ACF.

Absence of visible bars does not prove independence. In GARCH, levels have zero theoretical autocorrelation although their squares depend on the past; a finite sample may deviate from that pattern. Change the seed to observe sampling variation.

Process
0.80
Observations400
Level ACF, lag 10.829
Squared-value ACF, lag 10.636
IID reference band±0.098
Seed2609
Compare the path, its ACF and the ACF of its squares. Data are generated from explicit models with a reproducible seed; the iid-noise band is a reference, not a universal interval.

What stationary means

A process (Xt)t∈Z(X_t)_{t\in\mathbb Z} is strictly stationary if, for every finite set of times and integer shift hh,

(Xt1,…,Xtk)=d(Xt1+h,…,Xtk+h).(X_{t_1},\ldots,X_{t_k})\overset d=(X_{t_1+h},\ldots,X_{t_k+h}).

It does not require finite moments. Weak stationarity requires a finite second moment, constant mean μ\mu and covariance depending only on separation: Cov⁡(Xt,Xt+h)=γ(h)\operatorname{Cov}(X_t,X_{t+h})=\gamma(h). 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 γ(h)=1{h=0}\gamma(h)=\mathbf 1_{\{h=0\}}, but the marginal distribution changes with parity. The process is weakly stationary but not strictly stationary.

A deterministic trend Xt=at+εtX_t=at+\varepsilon_t with a≠0a\ne0 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.

InteractiveA moving window
  • Observed path
  • Window
  • Local mean

The shaded region contains exactly the indicated indices. Drag its top handle or use the slider. The vertical line marks time 120, where chosen changes apply.

Sample ACF inside the window, centered by its own mean. Lag zero, which is 1 when variance exists, is omitted.

One stationary AR(1) path is generated with coefficient 0.55, mean 0 and variance 1. From index 120 the level change is added and multiplied by the square root of the variance factor; changing these controls preserves the same base noise. Sample variance divides by window length and ACF divides centered products by the total sum of centered squares. With zero variance ACF is undefined.

Differences across windows can suggest changes but also arise from sampling fluctuation. Similarity among a few windows does not establish stationarity either: it is a property of the process distribution, not one path.

2.0
3.00
60
0
1
Window, inclusive indices0 to 59
Window mean−0.184
Window variance1.012
Local ACF, lag 10.632
Local ACF, lag 5−0.136
Global path mean0.437
Global path variance2.221
Move the window and introduce a change in level or scale. Local statistics summarize a finite sample and do not prove stationarity.

Autocovariance has constraints

The autocovariance function of a weakly stationary process is γ(h)=Cov⁡(Xt,Xt+h)\gamma(h)=\operatorname{Cov}(X_t,X_{t+h}). It is even, γ(−h)=γ(h)\gamma(-h)=\gamma(h), and ∣γ(h)∣≤γ(0)|\gamma(h)|\le\gamma(0) by Cauchy-Schwarz. When γ(0)>0\gamma(0)>0, the autocorrelation is ρ(h)=γ(h)/γ(0)\rho(h)=\gamma(h)/\gamma(0).

The stronger condition is nonnegative definiteness: for any times t1,…,tkt_1,\ldots,t_k and real coefficients aia_i,

∑i,j=1kaiajγ(ti−tj)=Var⁡(∑i=1kaiXti)≥0.\sum_{i,j=1}^k a_i a_j\gamma(t_i-t_j) =\operatorname{Var}\left(\sum_{i=1}^k a_iX_{t_i}\right)\ge0.

Therefore every Toeplitz matrix built with γ\gamma 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 E[Xt∣Ft−1]=0\mathbb E[X_t\mid\mathcal F_{t-1}]=0 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 εt\varepsilon_t are iid standard normal, Xt=εtεt−1X_t=\varepsilon_t\varepsilon_{t-1} is a martingale difference and white noise, but Xt2X_t^2 and Xt−12X_{t-1}^2 share εt−12\varepsilon_{t-1}^2 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 x1,…,xnx_1,\ldots,x_n, with xˉ=n−1∑txt\bar x=n^{-1}\sum_t x_t, use for 0≤h<n0\le h<n

γ^(h)=1n∑t=1n−h(xt−xˉ)(xt+h−xˉ),ρ^(h)=γ^(h)/γ^(0).\hat\gamma(h)=\frac1n\sum_{t=1}^{n-h}(x_t-\bar x)(x_{t+h}-\bar x), \qquad \hat\rho(h)=\hat\gamma(h)/\hat\gamma(0).

The divisor nn 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 n−hn-h does not guarantee that property; nor does it make ρ^(h)\hat\rho(h) unbiased.

For iid noise with finite positive variance and a fixed lag, the approximate reference is ±1.96/n\pm1.96/\sqrt n. These are pointwise bands, not a simultaneous guarantee for all lags. Now consider a stationary invertible MA(qq) with centered iid innovations, positive variance and finite fourth moment. With qq and h>qh>q fixed, Bartlett’s formula gives approximately

Var⁡(ρ^(h))≃1n(1+2∑j=1qρ(j)2).\operatorname{Var}(\hat\rho(h))\simeq\frac1n \left(1+2\sum_{j=1}^{q}\rho(j)^2\right).

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 hh is the correlation between linear-projection errors of XtX_t and Xt−hX_{t-h} 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:

QBP=n∑h=1mρ^(h)2,QLB=n(n+2)∑h=1mρ^(h)2n−h.Q_{\rm BP}=n\sum_{h=1}^m\hat\rho(h)^2,\qquad Q_{\rm LB}=n(n+2)\sum_{h=1}^m\frac{\hat\rho(h)^2}{n-h}.

The original papers by Box and Pierce and Ljung and Box study joint diagnosis of residual autocorrelations.

For iid noise and fixed mm, they are compared asymptotically with χm2\chi_m^2. For residuals of a well-specified ARMA model, the usual adjustment reduces degrees of freedom to m−p−qm-p-q, 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 pp 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 Xˉn\bar X_n converges to μ\mu in L2L^2. Since its expectation is μ\mu, this is equivalent to

Var⁡(Xˉn)=γ(0)n[1+2∑h=1n−1(1−hn)ρ(h)]⟶0.\operatorname{Var}(\bar X_n)=\frac{\gamma(0)}n \left[1+2\sum_{h=1}^{n-1}\left(1-\frac hn\right)\rho(h)\right]\longrightarrow0.

The identity counts the n−hn-h pairs separated by hh. Absolute summability of γ\gamma is sufficient for convergence, not necessary. Stationarity alone is insufficient: if Xt=ZX_t=Z for every tt and ZZ has positive variance, each average is ZZ. With absolutely summable covariances, nVar⁡(Xˉn)n\operatorname{Var}(\bar X_n) tends to γ(0)+2∑h≥1γ(h)\gamma(0)+2\sum_{h\ge1}\gamma(h).

For a stationary AR(1) Xt=ϕXt−1+εtX_t=\phi X_{t-1}+\varepsilon_t, ∣ϕ∣<1|\phi|<1, with iid innovations of variance σε2\sigma_\varepsilon^2, γ(0)=σε2/(1−ϕ2)\gamma(0)=\sigma_\varepsilon^2/(1-\phi^2) and ρ(h)=ϕh\rho(h)=\phi^h. Define neffn_{\rm eff} by equating the actual variance to γ(0)/neff\gamma(0)/n_{\rm eff}. At finite size use the previous sum; when nn is large relative to the dependence scale,

neff≃n1−ϕ1+ϕ,Var⁡(Xˉn)≃σε2n(1−ϕ)2.n_{\rm eff}\simeq n\frac{1-\phi}{1+\phi},\qquad \operatorname{Var}(\bar X_n)\simeq\frac{\sigma_\varepsilon^2}{n(1-\phi)^2}.

For ϕ<0\phi<0, cancellation between neighbors can make neff>nn_{\rm eff}>n. 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.

InteractiveUncertainty of a mean
Mean of each path; vertical axis is density
  • Means of 600 paths
  • Normal with naive error
  • Normal with exact finite variance

Each replicate starts in the normal stationary distribution with mean 0 and variance 1; innovations have variance 1 − φ². The histogram shows simulated means and their spread varies with seed. Both curves are theoretical normal densities: the naive one assumes independence and the other uses the exact variance of this finite mean.

Exact variance sums autocorrelations φᵏ with weight 1 − k/n. Finite effective size is 1 divided by that variance because marginal variance is 1. The expression n(1 − φ)/(1 + φ) is an asymptotic approximation: it can be inaccurate for small n and |φ| near 1. With negative correlation, effective size can exceed n: the mean fluctuates less than with independent observations.

0.80
100
Spread of simulated means0.2907
Naive standard error0.1000
Exact standard error for n0.2933
Exact effective size for n11.6
Approximate asymptotic effective size11.1
Replicates and seed600 · 2609
Repeat means of stationary AR(1) paths and compare their dispersion with the finite formula and asymptotic approximation.

Cross-correlation and spurious relationships

For jointly stationary processes define γXY(h)=Cov⁡(Xt,Yt+h)\gamma_{XY}(h)=\operatorname{Cov}(X_t,Y_{t+h}). 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, Yt=Xt−2+ηtY_t=X_{t-2}+\eta_t and both noise sources are independent. The maximum should appear near h=2h=2 under the chosen convention: YY lags XX by two steps. Knowing the mechanism in this simulation does not mean a peak observed in other data proves causality.

[ ]Cross-correlation and lag directionBrowser
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.

[ ]ACF, PACF and Ljung-Box from scratchBrowser
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.

[ ]Two divisors, two matricesBrowser
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])
[ ]Compare with statsmodelsBrowser
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 θ=0.8\theta=0.8. In that model ρ(1)=θ/(1+θ2)\rho(1)=\theta/(1+\theta^2). The Bartlett band for lags greater than one is wider than the iid band; both numbers are calculated from the model and observed series.

[ ]Bartlett bands in an MA(1)Browser
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.

[ ]Historical S&P 500 returnsBrowser
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 QLB≈15.79Q_{\rm LB}\approx15.79 and p≈0.106p\approx0.106 for levels, versus QLB≈108.48Q_{\rm LB}\approx108.48 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.

[ ]Empirical size with and without fittingBrowser
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.

[ ]Spurious correlations between independent walksBrowser
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

ProofAn impossible candidate
Prove: Prove that an autocovariance is nonnegative definite and rule out γ(h)=1 for h=0, 0.6 for |h|=1 and 0 otherwise.
0
Test a combination of five observations with coefficients (1, −2, 2, −2, 1).

Step 1 of 3. What does the double sum with coefficients aᵢ represent?

NumericMean of an AR(1)
For a stationary AR(1) with φ=0.8, innovation variance 1 and n=400, calculate the asymptotic approximation to the variance of the mean.
QuizFour models
Which of these processes is weakly stationary at every integer time?
ProofSeparating the notions
Prove: Construct one weakly stationary process that is not strictly stationary and another strictly stationary process that is not weakly stationary.
0
Think first about moments and then marginal distributions.

Step 1 of 2. If Zₜ are independent standard normals, what alternating transformation preserves mean zero and variance one while changing the marginals?

CodeJoint test and empirical size
Implement ljung_box(x, m, fitted_params=0), returning (statistic, p-value). Center the data, use autocovariance with divisor n, and adjust degrees of freedom by fitted_params. Require integers 0 ≤ fitted_params < m < n and positive variance. Also implement tamano(generar, reps, m, fitted_params=0), calling generar() reps times and returning the fraction of p-values below 0.05. Require positive integer reps.
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):
  pass
Shift+Enter to run
Key idea

Stationarity 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.