Stationarity Testing: ADF and KPSS Tests for Reliable Time Series Analysis
If you’ve ever built a time series forecast (for sales, stock prices, energy demand, or any other metric) that performed great in testing but failed catastrophically in production, there’s a good chance you skipped a critical preprocessing step: verifying stationarity. Stationarity is the foundation of most popular time series models, from ARIMA to VAR, and failing to test for it leads to spurious correlations, inflated values, and wildly inaccurate predictions.
In this guide, we’ll break down the two most widely used stationarity tests: the Augmented Dickey-Fuller (ADF) unit root test and the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) stationarity test. We’ll explain how they work, when to use each, how to combine them for unambiguous results, and walk through a production-ready Python implementation.
By Tom Roberts · Editor, Quantopia
Published · Updated
Table of Contents#
- What is Stationarity, and Why Does It Matter?
- Augmented Dickey-Fuller (ADF) Test: A Deep Dive
- KPSS Test: A Complementary Stationarity Check
- Dual Testing Framework: Combine ADF and KPSS for Accurate Results
- Python Implementation: Test Stationarity Step-by-Step
- Best Practices & Common Pitfalls to Avoid
- Key Takeaways & Conclusion
- References
What is Stationarity, and Why Does It Matter? {#what-is-stationarity}#
A time series is stationary if its core statistical properties do not change over time. For almost all practical time series use cases, we rely on weak (covariance) stationarity, which requires three mathematical conditions to hold for all points in time :
- Constant Mean: The expected value of the series is constant over time:
- Constant Variance: The variance (volatility) of the series is finite and stays consistent across time:
- Constant Autocovariance: The covariance between the series at time and at a lagged time depends only on the lag length , not on the specific time :
Strict stationarity (where the full joint distribution of the series is invariant to time shifts) is rarely required or tested for real-world applications.
Why Stationarity Is Non-Negotiable#
- Avoid spurious regressions: Regressing two independent non-stationary series can produce artificially high values and statistically significant coefficients, leading to false conclusions about causal relationships. For example, regressing ice cream sales against drowning deaths over time might yield a strong correlation, but both are simply driven by seasonal temperature shifts (non-stationary mean) rather than any real causal link.
- Model prerequisite: Popular models including ARIMA, VAR, and mean-reversion trading algorithms assume stationarity to ensure stable parameter estimates and avoid unbounded forecast error.
- Predictability: Non-stationary series have permanent "memory" of shocks (e.g., a random walk stock price will never return to its pre-shock average), while stationary series revert to their mean after shocks, making long-term forecasting feasible.
Augmented Dickey-Fuller (ADF) Test: A Deep Dive {#adf-test}#
The ADF test is the most widely used unit root test, designed to detect the presence of a stochastic trend (unit root) that makes a series non-stationary.
Core Purpose#
A unit root exists if the coefficient on the lagged level of the series in an autoregressive model equals 1, meaning shocks to the series have permanent effects. The ADF test checks for this scenario by examining if the series can be modeled as non-stationary.
Mathematical Formulation#
The ADF test is based on the following regression model fitted via ordinary least squares (OLS):
Where:
- is the first difference of the series.
- represents a constant drift term.
- represents a deterministic time trend.
- is the test parameter of interest. This parameter is derived from the AR(1) model . Subtracting from both sides yields , where . If there is a unit root (), then . If the series is stationary (), then .
- represents lagged difference terms included to correct for serial correlation in the error term.
- is a white noise error term.
Hypotheses#
- Null Hypothesis (): (The series has a unit root, meaning it is non-stationary).
- Alternative Hypothesis (): (The series does not have a unit root, meaning it is stationary).
Interpretation#
The test statistic is the t-ratio for the estimated parameter :
This statistic is compared against critical values from the non-standard Dickey-Fuller distribution (rather than the standard Student's t-distribution).
- Decision Rule: Reject if the p-value is less than your chosen significance level (typically 0.05) or if the test statistic is more negative than the critical value. Rejecting the null means the series is stationary.
KPSS Test: A Complementary Stationarity Check {#kpss-test}#
The KPSS test is a stationarity test that flips the hypothesis structure of the ADF test, filling gaps where ADF has low power (e.g., for near-unit root series).
Core Difference from ADF#
While ADF tests for the presence of a unit root (null = non-stationary), KPSS tests for the absence of a unit root (null = stationary). This complementary structure helps eliminate ambiguous results when used together.
Mathematical Formulation#
The KPSS test assumes the time series can be decomposed into a deterministic trend, a random walk, and a stationary error:
Where:
- is a random walk component with innovation variance , where .
- is an optional deterministic time trend.
- is a stationary error term.
The series is stationary if the variance of the random walk innovations is zero (), meaning the random walk component collapses to a constant intercept .
Hypotheses#
- Null Hypothesis (): (The series is stationary around a constant mean or trend).
- Alternative Hypothesis (): (The series is non-stationary due to a unit root).
Interpretation#
The KPSS test statistic is a Lagrange Multiplier (LM) statistic based on the residuals from the regression of on a constant (for level stationarity) or a constant and time trend (for trend stationarity):
Where:
-
is the partial sum of residuals.
-
is the OLS residual from the regression.
-
is the estimator of the long-run variance of (usually computed using a kernel window like Newey-West to control for autocorrelation).
-
is the sample size.
-
Decision Rule: Reject if the LM statistic is larger than the critical value at your chosen significance level, or if the p-value is less than 0.05. Rejecting the null means the series is non-stationary.
Dual Testing Framework: Combine ADF and KPSS for Accurate Results {#dual-testing-framework}#
Using only one test often leads to misclassification: ADF has low power for near-unit roots, while KPSS can be biased by incorrect trend specifications. Using both tests together lets you distinguish between four clear outcomes:
| ADF Result | KPSS Result | Combined Interpretation | Recommended Action |
|---|---|---|---|
| Reject (Stationary) | Fail to Reject (Stationary) | Stationary: Series meets covariance stationarity requirements. | Model directly with ARIMA/VAR without differencing. |
| Fail to Reject (Non-Stationary) | Reject (Non-Stationary) | Non-Stationary: Series has a stochastic unit root. | Take first difference of the series and retest. |
| Reject (Stationary) | Reject (Non-Stationary) | Trend-Stationary: Series is stationary around a deterministic trend. | Detrend the series (regress on time and use residuals) instead of differencing. |
| Fail to Reject (Non-Stationary) | Fail to Reject (Stationary) | Ambiguous: Tests are inconclusive. | Increase sample size, check for structural breaks, or inspect ACF/PACF plots (slowly decaying ACF signals non-stationarity). |
Python Implementation: Test Stationarity Step-by-Step {#python-implementation}#
We use the statsmodels library’s built-in ADF and KPSS implementations to test two sample series: white noise (stationary) and a random walk (non-stationary).
Full Code#
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import adfuller, kpss
# Generate sample data
np.random.seed(42)
n_samples = 200
white_noise = np.random.normal(0, 1, n_samples) # Stationary
random_walk = np.cumsum(white_noise) # Non-stationary (has unit root)
def analyze_stationarity(timeseries, name):
print(f"\n==================== Analyzing: {name} ====================")
# Run ADF Test
adf_res = adfuller(timeseries, autolag='AIC') # Auto-select optimal lags via AIC
adf_stat, adf_pvalue, adf_usedlag, adf_nobs, adf_crit, adf_icbest = adf_res
print("Augmented Dickey-Fuller (ADF) Test:")
print(f" Test Statistic : {adf_stat:.4f}")
print(f" p-value : {adf_pvalue:.4f}")
print(f" Lags Used : {adf_usedlag}")
print(f" Critical Values:")
for key, val in adf_crit.items():
print(f" {key}: {val:.4f}")
adf_is_stationary = adf_pvalue < 0.05
print(f" ADF Conclusion : {'Stationary (Reject H0)' if adf_is_stationary else 'Non-Stationary (Fail to reject H0)'}")
# Run KPSS Test (testing for level stationarity; use regression='ct' for trend stationarity)
kpss_res = kpss(timeseries, regression='c', nlags='auto')
kpss_stat, kpss_pvalue, kpss_lags, kpss_crit = kpss_res
print("\nKwiatkowski-Phillips-Schmidt-Shin (KPSS) Test:")
print(f" Test Statistic : {kpss_stat:.4f}")
# Note: Statsmodels clips KPSS p-values to [0.01, 0.1]
print(f" p-value : {kpss_pvalue:.4f}")
print(f" Lags Used : {kpss_lags}")
print(f" Critical Values:")
for key, val in kpss_crit.items():
print(f" {key}: {val:.4f}")
kpss_is_stationary = kpss_pvalue >= 0.05
print(f" KPSS Conclusion: {'Stationary (Fail to reject H0)' if kpss_is_stationary else 'Non-Stationary (Reject H0)'}")
# Combined interpretation
if adf_is_stationary and kpss_is_stationary:
print("\nOverall Status: Stationary")
elif not adf_is_stationary and not kpss_is_stationary:
print("\nOverall Status: Non-Stationary (Stochastic Trend)")
elif adf_is_stationary and not kpss_is_stationary:
print("\nOverall Status: Trend-Stationary (Consider detrending)")
else:
print("\nOverall Status: Inconclusive (Check for breaks / increase sample size)")
# Run analysis on sample data
analyze_stationarity(white_noise, "White Noise (Stationary)")
analyze_stationarity(random_walk, "Random Walk (Non-Stationary)")Sample Output Excerpt#
For the white noise series, you will see:
ADF p-value: 0.0000 → Reject null (stationary)
KPSS p-value: 0.1000 → Fail to reject null (stationary)
Overall Status: StationaryFor the random walk series:
ADF p-value: 0.3072 → Fail to reject null (non-stationary)
KPSS p-value: 0.0100 → Reject null (non-stationary)
Overall Status: Non-Stationary (Stochastic Trend)Best Practices & Common Pitfalls to Avoid {#best-practices}#
1. Choose the Correct Regression Specification#
- For ADF: Use
regression='nc'(no constant/trend) if the series has zero mean and no trend,'c'(constant only) for series with a fixed mean, and'ct'(constant + trend) for series with a clear linear trend. Including unnecessary terms reduces test power, while omitting needed terms biases results toward non-rejection of the unit root. - For KPSS: Use
regression='c'for level stationarity,'ct'if your series has a visible upward/downward trend.
2. Account for Near-Unit Roots#
If your series is an AR(1) process with (technically stationary, but very persistent), ADF will often fail to reject the null of a unit root. KPSS will typically fail to reject stationarity in this case, highlighting the ambiguity.
3. Watch for Structural Breaks#
A sudden level shift or trend change (e.g., 2020 lockdowns shifting retail sales, a policy change altering energy demand) will bias ADF toward incorrectly concluding the series has a unit root, even if it is stationary before and after the break. Use the Zivot-Andrews test for series with known or suspected structural breaks.
4. Use Sufficient Sample Size#
Both tests have very low power for sample sizes observations. Avoid over-interpreting results for small datasets, and supplement with ACF/PACF visualizations.
Key Takeaways & Conclusion {#conclusion}#
Stationarity testing is a non-negotiable step for any time series analysis workflow, and relying on a single test can lead to costly errors in forecasting and inference:
- The ADF test checks for the presence of a unit root, with a null hypothesis of non-stationarity.
- The KPSS test checks for stationarity directly, with a null hypothesis of stationarity.
- Using both tests together eliminates ambiguity between stationary, non-stationary, trend-stationary, and inconclusive cases.
- Always align your test specification to your data’s characteristics (trend, mean, breaks) to avoid biased results.
By following the dual testing framework outlined in this guide, you will ensure your time series models have stable parameters, avoid spurious correlations, and produce reliable forecasts in production.
References {#references}#
- Statsmodels ADF Test Documentation
- Statsmodels KPSS Test Documentation
- Machine Learning Plus: KPSS Test for Stationarity
- Hamilton, J. D. (1994). Time Series Analysis. Princeton University Press.
- Towards Data Science: Complete Guide to Stationarity for Time Series