Lesson 4.1Module 4: Testing a time series45 minIntermediate
Testing for stationarity: the ADF and KPSS tests
Two tests that ask opposite questions: does this series have a unit root, or is it stationary? Run both on simulated data and on 71 years of loudness, and find out why a test that can't decide is still telling you something.
Lesson 3.3 ended with an open question. Since 1950, average loudness has climbed by about a tenth of a decibel a year. Is that a trend-stationary series, one that always returns to a rising trend line and should be detrended? Or is it a random walk with drift, one that never returns and should be differenced? Looking at the chart can't settle it. This lesson introduces the two standard tests, runs them on simulated data where we know the answer, and then puts the loudness question to them. The answer turns out to be more interesting than a yes or a no.
Set up
You need statsmodels (lesson 3.1) and data_by_year.csv from lesson 2.1.
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import adfuller, kpss
from statsmodels.tools.sm_exceptions import InterpolationWarning
warnings.simplefilter("ignore", InterpolationWarning) # explained in the KPSS section
warnings.simplefilter("ignore", FutureWarning) # statsmodels notices about its next versionWhat a test is actually testing
Every hypothesis test starts from a null hypothesis, a default claim it assumes is true until the data says otherwise. The test then asks: if the null were true, how surprising would this data be? That surprise is measured by the p-value. A small p-value (the usual cut-off is 0.05) means the data would be very surprising under the null, so we reject it. A large p-value means the data is compatible with the null, so we fail to reject it.
That last phrase matters. Failing to reject is not the same as proving the null true. A test with too little data fails to reject almost everything. Keep that in mind: it will be the main point by the end of this lesson.
The unit root
Here is a simple way to write a series with memory. Each value is a fraction of the last value, plus a new random shock:
value today = φ × value yesterday + shock
The number φ (the Greek letter phi) controls everything:
- If φ is less than 1, the series is pulled back towards its average: a shock fades away, faster when φ is small. That's stationary.
- If φ equals 1, nothing pulls it back. Every shock stays in the series forever. That's a random walk.
A series with φ = 1 is said to have a unit root ("unit" because φ is one). So the question "random walk or not?" becomes "is φ equal to 1, or smaller?"
The Dickey–Fuller test
David Dickey and Wayne Fuller (1979) turned that question into a regression. Subtract yesterday's value from both sides of the equation above, and you get:
change today = (φ − 1) × value yesterday + shock
So regress each change on the previous value. If the slope (φ − 1) is zero, there's a unit root. If it's clearly negative, the series is pulled back: no unit root. For a series with a trend, the regression also includes a constant and a time trend, so the test asks whether the series returns to a trend line, not to a flat average.
The augmented Dickey–Fuller test (ADF) adds a few past changes to the regression, to soak up any short-term memory in the changes themselves. How many past changes to include is called the number of lags. Remember that choice: it comes back.
The null hypothesis of the ADF test is: there is a unit root. A small p-value rejects it, which is evidence that the series is stationary (around its trend, if you included one).
Why the test needs its own table
The ADF test produces a t-statistic, like any regression slope. You may have learned that a t-statistic below about −1.645 is significant at 5% in a one-sided test. That rule is wrong here, and seeing why is the main thing Dickey and Fuller discovered. Let's simulate 2,000 random walks the length of our loudness data (71 years), so the null hypothesis is true by construction, and look at the statistics the test produces:
rng = np.random.default_rng(0)
n = 71
null_stats = np.array([
adfuller(np.cumsum(rng.normal(size=n)), regression="ct", maxlag=0, autolag=None)[0]
for _ in range(2000)
])
cutoff = np.percentile(null_stats, 5)
print(f"5% cut-off for random walks: {cutoff:.2f} (the usual normal-table value is -1.645)")
grid = np.linspace(-6, 4, 300)
fig, ax = plt.subplots(figsize=(10, 3.6))
ax.hist(null_stats, bins=50, density=True, alpha=0.7, label="ADF statistic, 2,000 random walks")
ax.plot(grid, np.exp(-grid**2 / 2) / np.sqrt(2 * np.pi), color="C3", linewidth=2, label="Normal distribution")
ax.axvline(cutoff, color="C0", linestyle="--", label=f"Correct 5% cut-off ({cutoff:.2f})")
ax.axvline(-1.645, color="C3", linestyle="--", label="Normal-table cut-off (-1.645)")
ax.set_xlabel("Test statistic")
ax.set_title("When there is a unit root, the statistic is pushed well to the left of the normal curve")
ax.legend(fontsize=8, loc="upper right")
plt.show()Even when the null is true, the statistics sit far to the left of the normal curve. If you used −1.645 as your cut-off, you would "find" stationarity in most random walks. The right 5% cut-off is about −3.5. You don't need to simulate it every time: adfuller knows the correct table, and its p-values already account for it.
The KPSS test: the opposite question
The ADF test's default is "unit root", so it needs strong evidence to conclude "stationary". The KPSS test, named after the four economists who proposed it in 1992 (Kwiatkowski, Phillips, Schmidt and Shin), turns that around. Its null hypothesis is: the series is stationary (around a level, or around a trend). A small p-value rejects stationarity.
Using both tests together gives four possible outcomes:
- ADF rejects, KPSS doesn't: both point to stationary. A clear answer.
- ADF doesn't reject, KPSS rejects: both point to a unit root. A clear answer.
- Both reject: the tests contradict each other. Often a sign that something else is going on, such as a sudden break in the series.
- Neither rejects: the data isn't informative enough to tell the two apart.
One practical note: statsmodels looks up KPSS p-values in a short table that only runs from 0.01 to 0.10. A p-value outside that range is reported as exactly 0.01 or 0.10, with a warning (that's the InterpolationWarning we silenced). So read a KPSS p-value of 0.10 as "0.10 or more".
Back to loudness
Now the real question. We'll use 1950 onwards, the reliable part of the data (lesson 3.3):
loud = pd.read_csv("data_by_year.csv", index_col="year")["loudness"].loc[1950:]
slope, intercept = np.polyfit(loud.index, loud.values, 1)
trend_line = intercept + slope * loud.index
fig, ax = plt.subplots(figsize=(10, 3.4))
ax.plot(loud.index, loud.values, linewidth=1.5, label="Average loudness")
ax.plot(loud.index, trend_line, color="C2", linestyle="--", linewidth=2, label=f"Straight-line trend (+{slope:.2f} dB a year)")
ax.set_ylabel("Loudness (dB)")
ax.set_title("Loudness since 1950: does it keep returning to the line?")
ax.legend(fontsize=8, loc="upper left")
plt.show()
print("Levels: ", test_both(loud, "ct"))
print("Differences:", test_both(loud.diff().dropna(), "c"))On the levels, the ADF test rejects a unit root (p = 0.006) and the KPSS test doesn't reject trend-stationarity. Both say trend-stationary. The differences look stationary to both tests too, which we'd expect either way: differencing a trend-stationary series gives a stationary (over-differenced) series as well.
So is the case closed? Look at the chart again. The series doesn't hug its trend line. It sits above it from the late 1960s to the early 1980s, below it until the mid-1990s, then above it again through the 2000s: swings lasting 10 to 15 years. A series that returns to its trend that slowly sits close to the border between the two kinds. Before trusting the verdict, let's check how fragile it is.
How many lags?
autolag="AIC" let statsmodels choose the number of lags by trying each number up to a maximum and keeping the one with the best AIC, a score that balances how well a regression fits against how many terms it uses. Here it chose 12, the largest number it was allowed to try. What does the test say with other choices?
lags = range(13)
pvals = [adfuller(loud, regression="ct", maxlag=k, autolag=None)[1] for k in lags]
fig, ax = plt.subplots(figsize=(10, 3.2))
ax.bar(lags, pvals, color=["C1" if p < 0.05 else "C0" for p in pvals])
ax.axhline(0.05, color="grey", linestyle="--", linewidth=1)
ax.set_xlabel("Number of lags in the ADF regression")
ax.set_ylabel("p-value")
ax.set_title("The ADF verdict on loudness depends on the number of lags")
plt.show()
for rule in ["AIC", "BIC"]:
res = adfuller(loud, regression="ct", autolag=rule)
print(f"{rule} picks {res[2]} lags: p = {res[1]:.3f}")With 0 to 10 lags, the test can't reject a unit root. Only with 11 or 12 does it reject. BIC, a stricter score that penalises extra terms more heavily, picks 0 lags and gets p = 0.11. Each lag also costs a year of data at the start of the regression, so the 12-lag version is fitted to only 58 years.
There is no single correct number of lags, which is why careful analysts report how sensitive their result is rather than one p-value. Here the honest summary is: the ADF test rejects a unit root only under one particular choice. On its own, that isn't strong evidence.
Why the tests struggle: power
A test's power is how often it rejects the null when the null is false: how good it is at spotting the truth. Let's measure the ADF test's power in a situation like ours: 71 years, a trend, and a series that returns to its trend slowly (φ = 0.9, so each year keeps 90% of the previous year's deviation):
rng = np.random.default_rng(1)
def slow_return(n, phi=0.9, burn=50):
shocks = rng.normal(size=n + burn)
x = np.zeros(n + burn)
for i in range(1, n + burn):
x[i] = phi * x[i - 1] + shocks[i]
return x[burn:] + 0.1 * np.arange(n) # stationary around a rising trend
alt_stats = np.array([
adfuller(slow_return(n), regression="ct", maxlag=0, autolag=None)[0] for _ in range(2000)
])
print(f"Share of trend-stationary series where ADF rejects a unit root: {(alt_stats < cutoff).mean():.0%}")
fig, ax = plt.subplots(figsize=(10, 3.4))
bins = np.linspace(-7, 1, 60)
ax.hist(null_stats, bins=bins, density=True, alpha=0.6, label="Random walks (unit root)")
ax.hist(alt_stats, bins=bins, density=True, alpha=0.6, label="Trend-stationary, φ = 0.9")
ax.axvline(cutoff, color="grey", linestyle="--")
ax.set_xlabel("ADF statistic (71 years)")
ax.set_title("With 71 years of data, the two kinds of series give heavily overlapping statistics")
ax.legend(fontsize=8, loc="upper left")
plt.show()Even though every one of these series is stationary around its trend, the test rejects a unit root in only about one in eight of them (12%). In the other seven,, it wrongly fails to reject. With 71 points, a series that returns slowly and a series that never returns simply look alike. That's not a flaw in the ADF test in particular; any test would struggle. The data doesn't contain enough information.
This is why "the ADF test didn't reject" must never be read as "the series has a unit root". Economists learned this the hard way. In 1982, Charles Nelson and Charles Plosser ran Dickey–Fuller tests on long histories of US economic data and failed to reject a unit root in almost all of them, which started a decades-long debate about whether shocks to the economy are permanent. Part of the answer turned out to be low power.
Is it one trend line at all?
There's one more thing worth trying. If loudness really returned to a single straight trend line, that should hold in each part of the period too. Let's run the KPSS test on two halves, either side of the start of the "loudness war" (lesson 2.1):
for start, end in [(1950, 1990), (1991, 2020)]:
part = loud.loc[start:end]
print(f"{start}-{end}: KPSS p = {kpss(part, regression='ct', nlags='auto')[1]:.3f}")In both halves, the KPSS test rejects trend-stationarity (p = 0.01 for 1950–1990 and 0.014 for 1991–2020). Over the whole period it didn't. One explanation is that loudness doesn't follow one straight line: it follows different paths in different eras, joined by a shift, which is called a structural break. The economist Pierre Perron showed in 1989 that an unmodelled break can make a trend-stationary series look like it has a unit root, and he proposed tests that allow for one. That's a later lesson.
So what is loudness?
Put everything together:
- With its default settings, the ADF test rejects a unit root, and the KPSS test agrees the series looks trend-stationary.
- But the ADF result depends on the number of lags, and with most choices it doesn't reject.
- With 71 years, the test would miss most slowly returning series anyway.
- And within each half of the period, a single straight trend doesn't fit well.
The honest answer is that this data can't firmly separate "trend-stationary, returning slowly" from "random walk with drift", and that a straight trend line may be the wrong model altogether. That isn't a failure of the analysis. It's the result, and it tells you what to do next: treat any forecast built on either assumption with caution, especially far ahead, where the two models disagree most (a trend-stationary forecast stays close to the line; a random-walk forecast spreads out without limit). And investigate the break.
And the −0.33 autocorrelation from lesson 3.3? It turns out to rest mostly on a single zigzag: loudness jumped 1.66 dB from 1949 to 1950 and fell back 1.95 dB in 1951. Start the changes in 1951 and it shrinks to −0.20. Lesson 4.2 tests whether what's left is anything more than noise.
Key ideas
- A unit root (φ = 1) means shocks never fade: the series is a random walk.
- The ADF test: null hypothesis "unit root". A small p-value is evidence of stationarity.
- The KPSS test: null hypothesis "stationary". A small p-value is evidence against stationarity. Use both.
- The ADF statistic has its own distribution, far from the normal; the 5% cut-off is around −3.5 with a trend, not −1.645.
- Include a trend (
"ct") when the series has one, or the tests mistake a trending series for a random walk. - Check how the ADF result depends on the number of lags.
- These tests have low power in short series. "Can't reject a unit root" does not mean "has a unit root".
- Contradictory or fragile results are often a sign of a structural break.
Try it yourself
- Run
test_bothon the loudness series from 1922 instead of 1950. What do the tests say? Given lesson 3.3's findings about the early years, should you trust it? - Rerun the power simulation with φ = 0.5, and then with 300 years instead of 71. How does the share of correct rejections change?
- Run the null simulation 2,000 times with
regression="c"instead of"ct". Where is the 5% cut-off now? - Load the monthly Christmas page views and take logs as in lesson 3.3 (
log_m). Test them withtest_both(log_m, "ct"). Then test the seasonal difference,log_m.diff(12).dropna(), with"c". Do the results agree with what you found by looking at autocorrelations?
Next lesson: White noise versus a stationary series. Hear the difference between noise and memory, and test a model's leftovers.
The course
Music as Data: Time Series with Python
1Music as a time series
2Seeing patterns
3Decomposition and stationarity
4Testing a time series
5Missing values
- 5.1Handling missing values in music data coming soon
6Autocorrelation and forecasting
- 6.1Autocorrelation: finding the beat coming soon
- 6.2Partial autocorrelation and lag plots coming soon
- 6.3How forecastable is a hit? coming soon
7Smoothing and Granger causality
- 7.1Smoothing: moving averages and loudness envelopes coming soon
- 7.2Granger causality: does social-media buzz predict streams? coming soon
8From time series to AI music
- 8.1From forecasting to generating: how AI music models predict what comes next coming soon