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.

Part of the free course Music as Data: Time Series with Python · taught by Terence D. Agbeyegbe and Tone Agbeyegbe

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.

Python
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:

  1. its average is constant (usually zero),
  2. its variance is constant, and
  3. 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.

Python
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()
Three stacked panels of 150 points. White noise jumps around with no pattern. The φ = 0.9 series drifts in smooth, slow swings. The φ = −0.9 series zigzags, flipping sign almost every step.
Three stacked panels of 150 points. White noise jumps around with no pattern. The φ = 0.9 series drifts in smooth, slow swings. The φ = −0.9 series zigzags, flipping sign almost every step.

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.

Python
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)
Listen: white noise. A flat, even hiss, like a detuned radio.
Listen: memory with φ = 0.9. A muffled rumble, like distant surf or wind.
Listen: memory with φ = −0.9. A thin, bright hiss, all treble.

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.

Python
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()
Three spectra on a log scale. White noise is a flat line. The φ = 0.9 series starts very high at low frequencies and falls steeply. The φ = −0.9 series is its mirror image, low at the bass end and rising towards the highest frequencies.
Three spectra on a log scale. White noise is a flat line. The φ = 0.9 series starts very high at low frequencies and falls steeply. The φ = −0.9 series is its mirror image, low at the bass end and rising towards the highest frequencies.

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.

Python
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()
Three autocorrelation charts. White noise: every bar inside the grey band. φ = 0.9: bars start near 0.9 and decline slowly, all outside the band. φ = −0.9: bars alternate between negative and positive, shrinking slowly.
Three autocorrelation charts. White noise: every bar inside the grey band. φ = 0.9: bars start near 0.9 and decline slowly, all outside the band. φ = −0.9: bars alternate between negative and positive, shrinking slowly.

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:

Python
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.

Python
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.
Python
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}")
Two autocorrelation charts. The yearly change has every bar inside the band. The distance from the trend has large positive bars that fade slowly, then turn negative at longer lags, many of them well outside the band.
Two autocorrelation charts. The yearly change has every bar inside the band. The distance from the trend has large positive bars that fade slowly, then turn negative at longer lags, many of them well outside the band.

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:

Python
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()
Two autocorrelation charts of residuals up to lag 24. The ordinary STL residuals have a large negative bar at lag 12. The robust STL residuals stay inside the band except for two small crossings, at lags 17 and 22.
Two autocorrelation charts of residuals up to lag 24. The ordinary STL residuals have a large negative bar at lag 12. The robust STL residuals stay inside the band except for two small crossings, at lags 17 and 22.

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.

Uncorrelated isn't the same as unpredictable

One last subtlety. White noise only requires that values be uncorrelated. That's weaker than being completely unrelated. A series can have zero autocorrelation and still have a pattern, for example in how big its moves are. Here's a simulated series where calm stretches and turbulent stretches cluster together:

Python
rng2 = np.random.default_rng(1)
T = 1000
x = np.zeros(T + 100)
variance = np.ones(T + 100)
for i in range(1, T + 100):
    variance[i] = 0.02 + 0.1 * x[i - 1] ** 2 + 0.88 * variance[i - 1]   # big moves make big moves likelier
    x[i] = np.sqrt(variance[i]) * rng2.normal()
x = x[100:]

fig, ax = plt.subplots(figsize=(10, 3))
ax.plot(x, linewidth=0.7)
ax.set_title("No autocorrelation, but calm and turbulent spells cluster", fontsize=10)
plt.show()

print(f"The series:       Ljung-Box p = {ljung_box(x):.2f}")
print(f"Its squared size: Ljung-Box p = {ljung_box(x ** 2):.4f}")
A series that hovers around zero with quiet stretches and bursts of large swings.
A series that hovers around zero with quiet stretches and bursts of large swings.

The series itself passes the white-noise test (p = 0.68): its ups and downs are uncorrelated. But its squared values fail it decisively: a big move tends to follow a big move, in either direction. This is called volatility clustering, and it's everywhere in financial data, where calm markets and turbulent markets come in spells. Models for it (ARCH and GARCH) won Robert Engle a share of the 2003 Nobel prize in economics. Testing the squared residuals is a cheap way to check for it.

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

  1. Make a series with φ = 0.5 and listen to it. Can you hear the difference from white noise? Then look at its spectrum.
  2. 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?
  3. Run ljung_box on the robust STL residuals with 12 lags and with 36. Is the verdict stable?
  4. 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

Course home
  1. 1Music as a time series

  2. 2Seeing patterns

  3. 3Decomposition and stationarity

  4. 4Testing a time series

  5. 5Missing values

    • 5.1Handling missing values in music data coming soon
  6. 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
  7. 7Smoothing and Granger causality

    • 7.1Smoothing: moving averages and loudness envelopes coming soon
    • 7.2Granger causality: does social-media buzz predict streams? coming soon
  8. 8From time series to AI music

    • 8.1From forecasting to generating: how AI music models predict what comes next coming soon