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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , and compares the size of that sum with the long-run variance of the residuals: . A stationary series gives partial sums that keep returning to zero, so stays small. A random walk component makes the partial sums drift, and grows with . Under the null, 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:
with iid and a stationary process with long-run variance , where is the power spectral density of . The initial value is a fixed intercept. The null hypothesis is , so is stationary around a line (case "ct") or, when is imposed, around a level (case "c"). The alternative is , a unit root.
Statistic. Let be the residuals of the least squares regression of on (case "c") or on and (case "ct"), , and
The statistic is . The weights are the Bartlett (Newey-West) weights. With Gaussian iid and , is the Lagrange multiplier (score) statistic for (Nyblom and Makelainen 1983).
Null distribution. Asymptotic. If and (or with iid errors), then under
where is a Brownian bridge in case "c", and in case "ct" the second-level bridge with covariance (MacNeill 1978). The law is a weighted sum of independent squared normals, with the eigenvalues of the covariance kernel. In case "c", , which is the Cramer-von Mises limit. The mean is in case "c" and in case "ct". These limits are cited from KPSS (1992), not proved here.
Rejection rule and size. Reject at level when exceeds the upper 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 computed by numerical inversion of the characteristic function (Imhof's method); in case "ct" the eigenvalues were found numerically from . The differences are below 0.005 and change no decision except at the boundary. The size is asymptotically . In finite samples it is close to for iid errors, and too large when the errors are strongly autocorrelated and is small.
p-value. Interpolate in the table, which only gives between 0.01 and 0.10. In case "c" the implementation also gives the exact asymptotic tail .
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 with , grows at the rate , so the test is consistent. A larger protects the size under autocorrelation, but it also divides the statistic, so the power falls.
The algorithm
KPSS(X₁..Xₙ, case, ℓ) ▷ case ∈ {c, ct}, 0 ≤ ℓ < n- 1
e ← residuals of X on 1 (case c) or on (1, t) (case ct) - 2
S_t ← e₁ + … + e_t for t = 1..n; N ← Σ_t S_t² - 3
γ̂_j ← (1/n) Σ_{t=j+1..n} e_t e_{t−j} for j = 0..ℓ - 4
σ̂² ← γ̂₀ + 2 Σ_{j=1..ℓ} (1 − j/(ℓ+1)) γ̂_j - 5
η ← N / (n² σ̂²) - 6
c ← upper α point for the case (table) - 7
return (η, reject ⇔ η > c)
KPSS proposed two bandwidths, and . At these are 4 and 12, and at they are 4 and 14. Hobijn, Franses and Ooms (2004) give a data-driven choice. Line L1 has a closed form: in case "c", ; in case "ct", with .
Example
By hand. Take , the series of the ADF example, in case "c". The mean is :
| step | value |
|---|---|
| L1: | |
| L2: | |
| L2: | |
| L3: | |
| L5: with | |
| L5: with () | |
| L5: with () |
With or the test rejects level stationarity at 5% (). With 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 , , and with , 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 | table p-value | ||
|---|---|---|---|
| random walk | 3.373 | ||
| random walk | 1.230 | ||
| AR(1), | 0.116 | ||
| AR(1), | 0.120 |
Here the ADF and KPSS tests agree. For the random walk, the larger bandwidth cuts by almost two thirds.
Size and power (measured, 500 to 2000 samples each). With iid normal data and , the 5% rejection rate was 0.0545 at and 0.0525 at in case "c". Against a random walk the 5% power was 0.81 with and 0.62 with at , and 0.94 and 0.71 at . For a stationary AR(1) with and , the test wrongly rejected in 50% of samples with and 17% with .
Correctness
The correctness proof shows four facts. The residuals of line L1 sum to zero (and are orthogonal to in case "ct"), so and the partial sums are a bridge from 0 to 0. The Bartlett estimate of line L4 equals with set to 0 outside , so it is never negative, and lines L3 to L5 compute the stated . The statistic is invariant to (case "c") and to (case "ct"), for . For iid errors with variance in case "c", exactly, which matches the limit mean . 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 with residual partial sums that start and end at 0 (Lemma 1), that the Bartlett estimate is never negative (Lemma 2), that is invariant to the maps of Lemma 3, and that in case "c" with iid errors the numerator has mean (Lemma 4), whose scaled limit is the mean of for a Brownian bridge . We do not prove the limit law , the consistency of for , , or the divergence of 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", is the least squares residual on , and . In case "ct", with and , is the least squares residual on and , and . In both cases .
Proof. The columns and are orthogonal, since . The least squares fit on an orthogonal basis is the sum of the separate projections, which are and . The span of and equals the span of and . A least squares residual is orthogonal to every regressor, so , and in case "ct" also . Finally .
Lemma 2 (the Bartlett estimate is nonnegative). Extend by for and . For ,
Proof. Expand the square: . For fixed with , the inner sum runs over all for which both indices lie in , so it equals . The number of pairs in with is . So the sum is . Divide by .
The estimate is 0 only if every window sum is 0. The window that starts at contains only , so then , and by induction along the windows all . The implementation reports this case as an error. Without the Bartlett weights the estimate can be negative: for and , , while the Bartlett value is .
With Lemmas 1 and 2, lines L2 to L5 compute , the autocovariances, and , which is the statistic defined on the page.
Lemma 3 (invariance). Let . In case "c", the map leaves unchanged. In case "ct", so does .
Proof. The residual map is the linear projection onto the orthogonal complement of the regressors, so whenever lies in the regressor span (with in case "c"). So becomes , every becomes , every becomes , and and are both multiplied by . Their ratio is unchanged.
Lemma 4 (the mean of the numerator). In case "c", let with uncorrelated, mean 0 and variance . Then and
Proof. with . Since and , , and . Summing, . For the limit, and .
The same computation in case "ct" gives the limit mean , which is the trace of the covariance kernel stated on the page, and the sum of its eigenvalues.
Cited: the limit law and consistency. Under , with satisfying a functional central limit theorem with long-run variance , (MacNeill 1978 for polynomial regression residuals), and in probability when , . The continuous mapping theorem then gives . Under , is of exact order in probability, so for every fixed (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 or .
Complexity
On a real RAM, line L1 is one pass for the means and one for the slope, . Line L2 is one pass. Line L3 computes sums of at most products, . Lines L4 to L7 cost . The total is time, which is for the and rules, and extra space for . The autocovariances can also be computed for all lags at once by an FFT in .
Numerical stability. Compute from centered quantities ( and ), not from the raw normal equations, because and are both of order to and their difference loses digits. The partial sums are sums of numbers of both signs whose total is zero, so their relative error is small only if 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 , the test is the locally best invariant test of (Nyblom and Makelainen 1983).
- Invariant. 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 estimates the long-run variance consistently when and .
- A Cramer-von Mises statistic. In case "c", 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 can change by a factor of 2 or more between and , 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 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 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 with . Caner and Kilian (2001) show the same distortion for persistent stationary series. A larger helps the size, at the cost of power.
- Large bandwidth. With close to , 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.
# 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
- 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
- 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
- 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag AWK28P Edit this page History Report an error Markdown