Module contents
Lesson 12 of 31Core 105 min

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

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.

InteractiveThe fate of a shock

All four curves use the same independent normal innovations with standard deviation 0.5, the same drift 0.04 per step and initial state zero. The shocked version adds δ to the innovation at t=35; the unshocked version retains the rest of the noise. Both charts share a vertical scale.

Deterministic trend and AR(1) residual

Time t

Random walk with drift

Time t
  • Without shock
  • With shock
  • Shock time

The following chart subtracts the unshocked path from the shocked path in each model. This difference exactly removes shared noise and reveals the isolated response.

Steps h since shock
  • AR response: δφʰ
  • Walk response: δ

If uₜ=φuₜ₋₁+εₜ, the effect of impulse δ after h steps is δφʰ; for |φ|<1 it tends to zero, and if φ<0 it changes sign. In the walk the difference remains δ. At φ=1 both recursions coincide for the same initial state, drift and innovations: the effect does not disappear.

The AR residual has a stationary causal solution only for |φ|<1; these samples start at zero, so their initial distribution is transient. Adding a deterministic trend makes the series nonstationary in levels. At φ=1 a unit root appears and the name “stationary residual” no longer applies.

0.80
4.0
10
AR shock effect, δφʰ0.429
Walk effect, δ4.000
AR residualStable in regime
Seed2612
Compare paths with and without the same shock using shared innovations. The theoretical effect is calculated for the indicated models.

Deterministic trend or unit root

A series stationary around a trend can be written Xt=a+bt+UtX_t=a+bt+U_t, where UtU_t is stationary. If Ut=ϕUt−1+εtU_t=\phi U_{t-1}+\varepsilon_t and ∣ϕ∣<1|\phi|<1, a shock of size δ\delta at tt has effect δϕh\delta\phi^h at t+ht+h. Removing the deterministic trend leaves UtU_t; differencing is not the only way to remove growth.

A walk with drift Xt=Xt−1+c+εtX_t=X_{t-1}+c+\varepsilon_t has a unit root: autoregressive polynomial 1−z1-z vanishes at z=1z=1. Conditional on a fixed start and iid innovations of variance σ2\sigma^2, Var⁡(Xt)=tσ2\operatorname{Var}(X_t)=t\sigma^2. A shock shifts all later levels by δ\delta. Subtracting mean trend ctct does not remove increasing variance.

A process is integrated of order dd, I(dd), when it requires dd differences to obtain an I(0) process, under an I(0) definition excluding unit roots and cancellations. Write ΔXt=(1−B)Xt\Delta X_t=(1-B)X_t. A walk with drift satisfies ΔXt=c+εt\Delta X_t=c+\varepsilon_t 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 UtU_t is white noise, ΔUt=εt−εt−1\Delta U_t=\varepsilon_t-\varepsilon_{t-1} is MA(1) with θ=−1\theta=-1 under the previous lesson’s convention: its root is on the invertibility boundary and lag-one autocorrelation is −1/2-1/2. A negative bar alone does not prove overdifferencing; other models can produce it.

Dickey-Fuller: a t statistic with another distribution

Consider Xt=ρXt−1+εtX_t=\rho X_{t-1}+\varepsilon_t without a constant and with X0=0X_0=0. Subtracting Xt−1X_{t-1} gives

ΔXt=γXt−1+εt,γ=ρ−1.\Delta X_t=\gamma X_{t-1}+\varepsilon_t,\qquad \gamma=\rho-1.

The Dickey-Fuller test tests H0:γ=0H_0:\gamma=0 against the one-sided alternative γ<0\gamma<0. For a pure AR(1) to admit a causal stationary solution, ∣ρ∣<1|\rho|<1 is also required, that is −2<γ<0-2<\gamma<0; 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 H0H_0 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 WW. Without constant or trend,

nγ^ ⇒ ∫01W(r) dW(r)∫01W(r)2 dr,tγ ⇒ ∫01W(r) dW(r)∫01W(r)2 dr.n\hat\gamma\ \Rightarrow\ \frac{\int_0^1 W(r)\,dW(r)}{\int_0^1 W(r)^2\,dr}, \qquad t_\gamma\ \Rightarrow\ \frac{\int_0^1 W(r)\,dW(r)} {\sqrt{\int_0^1 W(r)^2\,dr}}.

The stochastic integral satisfies ∫01W dW=(W(1)2−1)/2\int_0^1 W\,dW=(W(1)^2-1)/2. 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.

InteractiveA nonstandard null distribution

Statistic distribution over independent evaluation walks, compared with standard normal density.

  • Dickey–Fuller statistic
  • Standard normal

For each walk fit ΔXₜ = γXₜ₋₁ + εₜ, adding a constant and linear trend as selected. The statistic is estimated γ divided by its OLS standard error, with degrees of freedom n minus number of coefficients. Rejection is in the left tail.

Each set contains up to 3000 walks: X₀ = 0 and ΔXₜ are independent standard normal, without drift. The first set calibrates the 5th percentile; the second, with another pseudorandom stream, produces the histogram and both rates. The normal uses its 5th percentile, −1.645. Degenerate regressions are excluded and the number valid is shown.

Quantiles and rates have Monte Carlo uncertainty and correspond to this n and this particular null model. The calibrated value is not a universal table: it changes with specification and assumptions. Difference lags are not added here as in ADF.

Dickey–Fuller regression
100
1
Evaluation 5% quantile−2.882
Independent calibration 5% threshold−2.865
Rejections with normal threshold46.2 %
Rejections with calibrated threshold5.2 %
Valid calibration / evaluation walks3000 / 3000
Simulate independent walks and compare the Dickey-Fuller statistic with the normal. Constants and trends are estimated within each regression; quantiles use finite Monte Carlo.

The augmented ADF test permits short-run autocorrelation through lagged differences:

ΔXt=a+bt+γXt−1+∑j=1kδjΔXt−j+ut.\Delta X_t=a+bt+\gamma X_{t-1} +\sum_{j=1}^{k}\delta_j\Delta X_{t-j}+u_t.

Include only deterministic terms compatible with the question and model. Too few lags can leave residual correlation; too many consume degrees of freedom. Selecting kk 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 ete_t be residuals and St=∑i=1teiS_t=\sum_{i=1}^te_i. The statistic is

KPSS=n−2∑t=1nSt2ω^2,ω^2=γ^0+2∑j=1L(1−jL+1)γ^j.\mathrm{KPSS}=\frac{n^{-2}\sum_{t=1}^n S_t^2}{\hat\omega^2},\qquad \hat\omega^2=\hat\gamma_0+ 2\sum_{j=1}^{L}\left(1-\frac{j}{L+1}\right)\hat\gamma_j.

The second expression is a Bartlett estimate of long-run variance, with γ^j=n−1∑t=j+1netet−j\hat\gamma_j=n^{-1}\sum_{t=j+1}^ne_te_{t-j}. Bandwidth LL affects the result. An asymptotic approximation requires conditions on dependence and growth of LL; 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 rootKPSS rejects stationarityProvisional interpretation
YesNoEvidence compatible with stationarity under the chosen specifications.
NoYesEvidence compatible with a unit root, among other explanations.
YesYesConflict: investigate breaks, dependence, variance and specification.
NoNoLittle 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.

InteractivePower and false rejections

Dickey–Fuller: reject unit root

Number of observations n
φ
50
100
200
400
0.80
0.90
0.95
0.98
1.00

KPSS: reject level stationarity

Number of observations n
φ
50
100
200
400
0.80
0.90
0.95
0.98
1.00

Each cell shows the proportion of 400 rejections in paths Xₜ = φXₜ₋₁ + εₜ, X₀ = 0, with independent normal εₜ of variance 1. At φ = 1 the DF unit-root null is true; with φ < 1 the model has a stationary solution, although these paths start at zero rather than their stationary distribution.

DF uses a constant and zero lags of differences: it is a specific ADF case. For each n the lower threshold is calculated from 1200 walks independent of evaluation, using order 60. KPSS removes a mean, estimates long-run variance with Bartlett and q = ⌊∛n⌋ lags, and rejects above the 5% asymptotic critical value 0.463 from statsmodels. Finite-sample sizes can differ from 5%, especially near unity.

The Wilson interval describes uncertainty of the cell replicates; for DF it is conditional on the simulated threshold and excludes uncertainty in its calibration. Maps show rejection rates, not probabilities that a hypothesis is true or guarantees for other trends, lags, initial conditions or innovations.

Selected cellDF · φ 0.95 · n 100
Rejections / replicates47 / 400
95% Wilson interval9.0 % to 15.3 %
Calibrated DF critical value−2.934
KPSS Bartlett lags4
Seed2612
The map calculates rates in simulated replications for each size and coefficient. ADF and KPSS have different nulls; figures fluctuate with simulation and its options.

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,dd,0) with 0<d<1/20<d<1/2 is stationary and its autocovariance decays as a constant times h2d−1h^{2d-1}, so it is not summable. Other values of dd 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(p,d,qp,d,q) satisfies

ϕ(B)(1−B)dXt=c+θ(B)εt,\phi(B)(1-B)^dX_t=c+\theta(B)\varepsilon_t,

with a causal invertible ARMA part after canceling common factors. For d=1d=1, 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 hh steps ahead is the last level plus hchc and error variance is hσ2h\sigma^2. For ARIMA(0,1,1), with ΔXt=εt+θεt−1\Delta X_t=\varepsilon_t+\theta\varepsilon_{t-1}, known parameters and last innovation, or infinite history and an invertible representation,

Var⁡(XT+h−X^T+h∣T)=σ2[1+(h−1)(1+θ)2].\operatorname{Var}(X_{T+h}-\hat X_{T+h|T}) =\sigma^2\left[1+(h-1)(1+\theta)^2\right].

If ∣θ∣<1|\theta|<1, 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.

[ ]ADF by least squares and AIC selectionBrowser
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.

[ ]KPSS and long-run varianceBrowser
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 pp 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 γ\gamma. Quantiles for the three specifications use the same innovations for easier comparison; differences from tables reflect Monte Carlo error and finite-sample differences.

[ ]Dickey-Fuller distribution by simulationBrowser
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 p(1−p)/R\sqrt{p(1-p)/R} for each rate.

[ ]Persistence and rejection in finite samplesBrowser
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 ϕ=1\phi=1 the generated process retains the level accumulated during burn-in; tests with a constant are invariant to that initial shift. For ∣ϕ∣<1|\phi|<1, burn-in approximates the stationary law. In this run KPSS rejects 24% of 300 replications with ϕ=0.8\phi=0.8 and about 75.7% with ϕ=0.95\phi=0.95, although both processes are stationary: with L=4L=4 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.

[ ]ADF and KPSS on log prices and 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)
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.

[ ]Out-of-sample ARIMA for log pricesBrowser
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

ProofA correlation that changes over time
Prove: Let Xₜ=Σᵢ₌₁ᵗ εᵢ, with X₀=0 and iid innovations of mean zero and variance σ²>0. Calculate Var(Xₜ) and Corr(Xₜ,Xₜ₊ₕ), and study the limit for fixed h as t grows.
0
Separate increments shared by both levels from later increments.

Step 1 of 3. What is the variance of Xₜ?

QuizFour results, four interpretations
In a short sample, ADF does not reject a unit root and KPSS does not reject stationarity around a constant. Which conclusion is most defensible?
NumericUncertainty at five steps
For ΔXₜ=εₜ−0.5 εₜ₋₁, with iid innovations of variance 1 and known state, calculate level forecast-error variance at h=5.
CodeCalibrate Dickey-Fuller
Implement df_critical_values(n, trend, reps, rng): simulate reps iid normal walks with X₀=0 and n increments; for each calculate the t statistic of γ in ΔXₜ=γXₜ₋₁ plus deterministic terms trend=\u0027n\u0027, \u0027c\u0027 or \u0027ct\u0027. Return empirical 1%, 5% and 10% quantiles. Use residual variance with n minus the number of regressors degrees of freedom and reject invalid parameters.
import numpy as np

def df_critical_values(n, trend, reps, rng):
  pass
Shift+Enter to run
ProofThe root created by differencing
Prove: Let Xₜ=a+bt+εₜ, with εₜ positive-variance white noise. Difference Xₜ, identify the resulting MA and explain its invertibility.
0
Do not confuse removing a deterministic trend with proving the original level has a unit root.

Step 1 of 3. What is ΔXₜ?

Key idea

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.