Lesson 4.2Module 4: Testing a time series40 minIntermediate
White noise versus a stationary series
Every white noise is stationary, but not every stationary series is white noise. Hear the difference, see it in the autocorrelations and the spectrum, test it with Ljung–Box, and use it to check whether a model has left anything behind.
Lesson 4.1 asked whether a series is stationary. This lesson asks a sharper question: is it white noise, a series with no memory at all? The answer matters in two ways. A white-noise series can't be predicted from its past, so there's nothing left for a forecasting model to find. And the leftovers of a good model should be white noise, so this is also how you check your work. Along the way you'll hear why it's called "white", in a lesson that, for once, you can listen to.
Set up
You'll need data_by_year.csv (lesson 2.1) and christmas_pageviews.csv (lesson 2.2) in your working folder.
import wave
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.tsa.seasonal import STL
from statsmodels.tsa.stattools import acf
def save_wav(name, x, sr):
"""Save a numpy array as a 16-bit mono WAV file you can play (from lesson 1.2)."""
pcm = (x / np.abs(x).max() * 0.8 * 32767).astype(np.int16)
with wave.open(name, "wb") as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sr)
f.writeframes(pcm.tobytes())What white noise is
A series is white noise if:
- its average is constant (usually zero),
- its variance is constant, and
- any two values at different times are uncorrelated: knowing one tells you nothing, on average, about the other.
The first two rules are part of being stationary (lesson 3.2). The third is what makes white noise special. A stationary series can have memory: today can be related to yesterday, as long as that relationship stays the same over time. White noise has none. So every white-noise series is stationary, but most stationary series are not white noise.
The memory-series from lesson 4.1 makes a good comparison: value today = φ × value yesterday + shock, where the shocks are white noise. With φ between −1 and 1 it's stationary, and with φ = 0 it is white noise. Let's make three series: white noise, and two with memory, φ = 0.9 and φ = −0.9.
rng = np.random.default_rng(5)
def ar1(phi, n):
"""value today = phi * value yesterday + a white-noise shock"""
shocks = rng.normal(size=n + 100)
x = np.zeros(n + 100)
for i in range(1, n + 100):
x[i] = phi * x[i - 1] + shocks[i]
return x[100:] # drop the first 100 so the start doesn't matter
n = 500
series = {"White noise": rng.normal(size=n), "Memory, φ = 0.9": ar1(0.9, n), "Memory, φ = −0.9": ar1(-0.9, n)}
fig, axes = plt.subplots(3, 1, figsize=(10, 6), sharex=True)
for ax, (name, x) in zip(axes, series.items()):
ax.plot(x[:150], linewidth=1)
ax.set_title(name, fontsize=9, loc="left")
plt.tight_layout()
plt.show()All three are stationary: each keeps the same average and spread throughout. But they behave very differently. The φ = 0.9 series wanders in slow swings, because each value stays close to the last. The φ = −0.9 series zigzags, because each value tends to flip the sign of the last. White noise does neither.
What white noise sounds like
Turn each series into sound by playing it as an audio signal: 22,050 samples a second, for three seconds.
sr = 22050
sounds = {"white": rng.normal(size=3 * sr), "memory_plus": ar1(0.9, 3 * sr), "memory_minus": ar1(-0.9, 3 * sr)}
for name, x in sounds.items():
save_wav(f"{name}.wav", x, sr)You can hear the memory. Slow swings are low frequencies, so the φ = 0.9 series rumbles. Sign flips at every sample are the highest frequency possible, so the φ = −0.9 series sounds thin and bright. White noise sits in between: an even hiss, with no pitch favoured over any other.
Why "white"? The spectrum
That last sentence is exactly where the name comes from. In lesson 1.2, frequency was what you hear as pitch. A series' spectrum shows how much of its variation happens at each frequency. White light contains all colours in equal amounts. White noise contains all frequencies in equal amounts, so its spectrum is flat.
def spectrum(x, sr, smooth=301):
"""Power at each frequency (a periodogram), smoothed so the shape is visible."""
power = np.abs(np.fft.rfft(x)) ** 2 / len(x)
freqs = np.fft.rfftfreq(len(x), 1 / sr)
return freqs, pd.Series(power).rolling(smooth, center=True).mean()
fig, ax = plt.subplots(figsize=(10, 3.6))
for (name, x), label in zip(sounds.items(), series.keys()):
freqs, power = spectrum(x, sr)
ax.plot(freqs[::20], power[::20], linewidth=1.5, label=label) # every 20th point is plenty to draw
ax.set_yscale("log")
ax.set_xlabel("Frequency (Hz)")
ax.set_ylabel("Power (log scale)")
ax.set_title("White noise has a flat spectrum; memory tilts it")
ax.legend(fontsize=8, loc="upper center")
plt.show()The φ = 0.9 series puts its power in the low frequencies. Sound engineers call noise like that "red" or "brown", by analogy with light at the low-frequency end of the rainbow. The φ = −0.9 series is the mirror image, sometimes called "blue" noise. White noise is flat all the way across.
This is a useful way to think about any time series, not just audio. "Memory" and "uneven spectrum" are the same thing seen from two sides: one in time, one in frequency.
Seeing memory: the autocorrelation function
The time-side view is the autocorrelation function (ACF): the correlation between the series and itself shifted by 1 step, 2 steps, 3 steps and so on. Lesson 3.3 used just the first of these. For white noise, every one should be zero, apart from chance.
How big can "chance" be? For white noise of length n, each autocorrelation is roughly normal with spread 1/√n, so about 95% of them fall within ±1.96/√n. That's the band we'll draw.
def plot_acf_bars(ax, x, title, lags=20):
r = acf(x, nlags=lags)[1:] # drop lag 0, which is always 1
band = 1.96 / np.sqrt(len(x))
ax.bar(range(1, lags + 1), r, color=["C1" if abs(v) > band else "C0" for v in r])
ax.axhspan(-band, band, color="grey", alpha=0.2)
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_ylim(-1, 1)
ax.set_title(title, fontsize=9, loc="left")
fig, axes = plt.subplots(1, 3, figsize=(10, 3.2), sharey=True)
for ax, (name, x) in zip(axes, series.items()):
plot_acf_bars(ax, x, name)
axes[1].set_xlabel("Lag (steps)")
plt.tight_layout()
plt.show()The white noise stays inside the band. The φ = 0.9 series starts at about 0.9 and fades slowly: each step keeps 90% of the memory. The φ = −0.9 series alternates, the time-side signature of a zigzag. Module 6 will use these patterns to choose forecasting models.
Twenty chances to be wrong
There's a trap in reading an ACF chart. Each bar has a 5% chance of poking out of the band even for perfect white noise. With 20 bars, the chance that at least one pokes out is much higher:
trials = [rng.normal(size=n) for _ in range(1000)]
band = 1.96 / np.sqrt(n)
share = np.mean([(np.abs(acf(x, nlags=20)[1:]) > band).any() for x in trials])
print(f"White-noise series with at least one bar outside the band: {share:.0%}")About 60% of perfectly white series have at least one bar outside the band. So one bar sticking out, especially at a lag with no special meaning like 13 or 17, is not evidence of anything. What you want is a single test that looks at all the lags together.
One test for all the lags: Ljung–Box
The Ljung–Box test (Greta Ljung and George Box, 1978) adds up the squared autocorrelations for lags 1 to h into one statistic. Its null hypothesis is: the series is white noise (no autocorrelation up to lag h). A small p-value says there is memory somewhere in those lags.
def ljung_box(x, lags=10):
result = acorr_ljungbox(x, lags=[lags])
return float(result["lb_pvalue"].iloc[0])
series["Weak memory, φ = 0.2"] = ar1(0.2, n)
for name, x in series.items():
print(f"{name:22s} Ljung-Box p = {ljung_box(x):.4f}")The white noise passes (p = 0.23). Both strong-memory series fail emphatically (p is 0 to four decimal places). The interesting one is φ = 0.2, a series with only a little memory: the test still catches it (p = 0.007). With 500 values, even a weak pattern is detectable.
How many lags should h be? A common rule of thumb is 10 for non-seasonal data and two full seasons (24 for monthly data) for seasonal data. As with the ADF test's lags in lesson 4.1, it's worth checking that your conclusion doesn't hinge on the choice.
Is loudness's yearly change just noise?
Lesson 4.1 couldn't decide between two descriptions of loudness since 1950: trend-stationary, or a random walk with drift. Those two make different predictions about white noise.
- If loudness is a random walk with drift, its yearly changes are the drift plus white noise. They should pass the Ljung–Box test.
- If loudness is trend-stationary, it's the distance from the trend line that's stationary, and that distance shouldn't be white noise if the series returns slowly.
loud = pd.read_csv("data_by_year.csv", index_col="year")["loudness"].loc[1950:]
change = loud.diff().dropna() # 1951 to 2020
slope, intercept = np.polyfit(loud.index, loud.values, 1)
from_trend = loud - (intercept + slope * loud.index)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.2), sharey=True)
plot_acf_bars(axes[0], change, "Yearly change in loudness", lags=15)
plot_acf_bars(axes[1], from_trend, "Distance from the trend line", lags=15)
plt.tight_layout()
plt.show()
print(f"Yearly change: Ljung-Box p = {ljung_box(change):.2f}")
print(f"From the trend: Ljung-Box p = {ljung_box(from_trend):.4f}")The yearly changes pass: their lag-1 autocorrelation is −0.20, inside the band, and the Ljung–Box p-value is 0.51. The distance from the trend line fails badly: it has strong, slowly fading memory, like the φ = 0.9 pattern from earlier (the negative bars at long lags are what slow swings above and below a line look like over 70 years). That is exactly what a random walk with drift would produce, and it's also what a trend-stationary series that returns very slowly would produce, with 70 years of data. So this test doesn't settle lesson 4.1's question either, but it does say something useful: once you difference loudness, there's no memory left for a model to use. Your best forecast of next year's change is simply the average change.
A correction to lesson 3.3: there, the lag-1 autocorrelation of the changes "from 1950" was −0.33. Most of that comes from one zigzag at the very start. Loudness jumped 1.66 dB from 1949 to 1950, then fell back 1.95 dB in 1951, the kind of see-saw a noisy single year produces. Starting the changes in 1951 instead brings it to −0.20. One year moved the number that much: in a short series, always check whether a statistic depends on a single point.
Checking a model's leftovers
The most common use of a white-noise test is on residuals, what a model leaves unexplained. Lesson 3.1 said a decomposition's residuals should have "no pattern left". Now we can test that. Here are the ordinary and the robust STL decompositions of the Christmas song's monthly page views from lesson 3.1:
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
log_m = np.log(views.resample("MS").sum())
fits = {"STL": STL(log_m, period=12, seasonal=7).fit(),
"Robust STL": STL(log_m, period=12, seasonal=7, robust=True).fit()}
fig, axes = plt.subplots(1, 2, figsize=(10, 3.2), sharey=True)
for ax, (name, fit) in zip(axes, fits.items()):
plot_acf_bars(ax, fit.resid, f"{name} residuals", lags=24)
print(f"{name:11s} residuals: Ljung-Box p (24 lags) = {ljung_box(fit.resid, 24):.4f}")
plt.tight_layout()
plt.show()The ordinary STL residuals fail, and the ACF shows why: a big negative bar at lag 12. That's the spikes again. Ordinary STL lets a one-off spike pull up that month's seasonal estimate. Then the same month in neighbouring years falls below the inflated season, so the leftovers a year apart point in opposite directions. The robust fit pushes the spikes into the residual where they belong, and its residuals pass (p = 0.21). Two of its bars, at lags 17 and 22, do poke out of the band, but neither lag means anything for monthly data, and with 24 bars a couple of chance crossings are expected: exactly the trap from the "twenty chances" section. The Ljung–Box test, which weighs all the lags together, isn't troubled by them. The test confirms what lesson 3.1 argued by eye: robust STL is the better decomposition here.
Key ideas
- White noise: constant mean, constant variance, and no correlation between different times. Every white noise is stationary; not every stationary series is white noise.
- Memory shows up in the autocorrelation function (in time) and as an uneven spectrum (in frequency). White noise has a flat spectrum, which is where the name comes from.
- On an ACF chart, about 1 bar in 20 crosses the ±1.96/√n band by chance. Don't read meaning into a single bar.
- The Ljung–Box test checks many lags at once. Null hypothesis: white noise.
- A good model leaves white-noise residuals. Test them.
- Yearly loudness changes since 1951 are indistinguishable from white noise: the best forecast of next year's change is the average change.
- Uncorrelated isn't unpredictable: test the squared values too.
Try it yourself
- Make a series with φ = 0.5 and listen to it. Can you hear the difference from white noise? Then look at its spectrum.
- Reload loudness from 1949 (
.loc[1949:]), so the changes start in 1950, and rerun the Ljung–Box test. Does one extra year change the verdict? - Run
ljung_boxon the robust STL residuals with 12 lags and with 36. Is the verdict stable? - Apply the squared-values test to the robust STL residuals. Is there any sign of volatility clustering in the Christmas song's page views?
Next lesson: Detrending and deseasonalising: seasonally adjusted data and the loudness gap. What month-on-month changes really say, and why the latest figures get revised.
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