Lesson 3.2Module 3: Decomposition and stationarity40 minIntermediate
Stationary and non-stationary series: why some trends fool you
What it means for a series to be stationary, why random walks wander off and never come back, how to tell a temporary shock from a permanent one, and how two unrelated music trends can correlate at −0.95.
Over the last century, as music on Spotify became less acoustic, it also became more popular: the two yearly series correlate at −0.95. Does that mean acoustic music is unpopular? No. In this lesson you'll see why: two series that both drift over time will almost always look related, whether they are or not. The idea that sorts the real relationships from the fake ones is stationarity, and it sits underneath almost everything else in time-series analysis.
What "stationary" means
A series is stationary if its statistical behaviour doesn't change over time. Pick any stretch of it, early or late, and you'd see the same kind of thing: the same average level, the same amount of wobble, the same way each value relates to the ones before it. Formally (this is called weak or covariance stationarity):
- The mean is constant over time.
- The variance is constant over time.
- The relationship between a value and the value k steps earlier depends only on k, not on when you look.
A stationary series can wobble a lot, but it always comes back towards the same level. A non-stationary series doesn't: it trends, or wanders, or its wobble grows or shrinks.
Some music examples:
- A sustained note, sampled as audio, is close to stationary: the same waveform, repeating.
- Daily streams of an old catalogue song often look roughly stationary: they wobble around a steady level.
- The loudness of new music, year by year (lesson 2.1), is clearly not: its level kept rising for decades.
- A song's total streams to date is never stationary: it only ever goes up.
Four series
Let's build the four basic shapes. Each one is driven by the same kind of random shocks, but they combine those shocks differently:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
T = 200
shocks = rng.normal(0, 1, T)
def ar1(shocks, phi):
"""Each value is phi times the previous value, plus a new shock."""
x = np.zeros(len(shocks))
for t in range(1, len(shocks)):
x[t] = phi * x[t - 1] + shocks[t]
return x
white_noise = shocks # no memory at all
mean_reverting = ar1(shocks, 0.8) # remembers, but drifts back towards 0
random_walk = np.cumsum(shocks) # every shock is permanent
trend_stationary = 0.05 * np.arange(T) + ar1(shocks, 0.8) # mean-reverting wobble around a rising line
series = {"White noise (stationary)": white_noise,
"Mean-reverting, φ = 0.8 (stationary)": mean_reverting,
"Random walk (not stationary)": random_walk,
"Trend plus mean-reverting noise (not stationary)": trend_stationary}
fig, axes = plt.subplots(2, 2, figsize=(10, 5.4), sharex=True)
for ax, (name, x) in zip(axes.flat, series.items()):
ax.plot(x, linewidth=1)
ax.set_title(name, fontsize=9)
plt.tight_layout()
plt.show()- White noise has no memory: each value is a fresh random draw.
- The mean-reverting series (an autoregressive or AR(1) series) remembers 80% of its last value, so it moves in smoother swings. But each shock fades, and it keeps returning to zero. It's stationary.
- The random walk is the running total of the shocks: each value is the last value plus a new shock. Nothing pulls it back, so it wanders off. That's the case φ = 1: it remembers 100% of where it was.
- The last series has a steady upward trend, with mean-reverting wobble around it. It isn't stationary, because its mean rises, but it always returns to its trend line.
Why a random walk isn't stationary
One run of a random walk can look a lot like a trend. To see what's really different, simulate many runs of each series and watch how far they spread:
runs = 2000
many_shocks = rng.normal(0, 1, (runs, T))
walks = many_shocks.cumsum(axis=1)
ar_paths = np.zeros((runs, T))
for t in range(1, T):
ar_paths[:, t] = 0.8 * ar_paths[:, t - 1] + many_shocks[:, t]
fig, ax = plt.subplots(1, 2, figsize=(10, 3.6), sharey=True)
ax[0].plot(ar_paths[:40].T, linewidth=0.6, alpha=0.6)
ax[0].set_title("40 mean-reverting paths: they stay in a band")
ax[1].plot(walks[:40].T, linewidth=0.6, alpha=0.6)
ax[1].set_title("40 random walks: they spread out forever")
for a in ax:
a.set_xlabel("Time")
plt.tight_layout()
plt.show()
for t in [10, 50, 100, 199]:
print(f"t = {t:>3}: spread of random walks {walks[:, t].std():5.1f} | spread of mean-reverting paths {ar_paths[:, t].std():4.1f}")The mean-reverting paths stay in the same band forever: their spread settles at about 1.7 and stays there. The random walks fan out: their spread grows with the square root of time (about 3 after 10 steps, about 14 after 200). A random walk's variance keeps growing, which breaks rule 2. So a random walk is non-stationary even though it has no trend at all.
A real series: a century of loudness
What about the loudness data from lesson 2.1? A quick check is to compute the mean and the spread over a moving window. If the series were stationary, both would stay roughly constant. You'll need data_by_year.csv from that lesson.
years = pd.read_csv("data_by_year.csv", index_col="year")
loud = years["loudness"]
fig, ax = plt.subplots(2, 1, figsize=(10, 4.6), sharex=True)
ax[0].plot(loud, linewidth=1, alpha=0.6, label="Loudness")
ax[0].plot(loud.rolling(10, center=True).mean(), linewidth=2.2, label="10-year rolling mean")
ax[0].legend(loc="upper left", fontsize=8)
ax[0].set_title("The mean keeps moving", fontsize=10)
ax[1].plot(loud.rolling(10, center=True).std(), linewidth=2, color="C2")
ax[1].set_title("10-year rolling standard deviation: the wobble shrinks", fontsize=10)
plt.tight_layout()
plt.show()Both rules fail. The rolling mean climbs by about 9 dB over the century, and the rolling standard deviation is much larger before 1950 than after (partly because, as lesson 2.1 showed, the early years rest on far fewer tracks). This series is non-stationary on two counts.
Spurious correlation: when trends fool you
Now the opening puzzle. Here's what happens when you correlate two random walks that have nothing to do with each other: different random shocks, no connection at all.
pairs = 1000
a = rng.normal(0, 1, (pairs, 100)).cumsum(axis=1) # 1,000 independent random walks...
b = rng.normal(0, 1, (pairs, 100)).cumsum(axis=1) # ...and 1,000 more, unrelated to the first
walk_r = np.array([np.corrcoef(a[i], b[i])[0, 1] for i in range(pairs)])
noise_a, noise_b = rng.normal(0, 1, (2, pairs, 100)) # the same, but stationary white noise
noise_r = np.array([np.corrcoef(noise_a[i], noise_b[i])[0, 1] for i in range(pairs)])
print(f"Unrelated random walks: {np.mean(np.abs(walk_r) > 0.5):.0%} of pairs correlate above 0.5 (either sign)")
print(f"Unrelated white noise: {np.mean(np.abs(noise_r) > 0.5):.0%} of pairs correlate above 0.5")About four in ten pairs of completely unrelated random walks show a correlation stronger than 0.5. For stationary noise, it essentially never happens. Two series that each wander will usually wander in some shared direction for a while, and the correlation coefficient can't tell that apart from a real link. The statistician George Udny Yule called these nonsense correlations in 1926. In regression they're known as spurious regressions, after a famous 1974 paper by Clive Granger and Paul Newbold.
A simple first check: correlate the changes instead of the levels. Year-to-year changes in a trending series are often much closer to stationary, and two unrelated series' changes shouldn't line up:
pairs_to_check = [("acousticness", "popularity"), ("loudness", "popularity"), ("loudness", "energy")]
table = pd.DataFrame({
"levels": [years[x].corr(years[y]) for x, y in pairs_to_check],
"year-to-year changes": [years[x].diff().corr(years[y].diff()) for x, y in pairs_to_check],
}, index=[f"{x} vs {y}" for x, y in pairs_to_check]).round(2)
print(table)
fig, ax = plt.subplots(1, 2, figsize=(10, 3.8))
ax[0].scatter(years["acousticness"], years["popularity"], s=14, color="C1")
ax[0].set_title(f"Levels: r = {table.iloc[0, 0]}", fontsize=10)
ax[1].scatter(years["acousticness"].diff(), years["popularity"].diff(), s=14, color="C0")
ax[1].set_title(f"Year-to-year changes: r = {table.iloc[0, 1]}", fontsize=10)
for a in ax:
a.set_xlabel("Acousticness")
a.set_ylabel("Popularity")
fig.suptitle("Acousticness vs popularity, by release year", fontsize=11)
plt.tight_layout()
plt.show()The table tells the story:
- Acousticness and popularity correlate at −0.95 in levels, but only 0.06 in changes. Years when music got a bit more acoustic weren't years when it got less popular. The two series simply both trended over the century, in opposite directions. (And as lesson 2.1 showed, the popularity trend isn't even real history. It comes from how Spotify defines popularity.)
- Loudness and popularity are similar: 0.93 in levels, much weaker in changes.
- Loudness and energy correlate at 0.93 in levels and still 0.74 in changes. That relationship survives because it's real: Spotify's energy score is partly built from loudness, so when loudness moves, energy moves with it.
Correlating changes isn't the last word. Two series can share a genuine long-run link that differences throw away, an idea called cointegration that comes later in the course. But it's the right first question to ask of any correlation between two trending series.
Key ideas
- A series is stationary if its mean, its variance and its relationship with its own past don't change over time.
- Mean-reverting series always come back to the same level. Random walks don't: their spread grows with the square root of time.
- Trend-stationary series return to a trend after a shock (temporary effects). Difference-stationary series, like random walks, keep every shock (permanent effects). Telling them apart matters for forecasting and needs formal tests (lesson 4.1).
- Rolling statistics are a quick visual check: a moving mean or a changing spread means non-stationary.
- Two trending or wandering series will often correlate strongly for no reason (nonsense correlation, spurious regression). Check the correlation of their changes before believing it.
Try it yourself
- Change φ in the mean-reverting series to 0.95, then 0.99. How do the paths change? How hard is it to tell φ = 0.99 apart from a random walk (φ = 1) in a single run of 200 steps?
- In the viral-moment chart, change 0.8 to 0.95 in the trend-stationary series. How long does the shock now take to fade?
- Find the pair of yearly Spotify features with the strongest correlation in levels:
years.corr(). Does it survive differencing? - Lesson 2.2's monthly Christmas page views: is that series stationary? Plot its 12-month rolling mean and standard deviation and decide.
Next lesson: Making a series stationary: differencing, detrending and transforming. The right tool for each kind of series, and what the wrong one does.
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