DTime series · ts.unitroot
Unit-root and stationarity tests
Does the series wander like a random walk (a unit root), or return to a mean or trend — and how many differences make it stationary?
Dickey–Fuller, augmented Dickey–Fuller, Phillips–Perron, DF-GLS (Elliott–Rothenberg–Stock), KPSS, Zivot–Andrews (one structural break) and Schmidt–Phillips — one at a time, or as a battery that reads the unit-root tests against KPSS and recommends how many differences (d) to take before modeling.
A real result
Example “Battery airpassengers”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Augmented Dickey–Fuller τ = 0.82, p = .992; Phillips–Perron Z(τ) = -1.84, p = .359; DF-GLS τ = 0.99, p = .915; KPSS η = 1.65, p ≤ 0.01
- Augmented Dickey–Fuller τ
- 0.8154
- p
- 0.9919
- Recommended d
- 2
Plots
View data
| month | passengers |
|---|---|
| −662,688,000,000 | 112 |
| −660,009,600,000 | 118 |
| −657,590,400,000 | 132 |
| −654,912,000,000 | 129 |
| −652,320,000,000 | 121 |
| −649,641,600,000 | 135 |
| −647,049,600,000 | 148 |
| −644,371,200,000 | 148 |
| −641,692,800,000 | 136 |
| −639,100,800,000 | 119 |
| −636,422,400,000 | 104 |
| −633,830,400,000 | 118 |
| −631,152,000,000 | 115 |
| −628,473,600,000 | 126 |
| −626,054,400,000 | 141 |
| −623,376,000,000 | 135 |
| −620,784,000,000 | 125 |
| −618,105,600,000 | 149 |
| −615,513,600,000 | 170 |
| −612,835,200,000 | 170 |
| −610,156,800,000 | 158 |
| −607,564,800,000 | 133 |
| −604,886,400,000 | 114 |
| −602,294,400,000 | 140 |
| −599,616,000,000 | 145 |
| −596,937,600,000 | 150 |
| −594,518,400,000 | 178 |
| −591,840,000,000 | 163 |
| −589,248,000,000 | 172 |
| −586,569,600,000 | 178 |
| −583,977,600,000 | 199 |
| −581,299,200,000 | 199 |
| −578,620,800,000 | 184 |
| −576,028,800,000 | 162 |
| −573,350,400,000 | 146 |
| −570,758,400,000 | 166 |
| −568,080,000,000 | 171 |
| −565,401,600,000 | 180 |
| −562,896,000,000 | 193 |
| −560,217,600,000 | 181 |
| −557,625,600,000 | 183 |
| −554,947,200,000 | 218 |
| −552,355,200,000 | 230 |
| −549,676,800,000 | 242 |
| −546,998,400,000 | 209 |
| −544,406,400,000 | 191 |
| −541,728,000,000 | 172 |
| −539,136,000,000 | 194 |
| −536,457,600,000 | 196 |
| −533,779,200,000 | 196 |
| −531,360,000,000 | 236 |
| −528,681,600,000 | 235 |
| −526,089,600,000 | 229 |
| −523,411,200,000 | 243 |
| −520,819,200,000 | 264 |
| −518,140,800,000 | 272 |
| −515,462,400,000 | 237 |
| −512,870,400,000 | 211 |
| −510,192,000,000 | 180 |
| −507,600,000,000 | 201 |
First 60 of 144 rows.
View data
| passengers |
|---|
| 112 |
| 118 |
| 132 |
| 129 |
| 121 |
| 135 |
| 148 |
| 148 |
| 136 |
| 119 |
| 104 |
| 118 |
| 115 |
| 126 |
| 141 |
| 135 |
| 125 |
| 149 |
| 170 |
| 170 |
| 158 |
| 133 |
| 114 |
| 140 |
| 145 |
| 150 |
| 178 |
| 163 |
| 172 |
| 178 |
| 199 |
| 199 |
| 184 |
| 162 |
| 146 |
| 166 |
| 171 |
| 180 |
| 193 |
| 181 |
| 183 |
| 218 |
| 230 |
| 242 |
| 209 |
| 191 |
| 172 |
| 194 |
| 196 |
| 196 |
| 236 |
| 235 |
| 229 |
| 243 |
| 264 |
| 272 |
| 237 |
| 211 |
| 180 |
| 201 |
First 60 of 144 rows.
Tests
| Test | H₀ | Statistic | p | Lags / bandwidth | 5 % critical value | At α = .05 | |
|---|---|---|---|---|---|---|---|
| Augmented Dickey–Fuller τ | unit root | 0.8154 | .992 | 13 | −2.884 | unit root not rejected | |
| Phillips–Perron Z(τ) | unit root | −1.844 | .359 | 4 | −2.882 | unit root not rejected | |
| DF-GLS τ | unit root | 0.9918 | .915 | 13 | −1.943 | unit root not rejected | |
| KPSS η | stationary | 1.651 | .010 | ≤ | 8 | 0.4630 | reject stationarity |
- Unit-root tests have low power near a unit root: read them with KPSS (the battery does) and a plot of the series.
- p-values come from nonstandard distributions (MacKinnon response surfaces, KPSS / ERS / Zivot–Andrews tables); a p shown at a table bound (≤ .01 or ≥ .10) means the statistic is beyond the tabulated range.
Augmented Dickey–Fuller τ = 0.82, p = .992; Phillips–Perron Z(τ) = -1.84, p = .359; DF-GLS τ = 0.99, p = .915; KPSS η = 1.65, p ≤ 0.01
- Augmented Dickey–Fuller τ
- 0.8154
- p
- 0.9919
- Recommended d
- 2
To keep this page light, the plots are shown once, under the R tab.
Tests
| Test | H₀ | Statistic | p | Lags / bandwidth | 5 % critical value | At α = .05 | |
|---|---|---|---|---|---|---|---|
| Augmented Dickey–Fuller τ | unit root | 0.8154 | .992 | 13 | −2.884 | unit root not rejected | |
| Phillips–Perron Z(τ) | unit root | −1.844 | .359 | 4 | −2.882 | unit root not rejected | |
| DF-GLS τ | unit root | 0.9918 | .915 | 13 | −1.943 | unit root not rejected | |
| KPSS η | stationary | 1.651 | .010 | ≤ | 8 | 0.4630 | reject stationarity |
- Unit-root tests have low power near a unit root: read them with KPSS (the battery does) and a plot of the series.
- p-values come from nonstandard distributions (MacKinnon response surfaces, KPSS / ERS / Zivot–Andrews tables); a p shown at a table bound (≤ .01 or ≥ .10) means the statistic is beyond the tabulated range.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Battery airpassengersml_airpassengers · time: month · value: passengers
- Df random walkts_truth · time: month · value: random_walk
- Recommend d fixed lagsml_airpassengers · time: month · value: passengers
- Adf ar1ts_truth · time: month · value: ar1
- Adf trend t rulets_truth · time: month · value: trend_stationary
- Pp lakehuronts_lakehuron · time: year · value: level
- Dfgls co2 trendts_co2 · time: month · value: co2
- Kpss nileml_nile · time: year · value: flow
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Seriesnumeric · 1 column
- The values over time.
- Timetemporal / numeric · 0–1 column
- Orders the rows (omit to use the row order). The tests assume one observation per evenly spaced time.
Choices you make
hypothesis
- Testdefault battery
Unit-root tests have H₀ = a unit root; KPSS reverses it (H₀ = stationary). Reading both protects against low power.
- Battery (ADF, PP, DF-GLS, KPSS) + recommended d(default) — Runs the four standard tests and the smallest number of differences at which ADF rejects and KPSS does not.
- Augmented Dickey–Fuller — Lagged differences absorb serial correlation; lags chosen by the rule below.
- Dickey–Fuller (no lags) — The original test: valid only when the errors are not autocorrelated.
- Phillips–Perron — Corrects the Dickey–Fuller t non-parametrically (Bartlett long-run variance) instead of adding lags.
- DF-GLS (Elliott–Rothenberg–Stock) — GLS-detrends first: more power than ADF when the series is close to a unit root.
- Zivot–Andrews (one break) — Allows one unknown break in level and/or trend under the alternative; reports the break date.
- Schmidt–Phillips (LM) — Lagrange-multiplier test with a linear trend; p from simulation on the shared random stream.
- KPSS — Tests stationarity around a level or trend; a small p means a unit root (or a break).
- Deterministic termsdefault c
What the series is stationary around under the alternative. Use a trend when the series drifts upward or downward.
- Constant (a level)(default) — Tests stationarity around a level; pick it when the series doesn't trend.
- Constant and linear trend — Tests stationarity around a straight-line trend; pick it when the series drifts up or down.
- None (mean zero) — Only for ADF, DF and PP; the others use a constant.
options
- Lag selectiondefault aic
ADF, DF-GLS and Zivot–Andrews: choose the augmenting lags by information criterion (up to 12(n/100)^¼) or a sequential t-test.
- AIC(default) — Chooses the lag count by AIC; tends to keep more lags, a safe default.
- BIC — Chooses the lag count by BIC; tends to keep fewer lags, which suits short series.
- General-to-specific t (|t| ≥ 1.645) — Starts long and drops the last lag until it's significant; helps keep the test's size near nominal.
- Fixed lagsdefault —
Overrides the lag rule for ADF, DF-GLS and Zivot–Andrews.
- Long-run variance bandwidthdefault auto
Bartlett lags for Phillips–Perron, KPSS and Schmidt–Phillips: short ⌊4(n/100)^¼⌋, long ⌊12(n/100)^¼⌋; automatic = Hobijn et al. for KPSS, short otherwise.
- Automatic(default) — Uses Hobijn et al.'s data-driven lags for KPSS and the short window for the other tests; the usual choice.
- Short — Uses fewer Bartlett lags; fine when autocorrelation is weak, and the tests keep more power.
- Long — Uses more Bartlett lags; safer when autocorrelation is strong, at some cost in power.
- Break indefault c
Where Zivot–Andrews allows a single break: in the level, the trend, or both.
- Level (intercept)(default) — Allows one break in the level; pick it for a sudden jump.
- Trend (slope) — Allows one break in the slope; pick it when growth changes.
- Level and trend — Allows a break in both; pick it when unsure, at some cost in power.
- Trimmingdefault 0.15
Share of observations at each end excluded as break dates.
- Simulationsdefault 999
Random walks simulated to calibrate the Schmidt–Phillips p-value.
What it reports
- n_obs
- How many independent units the analysis used; it sets precision and power.
- stat
- A single number that summarizes how far your data are from what H₀ predicts.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- lags
- Tests H₀ "the series has a unit root"; a small p-value supports stationarity.
- crit_1
- The value a statistic must pass for the test to reject at the chosen significance level.
- crit_5
- The value a statistic must pass for the test to reject at the chosen significance level.
- crit_10
- The value a statistic must pass for the test to reject at the chosen significance level.
- reject
- A p-value below the chosen α; it says the data are hard to explain by chance alone, not that the effect matters.
- d_recommended
- Replacing values with period-to-period changes to remove trends (or seasonal differences for seasonality).
Per group, level or term: test, test_label, break_index, adf_stat, adf_p, adf_lags, pp_stat, pp_p, dfgls_stat, dfgls_p, kpss_stat, kpss_p, reps
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same twin (codesplash.stats.ts ↔ cs_ts_*) with MacKinnon (1994/2010), KPSS, ERS and Zivot–Andrews tables generated into both packages from one source; Schmidt–Phillips p-values use the shared Wichmann–Hill stream.
- Phillips–Perron follows Phillips & Perron (1988) with y_{t−1} in the correction term; urca::ur.pp uses y_t there, so its Z(τ) differs in the third decimal.
- Schmidt–Phillips uses ω² = σ²_ε/σ² from the test regression's residuals (Schmidt & Phillips 1992); urca::ur.sp computes the ratio differently and reports a different value.
The exact script CodeSplash ran for example “Battery airpassengers” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Unit-root and stationarity tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.unitroot 1.1.1 · spec 7c26bc63d52c4e27
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", columns=["passengers", "month"])
n_input = len(df)
df = df.dropna(subset=["passengers", "month"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["passengers", "month"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "passengers"
TIME = "month"
TEMPORAL = True
TEST = "battery"
DET = "c"
LAG_RULE = "aic"
LAGS = None
BW = "auto"
ZA_MODEL = "c"
TRIM = 0.15
REPS = 999
SEED = 42
s = ts.ordered(df, VALUE, TIME, TEMPORAL)
x, labels = s["x"], s["labels"]
n = len(x)
if s["dups"]:
warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
det = DET
if DET == "n" and TEST not in ("adf", "df", "pp"):
det = "c"
warnings.append("No deterministic terms is only defined for ADF, DF and PP; a constant was used.")
det_kpss = "ct" if det == "ct" else "c"
# The test regressions need at least 2 × (deterministic terms + 1) observations (as statsmodels' adfuller), and
# never fewer than 4, and a series that varies (registry/errors.yaml; the same checks in R).
cs.check_rows(n, max(4, 2 * ({"n": 0, "c": 1, "ct": 2}[det] + 1)), "A unit-root test")
check_not_constant(x, VALUE)
bw_kpss = "auto" if BW == "auto" else BW
bw = "short" if BW == "auto" else BW
LABELS = {"adf": "Augmented Dickey–Fuller τ", "df": "Dickey–Fuller τ", "pp": "Phillips–Perron Z(τ)", "dfgls": "DF-GLS τ",
"za": "Zivot–Andrews t", "sp": "Schmidt–Phillips Z(τ)", "kpss": "KPSS η", "battery": "Battery"}
def pf(r):
"""p as text, with the table bound when the statistic is beyond the tabulated range."""
b = r.get("bound") or ""
return f"p {b} {r['p']:.2f}" if b else cs.fmt_p(r["p"])
def run(test):
if test == "adf":
return ts.adf(x, det, lags=LAGS, autolag=LAG_RULE)
if test == "df":
return ts.adf(x, det, lags=0)
if test == "pp":
return ts.pp(x, det, bw)
if test == "dfgls":
return ts.dfgls(x, det_kpss, lags=LAGS, autolag=LAG_RULE)
if test == "za":
return ts.zivot_andrews(x, ZA_MODEL, TRIM, lags=LAGS, autolag=LAG_RULE)
if test == "sp":
return ts.schmidt_phillips(x, bw, REPS, SEED)
return ts.kpss(x, det_kpss, bw_kpss)
# %% Tests
rows, values = [], {"n_obs": n, "test": TEST, "test_label": LABELS[TEST]}
battery = ["adf", "pp", "dfgls", "kpss"] if TEST == "battery" else [TEST]
res = {}
for t in battery:
r = run(t)
res[t] = r
crit = r.get("crit") or [None, None, None]
if t == "kpss":
crit = [crit[3], crit[1], crit[0]] # 1 %, 5 %, 10 %
reject = (r["p"] < 0.05)
rows.append({"test": LABELS[t], "h0": "stationary" if t == "kpss" else "unit root", "statistic": r["stat"], "p": r["p"],
"p_note": r.get("bound") or "", "lags": r.get("lags"), "crit_5": crit[1],
"verdict": ("reject stationarity" if reject else "stationary") if t == "kpss" else ("reject the unit root" if reject else "unit root not rejected")})
main = res[battery[0]]
crit = main.get("crit") or [None, None, None]
if battery[0] == "kpss":
crit = [crit[3], crit[1], crit[0]]
values.update({"stat": main["stat"], "p": main["p"], "lags": main.get("lags"), "crit_1": crit[0], "crit_5": crit[1], "crit_10": crit[2],
"reject": int(main["p"] < 0.05)})
if TEST == "battery":
for t in battery:
values[f"{t}_stat"] = res[t]["stat"]
values[f"{t}_p"] = res[t]["p"]
values["adf_lags"] = res["adf"]["lags"]
if TEST == "za":
values["break_index"] = main["break_index"]
if TEST == "sp":
values["reps"] = REPS
rd = ts.recommend_d(x, "ct" if det == "ct" else "c", lags=LAGS, autolag=LAG_RULE, bandwidth=bw_kpss, detail=True) # same lag settings as the tests
values["d_recommended"] = rd["d"]
if not rd["agreed"]:
warnings.append(f"ADF and KPSS never agreed on stationarity up to d = {rd['d']}; the recommended d is a convention, not a finding.")
# %% Result
if TEST == "battery":
summary = (f"Unit-root battery for {VALUE} ({n} observations): ADF τ = {res['adf']['stat']:.2f} ({pf(res['adf'])}), "
f"KPSS = {res['kpss']['stat']:.3f} ({pf(res['kpss'])}); recommended differences d = {values['d_recommended']}.")
else:
summary = f"{LABELS[TEST]} for {VALUE}: {main['stat']:.3f}, {pf(main)} — {rows[0]['verdict']}."
if TEST == "za":
summary += f" Most likely break after {labels[main['break_index']]}."
notes = ["Unit-root tests have low power near a unit root: read them with KPSS (the battery does) and a plot of the series.",
"p-values come from nonstandard distributions (MacKinnon response surfaces, KPSS / ERS / Zivot–Andrews tables); "
"a p shown at a table bound (≤ .01 or ≥ .10) means the statistic is beyond the tabulated range."]
if TEST == "sp":
notes.append(f"Schmidt–Phillips p from {REPS} simulated random walks (seed {SEED}; identical in Python and R).")
kind = "temporal" if TEMPORAL else "numeric"
charts = [cs.chart("series", "series-line", f"{VALUE} over time", {"x": cs.col(TIME or "index", labels, kind=kind), "y": cs.col(VALUE, x)},
controls={"marker": main["break_index"] + 1} if TEST == "za" else None),
cs.chart("acf", "acf", f"Autocorrelation of {VALUE}", {"y": cs.col(VALUE, x)})]
cs.publish({
"method": "ts.unitroot",
"methodVersion": "1.1.1",
"title": "Unit-root and stationarity tests",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": "; ".join(f"{LABELS[t]} = {res[t]['stat']:.2f}, {pf(res[t])}" for t in battery),
"statistics": [{"key": "stat", "label": LABELS[battery[0]], "value": main["stat"]}, {"key": "p", "label": "p", "value": main["p"]},
{"key": "d", "label": "Recommended d", "value": values["d_recommended"]}],
"tables": [{
"key": "tests", "title": "Tests",
"columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "h0", "label": "H₀", "type": "string"},
{"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_note", "label": "", "type": "string"}, {"key": "lags", "label": "Lags / bandwidth", "type": "integer"},
{"key": "crit_5", "label": "5 % critical value", "type": "number"}, {"key": "verdict", "label": "At α = .05", "type": "string"}],
"rows": rows,
}],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Battery airpassengers” · R version 4.5.1 (2025-06-13)
# Unit-root and stationarity tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.unitroot 1.1.1 · spec 7c26bc63d52c4e27
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", col_select = c("passengers", "month")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("passengers", "month")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("passengers", "month")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "passengers"
TIME <- "month"
TEMPORAL <- TRUE
TEST <- "battery"
DET <- "c"
LAG_RULE <- "aic"
LAGS <- NULL
BW <- "auto"
ZA_MODEL <- "c"
TRIM <- 0.15
REPS <- 999
SEED <- 42
s <- cs_ts_ordered(df, VALUE, TIME, TEMPORAL)
x <- s$x
labels <- s$labels
n <- length(x)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the tests assume one observation per evenly spaced time.", s$dups))
det <- DET
if (DET == "n" && !(TEST %in% c("adf", "df", "pp"))) {
det <- "c"
warnings <- c(warnings, "No deterministic terms is only defined for ADF, DF and PP; a constant was used.")
}
det_kpss <- if (det == "ct") "ct" else "c"
# The test regressions need at least 2 x (deterministic terms + 1) observations (as statsmodels' adfuller), and
# never fewer than 4, and a series that varies (registry/errors.yaml; the same checks in Python).
cs_check_rows(n, max(4, 2 * (c(n = 0, c = 1, ct = 2)[[det]] + 1)), "A unit-root test")
cs_check_not_constant(x, VALUE)
bw_kpss <- BW
bw <- if (BW == "auto") "short" else BW
LABELS <- list(adf = "Augmented Dickey–Fuller τ", df = "Dickey–Fuller τ", pp = "Phillips–Perron Z(τ)", dfgls = "DF-GLS τ",
za = "Zivot–Andrews t", sp = "Schmidt–Phillips Z(τ)", kpss = "KPSS η", battery = "Battery")
pf <- function(r) if (!is.null(r$bound) && nzchar(r$bound)) sprintf("p %s %.2f", r$bound, r$p) else cs_fmt_p(r$p)
run_test <- function(test) {
switch(test,
adf = cs_ts_adf(x, det, lags = LAGS, autolag = LAG_RULE),
df = cs_ts_adf(x, det, lags = 0),
pp = cs_ts_pp(x, det, bw),
dfgls = cs_ts_dfgls(x, det_kpss, lags = LAGS, autolag = LAG_RULE),
za = cs_ts_zivot_andrews(x, ZA_MODEL, TRIM, lags = LAGS, autolag = LAG_RULE),
sp = cs_ts_schmidt_phillips(x, bw, REPS, SEED),
cs_ts_kpss(x, det_kpss, bw_kpss))
}
# %% Tests
rows <- list()
values <- list(n_obs = n, test = TEST, test_label = LABELS[[TEST]])
battery <- if (TEST == "battery") c("adf", "pp", "dfgls", "kpss") else TEST
res <- list()
for (t in battery) {
r <- run_test(t)
res[[t]] <- r
crit <- if (is.null(r$crit)) list(NULL, NULL, NULL) else as.list(r$crit)
if (t == "kpss") crit <- list(r$crit[4], r$crit[2], r$crit[1])
reject <- r$p < 0.05
verdict <- if (t == "kpss") (if (reject) "reject stationarity" else "stationary") else (if (reject) "reject the unit root" else "unit root not rejected")
rows[[length(rows) + 1]] <- list(test = LABELS[[t]], h0 = if (t == "kpss") "stationary" else "unit root", statistic = r$stat, p = r$p,
p_note = if (is.null(r$bound)) "" else r$bound, lags = r$lags, crit_5 = crit[[2]], verdict = verdict)
}
main <- res[[battery[1]]]
crit <- if (is.null(main$crit)) list(NULL, NULL, NULL) else as.list(main$crit)
if (battery[1] == "kpss") crit <- list(main$crit[4], main$crit[2], main$crit[1])
values["stat"] <- list(main$stat)
values["p"] <- list(main$p)
values["lags"] <- list(main$lags)
values["crit_1"] <- list(crit[[1]])
values["crit_5"] <- list(crit[[2]])
values["crit_10"] <- list(crit[[3]])
values$reject <- as.integer(main$p < 0.05)
if (TEST == "battery") {
for (t in battery) {
values[[paste0(t, "_stat")]] <- res[[t]]$stat
values[[paste0(t, "_p")]] <- res[[t]]$p
}
values$adf_lags <- res$adf$lags
}
if (TEST == "za") values$break_index <- main$break_index
if (TEST == "sp") values$reps <- REPS
rd <- cs_ts_recommend_d(x, if (det == "ct") "ct" else "c", lags = LAGS, autolag = LAG_RULE, bandwidth = bw_kpss, detail = TRUE) # same lag settings as the tests
values$d_recommended <- rd$d
if (!rd$agreed) warnings <- c(warnings, sprintf("ADF and KPSS never agreed on stationarity up to d = %d; the recommended d is a convention, not a finding.", rd$d))
# %% Result
summary <- if (TEST == "battery") {
sprintf("Unit-root battery for %s (%d observations): ADF τ = %.2f (%s), KPSS = %.3f (%s); recommended differences d = %d.",
VALUE, n, res$adf$stat, pf(res$adf), res$kpss$stat, pf(res$kpss), values$d_recommended)
} else {
sprintf("%s for %s: %.3f, %s — %s.", LABELS[[TEST]], VALUE, main$stat, pf(main), rows[[1]]$verdict)
}
if (TEST == "za") summary <- paste0(summary, sprintf(" Most likely break after %s.", labels[main$break_index + 1]))
notes <- list("Unit-root tests have low power near a unit root: read them with KPSS (the battery does) and a plot of the series.",
"p-values come from nonstandard distributions (MacKinnon response surfaces, KPSS / ERS / Zivot–Andrews tables); a p shown at a table bound (≤ .01 or ≥ .10) means the statistic is beyond the tabulated range.")
if (TEST == "sp") notes <- c(notes, sprintf("Schmidt–Phillips p from %d simulated random walks (seed %d; identical in Python and R).", REPS, SEED))
kind <- if (TEMPORAL) "temporal" else "numeric"
charts <- list(
cs_chart("series", "series-line", sprintf("%s over time", VALUE), list(x = cs_col(if (is.null(TIME)) "index" else TIME, labels, kind = kind), y = cs_col(VALUE, x)),
controls = if (TEST == "za") list(marker = main$break_index + 1) else NULL),
cs_chart("acf", "acf", sprintf("Autocorrelation of %s", VALUE), list(y = cs_col(VALUE, x))))
cs_publish(list(
method = "ts.unitroot",
methodVersion = "1.1.1",
title = "Unit-root and stationarity tests",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = paste(vapply(battery, function(t) sprintf("%s = %.2f, %s", LABELS[[t]], res[[t]]$stat, pf(res[[t]])), ""), collapse = "; "),
statistics = list(list(key = "stat", label = LABELS[[battery[1]]], value = main$stat), list(key = "p", label = "p", value = main$p),
list(key = "d", label = "Recommended d", value = values$d_recommended)),
tables = list(list(
key = "tests", title = "Tests",
columns = list(list(key = "test", label = "Test", type = "string"), list(key = "h0", label = "H₀", type = "string"),
list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_note", label = "", type = "string"), list(key = "lags", label = "Lags / bandwidth", type = "integer"),
list(key = "crit_5", label = "5 % critical value", type = "number"), list(key = "verdict", label = "At α = .05", type = "string")),
rows = rows
)),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Sources
- Dickey, D. A., & Fuller, W. A. (1979). Distribution of the estimators for autoregressive time series with a unit root. JASA, 74, 427–431.
- Said, S. E., & Dickey, D. A. (1984). Testing for unit roots in autoregressive-moving average models of unknown order. Biometrika, 71, 599–607.
- Phillips, P. C. B., & Perron, P. (1988). Testing for a unit root in time series regression. Biometrika, 75, 335–346.
- Elliott, G., Rothenberg, T. J., & Stock, J. H. (1996). Efficient tests for an autoregressive unit root. Econometrica, 64, 813–836.
- Kwiatkowski, D., Phillips, P. C. B., Schmidt, P., & Shin, Y. (1992). Testing the null hypothesis of stationarity against the alternative of a unit root. J. Econometrics, 54, 159–178.
- Zivot, E., & Andrews, D. W. K. (1992). Further evidence on the great crash, the oil-price shock, and the unit-root hypothesis. JBES, 10, 251–270.
- Schmidt, P., & Phillips, P. C. B. (1992). LM tests for a unit root in the presence of deterministic trends. Oxford Bulletin of Economics and Statistics, 54, 257–287.
- MacKinnon, J. G. (1994). Approximate asymptotic distribution functions for unit-root and cointegration tests. JBES, 12, 167–176; (2010) Critical values for cointegration tests, Queen's WP 1227.
- Hobijn, B., Franses, P. H., & Ooms, M. (1998). Generalisations of the KPSS-test for stationarity. Econometric Institute Report 9802.
From the CodeSplash method registry · ts.unitroot v1.1.1.