Nonstationarity: unit roots and ARIMA
Many economic and product series wander rather than return to a mean. Distinguish deterministic from stochastic trends, define integration order, study why standard asymptotics fail with a unit root and Dickey-Fuller limits involve Brownian integrals, and compare ADF and KPSS as complementary tools. Differencing turns an I(d) process into ARMA and defines ARIMA.
After this lesson you can
- Distinguish theoretically and by simulation the shock response of a trend-stationary series and a unit-root series.
- Derive the Dickey-Fuller regression and simulate its nonstandard distribution to obtain critical values.
- Apply ADF and KPSS with appropriate deterministic specifications and combine results in a decision protocol.
- Choose the differencing order while avoiding overdifferencing and recognize its ACF signature.
- Fit and forecast an ARIMA model, explaining why prediction intervals grow without bound.
Before you start
- 26ARMA modelCausality and invertibilitySimple random walkAutocorrelation functionWeak (second-order) stationarityMoving average model
- 05Hypothesis testPower and power functionType I and type II errorsGaussian linear modelSampling distribution of OLS coefficients
- 04Convergence in distributionSlutsky's lemma and continuous mapping theorem
When a shock does not disappear
A traffic drop can be a temporary episode around a trend or leave a lasting level shift. One short path can appear compatible with both stories, especially when reversion is very slow. This distinction changes what forecasting means and how uncertainty grows.
Apply the same shock to two paths with identical innovations: it fades in a stable AR component but persists in a random walk. As the autoregressive coefficient approaches one, a finite sample needs increasingly more time to distinguish them.
Deterministic trend or unit root
A series stationary around a trend can be written , where is stationary. If and , a shock of size at has effect at . Removing the deterministic trend leaves ; differencing is not the only way to remove growth.
A walk with drift has a unit root: autoregressive polynomial vanishes at . Conditional on a fixed start and iid innovations of variance , . A shock shifts all later levels by . Subtracting mean trend does not remove increasing variance.
A process is integrated of order , I(), when it requires differences to obtain an I(0) process, under an I(0) definition excluding unit roots and cancellations. Write . A walk with drift satisfies and is I(1); a deterministic trend plus stationary noise is not, for that reason alone, a unit-root walk.
Overdifferencing also has consequences. If is white noise, is MA(1) with under the previous lesson’s convention: its root is on the invertibility boundary and lag-one autocorrelation is . A negative bar alone does not prove overdifferencing; other models can produce it.
Dickey-Fuller: a t statistic with another distribution
Consider without a constant and with . Subtracting gives
The Dickey-Fuller test tests against the one-sided alternative . For a pure AR(1) to admit a causal stationary solution, is also required, that is ; a process started at zero needs a transient before approximating that law. Although its statistic is a coefficient divided by its regression standard error, under the regressor is a random walk. The usual Student t distribution is invalid.
With centered iid innovations of positive finite variance and invariance conditions, the rescaled process converges to standard Brownian motion . Without constant or trend,
The stochastic integral satisfies . The numerator is not normal independent of the denominator: using normal or t tables changes test size. Adding a constant or trend changes the projection and null distribution. Critical values must match the specification and, in small samples, sample size.
The augmented ADF test permits short-run autocorrelation through lagged differences:
Include only deterministic terms compatible with the question and model. Too few lags can leave residual correlation; too many consume degrees of freedom. Selecting by AIC compares models on the same sample, then refits the chosen one. ADF can have low power against alternatives very close to one. The adfuller documentation specifies deterministic cases and critical values used.
KPSS asks from the other side
The KPSS test takes stationarity around a level or trend as its null, depending on the regression. After removing that deterministic part, let be residuals and . The statistic is
The second expression is a Bartlett estimate of long-run variance, with . Bandwidth affects the result. An asymptotic approximation requires conditions on dependence and growth of ; a finite rule is not a universal adjustment. Rejection occurs at large statistic values. The statsmodels implementation distinguishes level and trend and documents lag selection.
With compatible deterministic terms, ADF and KPSS answer complementary questions:
| ADF rejects a unit root | KPSS rejects stationarity | Provisional interpretation |
|---|---|---|
| Yes | No | Evidence compatible with stationarity under the chosen specifications. |
| No | Yes | Evidence compatible with a unit root, among other explanations. |
| Yes | Yes | Conflict: investigate breaks, dependence, variance and specification. |
| No | No | Little information for a decision; neither non-rejection proves its null. |
The two tests are not independent, and combining them does not remove their errors. Changing specifications after seeing results or trying many lags affects inference. Near unity the ambiguous region can be wide.
A level or trend break can resemble a unit root in a finite sample and reduce the power of a misspecified ADF. Perron explicitly studies unit-root tests against trends with a break. Investigate dates and mechanisms before attributing persistence to the process; tests with selected breaks need their own critical values. Other processes can exhibit fractional integration. For example, a Gaussian ARFIMA(0,,0) with is stationary and its autocovariance decays as a constant times , so it is not summable. Other values of behave differently. This hypothesis needs specific models and diagnostics; a slowly decaying ACF alone does not establish it. Example ARFIMA study.
ARIMA and forecasting
An ARIMA() satisfies
with a causal invertible ARMA part after canceling common factors. For , a constant in the differenced equation can represent drift; its value depends on AR parameterization. A constant in levels should not be confused with drift after differencing.
For a random walk, the best level forecast steps ahead is the last level plus and error variance is . For ARIMA(0,1,1), with , known parameters and last innovation, or infinite history and an invertible representation,
If , the long-run term does not cancel and this variance grows without bound. In a genuinely integrated causal invertible ARIMA, integration increases level uncertainty; exact unit-root cancellation changes the model’s effective order. Intervals also depend on innovation distribution and parameter uncertainty. A price level appearing I(1) in one period does not make that model a universal market law.
Lab: regressions and critical values
Implement ADF with AIC selection on the same window, KPSS with explicit bandwidth, and simulated critical values. Seeds and Monte Carlo sizes make the result reproducible. More replications reduce Monte Carlo error but do not eliminate specification errors.
import numpy as np
from statsmodels.tsa.stattools import adfuller, kpss
def regresion_adf(x, lag, inicio, tendencia="c"):
x = np.asarray(x, dtype=float)
dx = np.diff(x)
t = np.arange(inicio, len(dx))
cols = [x[t]]
cols += [dx[t-j] for j in range(1, lag+1)]
if tendencia in ("c", "ct"):
cols.append(np.ones(len(t)))
if tendencia == "ct":
cols.append(t+1.)
X = np.column_stack(cols)
y = dx[t]
coef, _, rango, _ = np.linalg.lstsq(X, y, rcond=None)
if rango < X.shape[1] or len(y) <= X.shape[1]:
raise ValueError("regresión singular o sin grados de libertad")
resid = y-X@coef
sse = resid@resid
cov = np.linalg.inv(X.T@X)*(sse/(len(y)-X.shape[1]))
stat = coef[0]/np.sqrt(cov[0,0])
aic = len(y)*np.log(sse/len(y))+2*X.shape[1]
return stat, aic
def adf_aic(x, maxlag=4, tendencia="c"):
if tendencia not in ("n", "c", "ct") or maxlag < 0:
raise ValueError("especificación inválida")
candidatos = [regresion_adf(x, lag, maxlag, tendencia)[1]
for lag in range(maxlag+1)]
elegido = int(np.argmin(candidatos))
stat, _ = regresion_adf(x, elegido, elegido, tendencia)
return stat, elegido
rng = np.random.default_rng(2612)
paseo = np.r_[0., np.cumsum(rng.normal(size=299))]
propio = adf_aic(paseo, 4, "c")
ref = adfuller(paseo, maxlag=4, regression="c", autolag="AIC")
print("ADF propio y statsmodels, estadístico y retardos:",
propio, (ref[0], ref[2]))
print("valor p y crítico 5 % de statsmodels:", ref[1], ref[4]["5%"])
propio_ct = adf_aic(paseo, 4, "ct")
ref_ct = adfuller(paseo, maxlag=4, regression="ct", autolag="AIC")
print("ADF con tendencia, propio y statsmodels:", propio_ct, (ref_ct[0], ref_ct[2]))The custom selection uses all candidates on the same observations; the selected regression then recovers observations available for that order. Its AIC omits a common constant that does not affect the choice.
def kpss_propio(x, lag, tendencia="c"):
x = np.asarray(x, dtype=float)
n = len(x)
if not 0 <= lag < n or tendencia not in ("c", "ct"):
raise ValueError("retardo o tendencia inválidos")
resid = x-x.mean()
if tendencia == "ct":
t = np.arange(n, dtype=float)-(n-1)/2
resid -= (resid@t)/(t@t)*t
largo = resid@resid/n
for j in range(1, lag+1):
largo += 2*(1-j/(lag+1))*(resid[j:]@resid[:-j])/n
if largo <= 0:
raise ValueError("varianza de largo plazo no positiva")
return np.sum(np.cumsum(resid)**2)/(n*n*largo)
lag = 4
ref_kpss = kpss(paseo, regression="c", nlags=lag)
print("KPSS propio y statsmodels:", kpss_propio(paseo, lag), ref_kpss[0])
print("p de tabla y crítico 5 %:", ref_kpss[1], ref_kpss[3]["5%"])
ref_ct = kpss(paseo, regression="ct", nlags=lag)
print("KPSS con tendencia, propio y statsmodels:", kpss_propio(paseo, lag, "ct"), ref_ct[0])The library’s KPSS value is interpolated over a tabulated range; if the statistic falls outside it, a bound is reported instead of an exact probability.
The next cell generates new samples under the unit root and calculates the statistic’s distribution without lags. In each regression it projects out deterministic terms before estimating . Quantiles for the three specifications use the same innovations for easier comparison; differences from tables reflect Monte Carlo error and finite-sample differences.
from statsmodels.tsa.adfvalues import mackinnoncrit
from scipy.stats import norm
def df_en_lote(innovaciones, tendencia="c"):
e = np.asarray(innovaciones, dtype=float)
if e.ndim != 2 or tendencia not in ("n", "c", "ct"):
raise ValueError("innovaciones o tendencia inválidas")
reps, n = e.shape
if n <= 4:
raise ValueError("muestra demasiado corta")
prev = np.column_stack((np.zeros(reps), np.cumsum(e, axis=1)[:,:-1]))
y = e.copy()
d = 0
if tendencia in ("c", "ct"):
prev = prev-prev.mean(axis=1, keepdims=True)
y = y-y.mean(axis=1, keepdims=True)
d = 1
if tendencia == "ct":
t = np.arange(n, dtype=float)-(n-1)/2
prev = prev - (prev@t/(t@t))[:,None]*t
y = y - (y@t/(t@t))[:,None]*t
d = 2
denom = np.sum(prev*prev, axis=1)
gamma = np.sum(prev*y, axis=1)/denom
resid = y-gamma[:,None]*prev
s2 = np.sum(resid*resid, axis=1)/(n-d-1)
return gamma/np.sqrt(s2/denom)
rng = np.random.default_rng(19)
innov = rng.normal(size=(3000, 250))
for tendencia in ("n", "c", "ct"):
ts = df_en_lote(innov, tendencia)
critico = np.quantile(ts, .05)
tabla = mackinnoncrit(N=1, regression=tendencia, nobs=250)[1]
print(tendencia, "cuantil 5% simulado y tabla:", critico, tabla,
"rechazo con normal:", np.mean(ts < norm.ppf(.05)))
trayectoria = np.r_[0., np.cumsum(innov[0])]
df_ref = adfuller(trayectoria, maxlag=0, regression="ct", autolag=None)
print("DF de una trayectoria, propio y statsmodels:",
df_en_lote(innov[:1], "ct")[0], df_ref[0])Now study both tests’ sensitivity to persistence. Replications are independent, parameters and procedure are fixed before inspecting rates, and the Monte Carlo interval is of order for each rate.
from statsmodels.tsa.adfvalues import mackinnoncrit
rng = np.random.default_rng(88)
reps, n, burn = 300, 200, 300
crit_adf = mackinnoncrit(N=1, regression="c", nobs=n-1)[1]
crit_kpss = .463
for phi in (.8, .95, .99, 1.):
z = np.zeros(reps)
datos = np.empty((reps, n))
for t in range(n+burn):
z = phi*z+rng.normal(size=reps)
if t >= burn:
datos[:, t-burn] = z
# ADF sin retardos: un caso concreto, no el selector AIC anterior.
niveles = datos[:,:-1]
diferencias = np.diff(datos, axis=1)
niveles = niveles-niveles.mean(axis=1, keepdims=True)
diferencias = diferencias-diferencias.mean(axis=1, keepdims=True)
xx = np.sum(niveles*niveles, axis=1)
coef = np.sum(niveles*diferencias, axis=1)/xx
residuos = diferencias-coef[:,None]*niveles
s2 = np.sum(residuos*residuos, axis=1)/(n-1-2)
stat_adf = coef/np.sqrt(s2/xx)
# KPSS por filas con el mismo ancho de Bartlett que la celda anterior.
resid = datos-datos.mean(axis=1, keepdims=True)
largo = np.sum(resid*resid, axis=1)/n
for j in range(1,5):
largo += 2*(1-j/5)*np.sum(resid[:,j:]*resid[:,:-j], axis=1)/n
stat_kpss = np.sum(np.cumsum(resid, axis=1)**2, axis=1)/(n*n*largo)
print("phi, rechazo ADF, rechazo KPSS:",
phi, np.mean(stat_adf < crit_adf), np.mean(stat_kpss > crit_kpss))For the generated process retains the level accumulated during burn-in; tests with a constant are invariant to that initial shift. For , burn-in approximates the stationary law. In this run KPSS rejects 24% of 300 replications with and about 75.7% with , although both processes are stationary: with and this sample size its calibration is poor. These rates estimate false rejections under the KPSS null, not power; do not extrapolate the percentages to other rules or sizes.
A real series and a forecast
Reuse the 503 S&P 500 closes from the autocorrelation lesson, from January 2, 2018 through December 31, 2019, from Vega Datasets. These are index levels, not total returns. Each difference corresponds to consecutive closes, not every calendar day. Tests are exploratory and results depend on that period and their assumptions.
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)
logprecio = np.log(precios)
rendimiento = np.diff(logprecio)
for nombre, datos in (("log-precio", logprecio), ("rendimiento", rendimiento)):
adf = adfuller(datos, maxlag=4, regression="c", autolag="AIC")
kp = kpss(datos, regression="c", nlags=4)
print(nombre, "ADF estadístico, p, retardos:", adf[0], adf[1], adf[2])
print(nombre, "KPSS estadístico, p acotado por tabla:", kp[0], kp[1])Fit ARIMA to the first 400 closes and leave the rest out of fitting. Compare level forecasts with the last observed level: this example uses a prespecified horizon and one split without claiming general superiority. The library’s intervals condition on the fitted model and estimated parameters.
from statsmodels.tsa.arima.model import ARIMA
entrenamiento, prueba = logprecio[:400], logprecio[400:]
ajuste = ARIMA(entrenamiento, order=(0,1,1), trend="t").fit()
forecast = ajuste.get_forecast(steps=len(prueba))
pred = np.asarray(forecast.predicted_mean)
errores = np.asarray(forecast.se_mean)
ingenuo = np.repeat(entrenamiento[-1], len(prueba))
print("parámetros ARIMA:", ajuste.params)
print("RMSE ARIMA e ingenuo:", np.sqrt(np.mean((prueba-pred)**2)),
np.sqrt(np.mean((prueba-ingenuo)**2)))
print("error estándar predictivo primer y último horizonte:", errores[0], errores[-1])Exercises
Step 1 of 3. What is the variance of Xₜ?
import numpy as np
def df_critical_values(n, trend, reps, rng):
passStep 1 of 3. What is ΔXₜ?
A unit root preserves shocks and changes estimator distributions. Differencing can produce a stationary series, but unnecessary differencing introduces its own dependence. Diagnosis should combine models, tests and temporal evaluation.