Algorithm Search⌘K

Algorithmcore

KPSS test

Also called Kwiatkowski-Phillips-Schmidt-Shin test.

Tests the null of stationarity around a level or trend against a unit root, by the partial sums of residuals. It complements the Dickey-Fuller test.

Time
Θ(n (l + 1)) worst · best
Space
Θ(n) extra
Where
l = the truncation lag of the long-run variance; n = the length of the series
Properties
deterministicnot exactofflineiterative
Origin
Denis Kwiatkowski, Peter C. B. Phillips, Peter Schmidt, Yongcheol Shin, 1992

The KPSS test checks whether a time series is stationary around a constant level, or around a straight line, against the alternative that it contains a unit root. It is the reverse of the augmented Dickey-Fuller test, whose null is the unit root. The statistic removes the level (or the line) by least squares, adds up the residuals into a running sum StS_t, and compares the size of that sum with the long-run variance of the residuals: η=∑tSt2/(n2σ^LR2)\eta = \sum_t S_t^2/(n^2 \hat\sigma^2_{\mathrm{LR}}). A stationary series gives partial sums that keep returning to zero, so η\eta stays small. A random walk component makes the partial sums drift, and η\eta grows with nn. Under the null, η\eta tends to the integral of a squared Brownian bridge, the same law as the Cramer-von Mises goodness-of-fit statistic.

In plain words

Draw the best flat line (or the best sloped line) through the series. Then walk along the series and keep a running total of how far each point is above or below the line. If the series really moves around that line, the total goes up and down and keeps coming back near zero. If the series wanders away and does not come back, the total builds up in one direction for long stretches. The test measures how large this running total gets, compared with the normal size of the swings in the data, and calls the series not stationary when the running total is too large. Because nearby points in a series are often alike, the normal size of the swings is measured with that likeness taken into account.

The problem

Model and hypotheses. KPSS write the series as a sum of a deterministic trend, a random walk and a stationary error:

Xt=ξt+rt+εt,rt=rt−1+ut,t=1,…,n,X_t = \xi t + r_t + \varepsilon_t, \qquad r_t = r_{t-1} + u_t, \qquad t = 1, \dots, n,

with utu_t iid (0,σu2)(0, \sigma_u^2) and εt\varepsilon_t a stationary process with long-run variance σ2=∑h∈Zγ(h)=2πf(0)\sigma^2 = \sum_{h \in \mathbb Z}\gamma(h) = 2\pi f(0), where ff is the power spectral density of εt\varepsilon_t. The initial value r0r_0 is a fixed intercept. The null hypothesis is H0:σu2=0H_0: \sigma_u^2 = 0, so XtX_t is stationary around a line (case "ct") or, when ξ=0\xi = 0 is imposed, around a level (case "c"). The alternative is H1:σu2>0H_1: \sigma_u^2 > 0, a unit root.

Statistic. Let ete_t be the residuals of the least squares regression of XtX_t on 11 (case "c") or on 11 and tt (case "ct"), St=∑s=1tesS_t = \sum_{s=1}^{t}e_s, and

σ^2(ℓ)=γ^0+2∑j=1ℓ(1−jℓ+1)γ^j,γ^j=1n∑t=j+1netet−j.\hat\sigma^2(\ell) = \hat\gamma_0 + 2\sum_{j=1}^{\ell}\left(1 - \frac{j}{\ell + 1}\right)\hat\gamma_j, \qquad \hat\gamma_j = \frac1n\sum_{t=j+1}^{n}e_te_{t-j}.

The statistic is η=∑t=1nSt2/(n2σ^2(ℓ))\eta = \sum_{t=1}^{n}S_t^2\big/\left(n^2\hat\sigma^2(\ell)\right). The weights 1−j/(ℓ+1)1 - j/(\ell + 1) are the Bartlett (Newey-West) weights. With Gaussian iid εt\varepsilon_t and ℓ=0\ell = 0, η\eta is the Lagrange multiplier (score) statistic for σu2=0\sigma_u^2 = 0 (Nyblom and Makelainen 1983).

Null distribution. Asymptotic. If ℓ→∞\ell \to \infty and ℓ/n→0\ell/n \to 0 (or ℓ=0\ell = 0 with iid errors), then under H0H_0

η⇒∫01V(r)2 dr,\eta \Rightarrow \int_0^1 V(r)^2\,dr,

where V(r)=W(r)−rW(1)V(r) = W(r) - rW(1) is a Brownian bridge in case "c", and in case "ct" the second-level bridge V2V_2 with covariance K(s,t)=min⁡(s,t)−4st+3st2+3s2t−3s2t2K(s, t) = \min(s, t) - 4st + 3st^2 + 3s^2t - 3s^2t^2 (MacNeill 1978). The law is a weighted sum ∑kλkZk2\sum_k \lambda_k Z_k^2 of independent squared normals, with λk\lambda_k the eigenvalues of the covariance kernel. In case "c", λk=1/(k2π2)\lambda_k = 1/(k^2\pi^2), which is the Cramer-von Mises limit. The mean is 1/61/6 in case "c" and 1/151/15 in case "ct". These limits are cited from KPSS (1992), not proved here.

Rejection rule and size. Reject at level α\alpha when η\eta exceeds the upper α\alpha point:

case 10% 5% 2.5% 1%
"c", KPSS Table 1 0.347 0.463 0.574 0.739
"c", exact limit (Anderson and Darling 1952) 0.3473 0.4614 0.5806 0.7435
"ct", KPSS Table 1 0.119 0.146 0.176 0.216
"ct", limit computed from the kernel eigenvalues 0.1193 0.1479 0.1775 0.2178

The KPSS values come from a simulation of the limit. The second and fourth rows are the quantiles of ∑kλkZk2\sum_k\lambda_kZ_k^2 computed by numerical inversion of the characteristic function (Imhof's method); in case "ct" the eigenvalues were found numerically from KK. The differences are below 0.005 and change no decision except at the boundary. The size is asymptotically α\alpha. In finite samples it is close to α\alpha for iid errors, and too large when the errors are strongly autocorrelated and ℓ\ell is small.

p-value. Interpolate in the table, which only gives pp between 0.01 and 0.10. In case "c" the implementation also gives the exact asymptotic tail P(∑kZk2/(k2π2)>η)P(\sum_k Z_k^2/(k^2\pi^2) > \eta).

Sensitivity and power. The test reacts to a random walk component, and also to anything that makes the partial sums drift: a shift in level, a missed trend, or long memory. Under H1H_1 with ℓ/n→0\ell/n \to 0, η\eta grows at the rate n/ℓn/\ell, so the test is consistent. A larger ℓ\ell protects the size under autocorrelation, but it also divides the statistic, so the power falls.

The algorithm

  1. KPSS(X₁..Xₙ, case, ℓ) ▷ case ∈ {c, ct}, 0 ≤ ℓ < n
  2. 1e ← residuals of X on 1 (case c) or on (1, t) (case ct)
  3. 2S_t ← e₁ + … + e_t for t = 1..n; N ← Σ_t S_t²
  4. 3γ̂_j ← (1/n) Σ_{t=j+1..n} e_t e_{t−j} for j = 0..ℓ
  5. 4σ̂² ← γ̂₀ + 2 Σ_{j=1..ℓ} (1 − j/(ℓ+1)) γ̂_j
  6. 5η ← N / (n² σ̂²)
  7. 6c ← upper α point for the case (table)
  8. 7return (η, reject ⇔ η > c)

KPSS proposed two bandwidths, ℓ4=⌊4(n/100)1/4⌋\ell_4 = \lfloor 4(n/100)^{1/4}\rfloor and ℓ12=⌊12(n/100)1/4⌋\ell_{12} = \lfloor 12(n/100)^{1/4}\rfloor. At n=100n = 100 these are 4 and 12, and at n=200n = 200 they are 4 and 14. Hobijn, Franses and Ooms (2004) give a data-driven choice. Line L1 has a closed form: in case "c", et=Xt−Xˉe_t = X_t - \bar X; in case "ct", et=Xt−Xˉ−b^(t−tˉ)e_t = X_t - \bar X - \hat b(t - \bar t) with b^=∑(t−tˉ)Xt/∑(t−tˉ)2\hat b = \sum(t - \bar t)X_t/\sum(t - \bar t)^2.

Example

By hand. Take X=(3,5,4,6,8,7,9,8)X = (3, 5, 4, 6, 8, 7, 9, 8), the series of the ADF example, in case "c". The mean is 6.256.25:

step value
L1: ete_t −3.25,−1.25,−2.25,−0.25,1.75,0.75,2.75,1.75-3.25, -1.25, -2.25, -0.25, 1.75, 0.75, 2.75, 1.75
L2: StS_t −3.25,−4.5,−6.75,−7,−5.25,−4.5,−1.75,0-3.25, -4.5, -6.75, -7, -5.25, -4.5, -1.75, 0
L2: N=∑St2N = \sum S_t^2 705/4=176.25705/4 = 176.25
L3: γ^0,γ^1,γ^2\hat\gamma_0, \hat\gamma_1, \hat\gamma_2 63/16,243/128,77/6463/16, 243/128, 77/64
L5: η\eta with ℓ=0\ell = 0 235/336=0.6994235/336 = 0.6994
L5: η\eta with ℓ=1\ell = 1 (σ^2=747/128\hat\sigma^2 = 747/128) 235/498=0.4719235/498 = 0.4719
L5: η\eta with ℓ=2\ell = 2 (σ^2=349/48\hat\sigma^2 = 349/48) 2115/5584=0.37882115/5584 = 0.3788

With ℓ=0\ell = 0 or 11 the test rejects level stationarity at 5% (η>0.463\eta > 0.463). With ℓ=2\ell = 2 it does not, and the table p-value is about 0.09. The partial sums stay negative for the whole sample, because the series rises: the first half is below the mean and the second half above. In case "ct" the line takes out the rise, the residuals are −1/2,5/7,−15/14,1/7,19/14,−3/7,11/14,−1-1/2, 5/7, -15/14, 1/7, 19/14, -3/7, 11/14, -1, N=3N = 3, and η=7/104=0.0673\eta = 7/104 = 0.0673 with ℓ=0\ell = 0, far below 0.146. So the data are compatible with stationarity around a line.

A random walk against a stationary series. The same 200 shocks as on the ADF page (seed 2026) give:

series ℓ\ell η\eta table p-value
random walk ℓ4=4\ell_4 = 4 3.373 ≤0.01\le 0.01
random walk ℓ12=14\ell_{12} = 14 1.230 ≤0.01\le 0.01
AR(1), ϕ1=0.5\phi_1 = 0.5 ℓ4=4\ell_4 = 4 0.116 ≥0.10\ge 0.10
AR(1), ϕ1=0.5\phi_1 = 0.5 ℓ12=14\ell_{12} = 14 0.120 ≥0.10\ge 0.10

Here the ADF and KPSS tests agree. For the random walk, the larger bandwidth cuts η\eta by almost two thirds.

Size and power (measured, 500 to 2000 samples each). With iid normal data and ℓ=0\ell = 0, the 5% rejection rate was 0.0545 at n=100n = 100 and 0.0525 at n=400n = 400 in case "c". Against a random walk the 5% power was 0.81 with ℓ4\ell_4 and 0.62 with ℓ12\ell_{12} at n=100n = 100, and 0.94 and 0.71 at n=200n = 200. For a stationary AR(1) with ϕ1=0.9\phi_1 = 0.9 and n=200n = 200, the test wrongly rejected in 50% of samples with ℓ4\ell_4 and 17% with ℓ12\ell_{12}.

Correctness

The correctness proof shows four facts. The residuals of line L1 sum to zero (and are orthogonal to tt in case "ct"), so Sn=0S_n = 0 and the partial sums are a bridge from 0 to 0. The Bartlett estimate of line L4 equals 1n(ℓ+1)∑t(∑i=0ℓet+i)2\frac{1}{n(\ell+1)}\sum_t\left(\sum_{i=0}^{\ell}e_{t+i}\right)^2 with ee set to 0 outside 1..n1..n, so it is never negative, and lines L3 to L5 compute the stated η\eta. The statistic is invariant to Xt↦a+cXtX_t \mapsto a + cX_t (case "c") and to Xt↦a+bt+cXtX_t \mapsto a + bt + cX_t (case "ct"), for c≠0c \ne 0. For iid errors with variance σ2\sigma^2 in case "c", E∑tSt2=σ2(n2−1)/6E\sum_tS_t^2 = \sigma^2(n^2 - 1)/6 exactly, which matches the limit mean 1/61/6. The Brownian bridge limits and the consistency under the alternative are cited from KPSS (1992).

Proof: KPSS computes the stated statistic with a nonnegative long-run variance, the statistic is invariant to level, scale and trend, and its numerator has the exact mean of the Brownian bridge limitfull

We prove that KPSS returns η=∑tSt2/(n2σ^2(ℓ))\eta = \sum_t S_t^2/(n^2\hat\sigma^2(\ell)) with residual partial sums that start and end at 0 (Lemma 1), that the Bartlett estimate σ^2(ℓ)\hat\sigma^2(\ell) is never negative (Lemma 2), that η\eta is invariant to the maps of Lemma 3, and that in case "c" with iid errors the numerator has mean σ2(n2−1)/6\sigma^2(n^2 - 1)/6 (Lemma 4), whose scaled limit 1/61/6 is the mean of ∫01V(r)2dr\int_0^1V(r)^2dr for a Brownian bridge VV. We do not prove the limit law η⇒∫01V2\eta \Rightarrow \int_0^1V^2, the consistency of σ^2(ℓ)\hat\sigma^2(\ell) for ℓ→∞\ell \to \infty, ℓ/n→0\ell/n \to 0, or the divergence of η\eta under a unit root. These are Theorems in Kwiatkowski, Phillips, Schmidt and Shin (1992), with the partial-sum limit for polynomial regression from MacNeill (1978).

Lemma 1 (line L1 and the bridge). In case "c", et=Xt−Xˉe_t = X_t - \bar X is the least squares residual on 11, and ∑tet=0\sum_te_t = 0. In case "ct", with tˉ=(n+1)/2\bar t = (n + 1)/2 and b^=∑t(t−tˉ)Xt/∑t(t−tˉ)2\hat b = \sum_t(t - \bar t)X_t/\sum_t(t - \bar t)^2, et=Xt−Xˉ−b^(t−tˉ)e_t = X_t - \bar X - \hat b(t - \bar t) is the least squares residual on 11 and tt, and ∑tet=∑ttet=0\sum_te_t = \sum_t te_t = 0. In both cases Sn=0S_n = 0.

Proof. The columns 11 and t−tˉt - \bar t are orthogonal, since ∑t(t−tˉ)=0\sum_t(t - \bar t) = 0. The least squares fit on an orthogonal basis is the sum of the separate projections, which are Xˉ⋅1\bar X \cdot 1 and b^(t−tˉ)\hat b(t - \bar t). The span of 11 and t−tˉt - \bar t equals the span of 11 and tt. A least squares residual is orthogonal to every regressor, so ∑et=0\sum e_t = 0, and in case "ct" also ∑tet=0\sum te_t = 0. Finally Sn=∑tet=0S_n = \sum_te_t = 0. □\square

Lemma 2 (the Bartlett estimate is nonnegative). Extend ee by et=0e_t = 0 for t≤0t \le 0 and t>nt > n. For ℓ≥0\ell \ge 0,

γ^0+2∑j=1ℓ(1−jℓ+1)γ^j=1n(ℓ+1)∑t=−ℓ+1n(∑i=0ℓet+i)2 ≥0.\hat\gamma_0 + 2\sum_{j=1}^{\ell}\left(1 - \frac{j}{\ell + 1}\right)\hat\gamma_j = \frac{1}{n(\ell + 1)}\sum_{t=-\ell+1}^{n}\left(\sum_{i=0}^{\ell}e_{t+i}\right)^2 \ \ge 0.

Proof. Expand the square: ∑t(∑i=0ℓet+i)2=∑i=0ℓ∑i′=0ℓ∑tet+iet+i′\sum_t\left(\sum_{i=0}^{\ell}e_{t+i}\right)^2 = \sum_{i=0}^{\ell}\sum_{i'=0}^{\ell}\sum_te_{t+i}e_{t+i'}. For fixed i,i′i, i' with ∣i−i′∣=j|i - i'| = j, the inner sum runs over all tt for which both indices lie in 1..n1..n, so it equals ∑s=j+1neses−j=nγ^j\sum_{s=j+1}^{n}e_se_{s-j} = n\hat\gamma_j. The number of pairs (i,i′)(i, i') in {0,…,ℓ}2\{0, \dots, \ell\}^2 with i−i′=ji - i' = j is ℓ+1−∣j∣\ell + 1 - |j|. So the sum is n∑j=−ℓℓ(ℓ+1−∣j∣)γ^∣j∣=n(ℓ+1)(γ^0+2∑j=1ℓ(1−j/(ℓ+1))γ^j)n\sum_{j=-\ell}^{\ell}(\ell + 1 - |j|)\hat\gamma_{|j|} = n(\ell + 1)\left(\hat\gamma_0 + 2\sum_{j=1}^{\ell}(1 - j/(\ell + 1))\hat\gamma_j\right). Divide by n(ℓ+1)n(\ell + 1). □\square

The estimate is 0 only if every window sum ∑i=0ℓet+i\sum_{i=0}^{\ell}e_{t+i} is 0. The window that starts at t=−ℓ+1t = -\ell + 1 contains only e1e_1, so then e1=0e_1 = 0, and by induction along the windows all et=0e_t = 0. The implementation reports this case as an error. Without the Bartlett weights the estimate can be negative: for e=(1,−1,1,−1)e = (1, -1, 1, -1) and ℓ=1\ell = 1, γ^0+2γ^1=1−3/2<0\hat\gamma_0 + 2\hat\gamma_1 = 1 - 3/2 < 0, while the Bartlett value is 1−3/4=1/41 - 3/4 = 1/4.

With Lemmas 1 and 2, lines L2 to L5 compute N=∑St2N = \sum S_t^2, the autocovariances, σ^2(ℓ)>0\hat\sigma^2(\ell) > 0 and η=N/(n2σ^2(ℓ))\eta = N/(n^2\hat\sigma^2(\ell)), which is the statistic defined on the page.

Lemma 3 (invariance). Let c≠0c \ne 0. In case "c", the map Xt↦a+cXtX_t \mapsto a + cX_t leaves η\eta unchanged. In case "ct", so does Xt↦a+bt+cXtX_t \mapsto a + bt + cX_t.

Proof. The residual map X↦eX \mapsto e is the linear projection MM onto the orthogonal complement of the regressors, so M(a1+bt+cX)=cMXM(a\mathbf 1 + b\mathbf t + cX) = cMX whenever a1+bta\mathbf 1 + b\mathbf t lies in the regressor span (with b=0b = 0 in case "c"). So ee becomes cece, every StS_t becomes cStcS_t, every γ^j\hat\gamma_j becomes c2γ^jc^2\hat\gamma_j, and NN and σ^2(ℓ)\hat\sigma^2(\ell) are both multiplied by c2c^2. Their ratio is unchanged. □\square

Lemma 4 (the mean of the numerator). In case "c", let Xt=μ+εtX_t = \mu + \varepsilon_t with εt\varepsilon_t uncorrelated, mean 0 and variance σ2\sigma^2. Then Var⁡(St)=σ2t(n−t)/n\operatorname{Var}(S_t) = \sigma^2t(n - t)/n and

E∑t=1nSt2=σ2n2−16,so1n2σ2E∑tSt2→16=E∫01V(r)2 dr.E\sum_{t=1}^{n}S_t^2 = \sigma^2\frac{n^2 - 1}{6}, \qquad \text{so} \qquad \frac{1}{n^2\sigma^2}E\sum_tS_t^2 \to \frac16 = E\int_0^1V(r)^2\,dr.

Proof. St=∑s≤t(εs−εˉ)=At−(t/n)AnS_t = \sum_{s \le t}(\varepsilon_s - \bar\varepsilon) = A_t - (t/n)A_n with At=∑s≤tεsA_t = \sum_{s \le t}\varepsilon_s. Since Var⁡(At)=tσ2\operatorname{Var}(A_t) = t\sigma^2 and Cov⁡(At,An)=tσ2\operatorname{Cov}(A_t, A_n) = t\sigma^2, Var⁡(St)=σ2(t−2t2/n+t2/n)=σ2t(n−t)/n\operatorname{Var}(S_t) = \sigma^2\left(t - 2t^2/n + t^2/n\right) = \sigma^2t(n - t)/n, and ESt=0ES_t = 0. Summing, ∑t=1nt(n−t)/n=(n⋅n(n+1)2−n(n+1)(2n+1)6)/n=(n+1)(n−1)6\sum_{t=1}^{n}t(n - t)/n = \left(n\cdot\frac{n(n+1)}{2} - \frac{n(n+1)(2n+1)}{6}\right)/n = \frac{(n+1)(n-1)}{6}. For the limit, EV(r)2=r(1−r)E V(r)^2 = r(1 - r) and ∫01r(1−r)dr=1/6\int_0^1r(1 - r)dr = 1/6. □\square

The same computation in case "ct" gives the limit mean ∫01K(r,r)dr=∫01(r−4r2+6r3−3r4)dr=1/15\int_0^1K(r, r)dr = \int_0^1(r - 4r^2 + 6r^3 - 3r^4)dr = 1/15, which is the trace of the covariance kernel KK stated on the page, and the sum of its eigenvalues.

Cited: the limit law and consistency. Under H0H_0, with εt\varepsilon_t satisfying a functional central limit theorem with long-run variance σ2>0\sigma^2 > 0, n−1/2S⌊nr⌋⇒σV(r)n^{-1/2}S_{\lfloor nr\rfloor} \Rightarrow \sigma V(r) (MacNeill 1978 for polynomial regression residuals), and σ^2(ℓ)→σ2\hat\sigma^2(\ell) \to \sigma^2 in probability when ℓ→∞\ell \to \infty, ℓ/n→0\ell/n \to 0. The continuous mapping theorem then gives η⇒∫01V2\eta \Rightarrow \int_0^1V^2. Under H1H_1, η\eta is of exact order n/ℓn/\ell in probability, so P(η>c)→1P(\eta > c) \to 1 for every fixed cc (KPSS 1992). The quantiles in the table of the page were computed numerically from the eigenvalue expansion of the limit and are not part of the proof.

Termination. Every line is a finite loop over t=1..nt = 1..n or j=0..ℓj = 0..\ell. □\square

Complexity

On a real RAM, line L1 is one pass for the means and one for the slope, Θ(n)\Theta(n). Line L2 is one pass. Line L3 computes ℓ+1\ell + 1 sums of at most nn products, Θ(n(ℓ+1))\Theta(n(\ell + 1)). Lines L4 to L7 cost Θ(ℓ)\Theta(\ell). The total is Θ(n(ℓ+1))\Theta(n(\ell + 1)) time, which is Θ(n5/4)\Theta(n^{5/4}) for the ℓ4\ell_4 and ℓ12\ell_{12} rules, and Θ(n)\Theta(n) extra space for ee. The autocovariances can also be computed for all lags at once by an FFT in Θ(nlog⁡n)\Theta(n\log n).

Numerical stability. Compute ete_t from centered quantities (Xt−XˉX_t - \bar X and t−tˉt - \bar t), not from the raw normal equations, because ∑t2\sum t^2 and (∑t)2(\sum t)^2 are both of order n3n^3 to n4n^4 and their difference loses digits. The partial sums StS_t are sums of numbers of both signs whose total is zero, so their relative error is small only if ete_t is accurate.

Properties

  • The reverse null. Stationarity is the null and the unit root the alternative, the opposite of the ADF test. Used together, the pair can say "stationary", "unit root" or "the data cannot tell".
  • Locally best invariant. In the Gaussian components model with iid errors and ℓ=0\ell = 0, the test is the locally best invariant test of σu2=0\sigma_u^2 = 0 (Nyblom and Makelainen 1983).
  • Invariant. η\eta does not depend on the level or the scale of the series, nor on an added line in case "ct".
  • Free of nuisance parameters in the limit. The limit law depends only on the case, because σ^2(ℓ)\hat\sigma^2(\ell) estimates the long-run variance consistently when ℓ→∞\ell \to \infty and ℓ/n→0\ell/n \to 0.
  • A Cramer-von Mises statistic. In case "c", η\eta is the Cramer-von Mises statistic of the partial-sum process, so its limit is the same as that of the goodness-of-fit test, with 5% point 0.4614.
  • Sensitive to the bandwidth. The value of η\eta can change by a factor of 2 or more between ℓ4\ell_4 and ℓ12\ell_{12}, as in the examples.

Variants and improvements

  • Leybourne-McCabe test. Model the short-run correlation by an ARMA fit instead of a nonparametric long-run variance. Its size is better when the autocorrelation is strong (Leybourne and McCabe 1994).
  • Automatic bandwidth. Choose ℓ\ell from the data, as in Newey and West (1994) or Hobijn, Franses and Ooms (2004). Most software uses such a rule by default.
  • Other kernels. The quadratic spectral kernel or a prewhitened Bartlett kernel estimates the long-run variance with less bias.
  • Tests with breaks. Allow a known or estimated shift in level or slope, so that a single break is not read as a unit root.
  • Panel versions. Average the statistic over many series, as in the Hadri test.
  • A CUSUM view. The same partial sums StS_t are the basis of the CUSUM test for a change in mean. KPSS uses their sum of squares; CUSUM-type tests use their maximum.

When to use it

Use the KPSS test together with the ADF test or DF-GLS, before choosing between a model in levels and a model in differences. Use case "ct" when the series has a visible trend. It is also a natural test for the residuals of a cointegrating regression, where the null of interest is that the residuals are stationary. Report the bandwidth with the result.

Pitfalls

  • Small bandwidth with strong autocorrelation. A stationary AR(1) with root 0.9 is rejected half the time at n=200n = 200 with ℓ4\ell_4. Caner and Kilian (2001) show the same distortion for persistent stationary series. A larger ℓ\ell helps the size, at the cost of power.
  • Large bandwidth. With ℓ\ell close to nn, σ^2(ℓ)\hat\sigma^2(\ell) is inflated under the alternative, and the test loses its power.
  • Missing the trend. A trend-stationary series tested in case "c" is rejected almost always, because the partial sums of a line are a parabola.
  • Level shifts. One break in the mean makes the partial sums drift, so the test rejects stationarity. Check for breaks with change-point detection.
  • Reading the table p-value as exact. Interpolation in a four-row table gives only rough p-values, and values outside 0.01 to 0.10 are clipped.
  • Treating both tests as independent. The ADF and KPSS tests use the same data. Combining their decisions does not have a simple overall size.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

kpss_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kpss-test/. The authors are listed in prov/AWK28P.jsonl.
"""The KPSS test of the null of (level or trend) stationarity against a unit root.

Regress x_t on a constant (case "c") or on a constant and a trend (case "ct"),
form the partial sums S_t of the residuals, estimate the long-run variance
with Bartlett weights, and return

    eta = sum_t S_t^2 / (n^2 s^2(l)).

Large eta rejects stationarity. The arithmetic is generic: with Fraction
input every step except the bandwidth rule is exact.
The code is in this file and not in kpss_test.py, because tools treat a file
whose name ends in _test.py as a test file.
"""

import math
import random

# Kwiatkowski, Phillips, Schmidt and Shin (1992), Table 1 (upper tail).
KPSS_TABLE = {
    "c": {0.10: 0.347, 0.05: 0.463, 0.025: 0.574, 0.01: 0.739},
    "ct": {0.10: 0.119, 0.05: 0.146, 0.025: 0.176, 0.01: 0.216},
}


def detrend(x, case="c"):
    """Least squares residuals of x on 1 (case "c") or on 1 and t (case "ct")."""
    n = len(x)
    mean = sum(x) / n
    if case == "c":
        return [v - mean for v in x]
    if case != "ct":
        raise ValueError("case must be 'c' or 'ct'")
    tbar = (n + 1) / 2 if isinstance(mean, float) else type(mean)(n + 1, 2)
    tc = [t + 1 - tbar for t in range(n)]
    b = sum(c * v for c, v in zip(tc, x)) / sum(c * c for c in tc)
    return [v - mean - b * c for v, c in zip(x, tc)]


def bandwidth(n, rule="l4"):
    """The KPSS truncation lags: l4 = floor(4 (n/100)^(1/4)), l12 = floor(12 (n/100)^(1/4)),
    l0 = 0, or an integer given directly."""
    if isinstance(rule, int):
        return rule
    return {"l0": 0, "l4": int(4.0 * (n / 100.0) ** 0.25), "l12": int(12.0 * (n / 100.0) ** 0.25)}[rule]


def autocovariances(e, lags):
    """gamma_j = (1/n) sum_(t>j) e_t e_(t-j) for j = 0..lags."""
    n = len(e)
    return [sum(e[t] * e[t - j] for t in range(j, n)) / n for j in range(lags + 1)]


def bartlett(gam):
    """gamma_0 + 2 sum_(j=1..l) (1 - j/(l+1)) gamma_j, the Bartlett (Newey-West) weights."""
    lags = len(gam) - 1
    s2 = gam[0]
    for j in range(1, lags + 1):
        w = 1 - (j / (lags + 1) if isinstance(gam[0], float) else type(gam[0])(j, lags + 1))
        s2 = s2 + 2 * w * gam[j]
    return s2


def long_run_variance(e, lags):
    """The Bartlett estimate of the long-run variance of e with the given lags."""
    return bartlett(autocovariances(e, lags))


def kpss(x, case="c", lags="l4"):
    """The KPSS statistic eta, the lags used, and reject at 5% (eta > table value)."""
    n = len(x)
    if n < 3:
        raise ValueError("need at least 3 observations")
    ell = bandwidth(n, lags)
    if not 0 <= ell < n:
        raise ValueError("the number of lags must be in 0..n-1")
    e = detrend(x, case)  # @line L1
    s, ssum = 0, 0
    for v in e:  # @line L2
        s = s + v
        ssum = ssum + s * s
    gam = autocovariances(e, ell)  # @line L3
    s2 = bartlett(gam)  # @line L4
    if s2 == 0:
        raise ValueError("the residuals are all zero")
    eta = ssum / (n * n * s2)  # @line L5
    crit = KPSS_TABLE[case]  # @line L6
    return {"eta": eta, "lags": ell, "critical": crit, "reject": eta > crit[0.05],  # @line L7
            "p_value": table_p_value(float(eta), case)}


def table_p_value(eta, case="c"):
    """Linear interpolation in the KPSS table, clipped to [0.01, 0.10].
    A value of 0.10 means "0.10 or more" and 0.01 means "0.01 or less"."""
    pts = sorted(KPSS_TABLE[case].items(), key=lambda kv: kv[1])
    crit = [c for _, c in pts]
    lev = [a for a, _ in pts]
    if eta <= crit[0]:
        return lev[0]
    if eta >= crit[-1]:
        return lev[-1]
    for i in range(len(crit) - 1):
        if crit[i] <= eta <= crit[i + 1]:
            w = (eta - crit[i]) / (crit[i + 1] - crit[i])
            return lev[i] + w * (lev[i + 1] - lev[i])
    return lev[-1]


def simulate_null(n, case="c", lags=0, reps=1000, rng=None):
    """eta for reps iid N(0, 1) series of length n (the null, stationary)."""
    rng = rng or random.Random(0)
    return [kpss([rng.gauss(0.0, 1.0) for _ in range(n)], case, lags)["eta"] for _ in range(reps)]


def cvm_limit_sf(x, terms=200):
    """Asymptotic P(eta > x) in case "c": eta tends to sum_k Z_k^2 / (k^2 pi^2),
    the Cramer-von Mises limit. Computed by numerical inversion of the
    characteristic function (Imhof), truncated at terms and corrected for the
    mean of the tail. Accurate to about 1e-4."""
    lam = [1.0 / (k * k * math.pi * math.pi) for k in range(1, terms + 1)]
    x = x - (1.0 / 6.0 - sum(lam))

    def f(u):
        th = 0.5 * sum(math.atan(l * u) for l in lam) - 0.5 * x * u
        rho = math.exp(0.25 * sum(math.log1p((l * u) ** 2) for l in lam))
        return math.sin(th) / (u * rho)

    edges = [0.0] + [10 ** (k / 8.0) for k in range(-24, 41)]
    total = 0.0
    for lo, hi in zip(edges, edges[1:]):
        m = 24
        h = (hi - lo) / m
        acc = 0.0
        for i in range(m + 1):
            u = lo + i * h
            fu = 0.5 * (sum(lam) - x) if u == 0 else f(u)
            acc += fu * (1 if i in (0, m) else (4 if i % 2 else 2))
        total += acc * h / 3
    return 0.5 + total / math.pi
kpss_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kpss-test/. The authors are listed in prov/AWK28P.jsonl.
"""Entry point named after the slug. The code lives in kpss_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from kpss_core import (KPSS_TABLE, autocovariances, bandwidth, bartlett, cvm_limit_sf, detrend,
                       kpss, long_run_variance, simulate_null, table_p_value)

__all__ = ["KPSS_TABLE", "autocovariances", "bandwidth", "bartlett", "cvm_limit_sf", "detrend",
           "kpss", "long_run_variance", "simulate_null", "table_p_value"]
test_kpss_test.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kpss-test/. The authors are listed in prov/AWK28P.jsonl.

import math
import random
from fractions import Fraction

import pytest

from kpss_test import (KPSS_TABLE, autocovariances, bandwidth, bartlett, cvm_limit_sf, detrend,
                       kpss, long_run_variance, simulate_null, table_p_value)

EXAMPLE = [Fraction(v) for v in (3, 5, 4, 6, 8, 7, 9, 8)]


def brute_eta(x, case, ell):
    """Brute force in exact rationals: residuals from the normal equations,
    partial sums by direct summation, and the Bartlett sum term by term."""
    n = len(x)
    cols = [[Fraction(1)] * n] + ([[Fraction(t + 1) for t in range(n)]] if case == "ct" else [])
    k = len(cols)
    a = [[sum(p * q for p, q in zip(cols[i], cols[j])) for j in range(k)]
         + [sum(p * q for p, q in zip(cols[i], x))] for i in range(k)]
    if k == 1:
        b = [a[0][1] / a[0][0]]
    else:
        det = a[0][0] * a[1][1] - a[0][1] * a[1][0]
        b = [(a[0][2] * a[1][1] - a[0][1] * a[1][2]) / det, (a[0][0] * a[1][2] - a[1][0] * a[0][2]) / det]
    e = [x[t] - sum(b[j] * cols[j][t] for j in range(k)) for t in range(n)]
    num = sum(sum(e[:t + 1]) ** 2 for t in range(n))
    s2 = sum(v * v for v in e) / n
    for j in range(1, ell + 1):
        s2 += 2 * (1 - Fraction(j, ell + 1)) * sum(e[t] * e[t - j] for t in range(j, n)) / n
    return num / (n * n * s2)


def test_worked_example() -> None:
    r = kpss(EXAMPLE, "c", 0)
    assert r["eta"] == Fraction(235, 336)
    assert r["reject"]
    assert kpss(EXAMPLE, "c", 1)["eta"] == Fraction(235, 498)
    assert kpss(EXAMPLE, "c", 2)["eta"] == Fraction(2115, 5584)
    assert not kpss(EXAMPLE, "c", 2)["reject"]
    assert kpss(EXAMPLE, "ct", 0)["eta"] == Fraction(7, 104)
    assert kpss(EXAMPLE, "ct", 1)["eta"] == Fraction(7, 52)


@pytest.mark.parametrize("case", ["c", "ct"])
@pytest.mark.parametrize("ell", [0, 1, 2, 5])
def test_matches_brute_force(case, ell) -> None:
    rng = random.Random(10 * ell + len(case))
    x = [Fraction(rng.randint(-30, 30), rng.randint(1, 4)) for _ in range(17)]
    assert kpss(x, case, ell)["eta"] == brute_eta(x, case, ell)


@pytest.mark.parametrize("case", ["c", "ct"])
def test_residuals_are_orthogonal(case) -> None:
    # S_n = 0 always, and sum t e_t = 0 in case "ct".
    rng = random.Random(3)
    x = [Fraction(rng.randint(-9, 9)) for _ in range(12)]
    e = detrend(x, case)
    assert sum(e) == 0
    if case == "ct":
        assert sum((t + 1) * v for t, v in enumerate(e)) == 0


def test_bartlett_estimate_is_nonnegative() -> None:
    # The Bartlett weights give a nonnegative long-run variance for every series.
    rng = random.Random(4)
    for _ in range(200):
        n = rng.randint(3, 15)
        e = [Fraction(rng.randint(-5, 5)) for _ in range(n)]
        for ell in range(n):
            assert long_run_variance(e, ell) >= 0
    # Truncated uniform weights can go negative: e = (1, -1, 1, -1), l = 1.
    gam = autocovariances([1, -1, 1, -1], 1)
    assert gam[0] + 2 * gam[1] < 0
    assert bartlett(gam) >= 0


@pytest.mark.parametrize("case,move", [("c", lambda t, v: 5 - 2 * v), ("ct", lambda t, v: 1 + 3 * t + 0.5 * v)])
def test_invariance(case, move) -> None:
    rng = random.Random(8)
    x = [rng.gauss(0, 1) for _ in range(50)]
    y = [move(t, v) for t, v in enumerate(x)]
    for ell in (0, 3, 12):
        assert abs(kpss(x, case, ell)["eta"] - kpss(y, case, ell)["eta"]) < 1e-9


def test_mean_of_numerator() -> None:
    # Var(S_t) = t (n - t) / n for iid unit-variance errors in case "c", so
    # E sum S_t^2 / n^2 = (n^2 - 1) / (6 n^2). Checked from the exact covariance of e.
    n = 9
    m = [[Fraction(int(i == j)) - Fraction(1, n) for j in range(n)] for i in range(n)]
    for t in range(1, n + 1):
        var = sum(m[i][j] for i in range(t) for j in range(t))
        assert var == Fraction(t * (n - t), n)
    total = sum(Fraction(t * (n - t), n) for t in range(1, n + 1))
    assert total / n ** 2 == Fraction(n * n - 1, 6 * n * n)


def test_bandwidth_rules() -> None:
    assert [bandwidth(n, "l4") for n in (50, 100, 200, 1000)] == [3, 4, 4, 7]
    assert [bandwidth(n, "l12") for n in (50, 100, 200, 1000)] == [10, 12, 14, 21]
    assert bandwidth(100, 7) == 7


@pytest.mark.parametrize("case", ["c", "ct"])
def test_size_against_table(case) -> None:
    # iid N(0, 1), n = 200, l = 0, 2000 samples: the 5% rejection rate must be
    # within 4 binomial standard errors (0.0195) of 0.05.
    reps = 2000
    sims = simulate_null(200, case, 0, reps, random.Random(31 if case == "c" else 32))
    rate = sum(1 for v in sims if v > KPSS_TABLE[case][0.05]) / reps
    assert abs(rate - 0.05) < 4 * math.sqrt(0.05 * 0.95 / reps)


def test_asymptotic_level_case() -> None:
    # The level-case limit is the Cramer-von Mises law. Its exact 5% point is
    # 0.4614 (Anderson and Darling 1952); the KPSS table rounds a simulation to 0.463.
    assert abs(cvm_limit_sf(0.4614) - 0.05) < 2e-4
    assert abs(cvm_limit_sf(0.3473) - 0.10) < 2e-4
    assert abs(cvm_limit_sf(0.7435) - 0.01) < 2e-4
    assert abs(cvm_limit_sf(0.463) - 0.05) < 1e-3


def test_power_against_random_walk() -> None:
    rng = random.Random(9)
    rej = 0
    for _ in range(50):
        s, y = 0.0, []
        for _ in range(200):
            s += rng.gauss(0, 1)
            y.append(s)
        rej += kpss(y, "c", "l4")["reject"]
    assert rej >= 40


def test_table_p_value() -> None:
    assert table_p_value(0.2) == 0.10
    assert table_p_value(0.463) == 0.05
    assert table_p_value(2.0) == 0.01
    assert abs(table_p_value((0.347 + 0.463) / 2) - 0.075) < 1e-12
    assert table_p_value(0.146, "ct") == 0.05


def test_rejects_bad_input() -> None:
    with pytest.raises(ValueError):
        kpss([1, 2], "c", 0)
    with pytest.raises(ValueError):
        kpss([1, 1, 1, 1], "c", 0)
    with pytest.raises(ValueError):
        kpss([1, 2, 3, 5], "x", 0)

History

Nyblom and Makelainen (1983) derived the locally best invariant test for a random walk component in a regression with iid errors, and Nabeya and Tanaka (1988) studied its distribution. Kwiatkowski, Phillips, Schmidt and Shin published the version with a nonparametric long-run variance in the Journal of Econometrics in 1992, in response to the many studies that could not reject a unit root in macroeconomic series with the Dickey-Fuller test. Their aim was a test in which stationarity is the null, so that the two tests could be run side by side. The limit in case "c" was already known in goodness-of-fit testing, where Anderson and Darling (1952) had computed its distribution.

References

  1. Denis Kwiatkowski, Peter C. B. Phillips, Peter Schmidt and Yongcheol Shin, Testing the null hypothesis of stationarity against the alternative of a unit root, Journal of Econometrics 54(1-3) (1992), pages 159 to 178, the components model, the LM statistic, the limits as integrals of Brownian bridges, and Table 1 (page 166) of upper tail critical values
  2. Jukka Nyblom and Timo Makelainen, Comparisons of tests for the presence of random walk coefficients in a simple linear model, Journal of the American Statistical Association 78(384) (1983), pages 856 to 864, the locally best invariant test of a zero random walk variance, the level case of the KPSS statistic
  3. Whitney K. Newey and Kenneth D. West, A simple, positive semi-definite, heteroskedasticity and autocorrelation consistent covariance matrix, Econometrica 55(3) (1987), pages 703 to 708, the Bartlett weights and the proof that the estimate is nonnegative
  4. T. W. Anderson and D. A. Darling, Asymptotic theory of certain goodness of fit criteria based on stochastic processes, Annals of Mathematical Statistics 23(2) (1952), pages 193 to 212, the law of the integral of a squared Brownian bridge (the Cramer-von Mises limit) and its percentage points
  5. Ian B. MacNeill, Properties of sequences of partial sums of polynomial regression residuals with applications to tests for change of regression at unknown times, Annals of Statistics 6(2) (1978), pages 422 to 433, the limit of partial sums of residuals from a polynomial regression (the second-level Brownian bridge of the trend case)
  6. Bart Hobijn, Philip Hans Franses and Marius Ooms, Generalizations of the KPSS-test for stationarity, Statistica Neerlandica 58(4) (2004), pages 483 to 502, the automatic bandwidth choice for the long-run variance

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example