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.

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

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

  1. The mean is constant over time.
  2. The variance is constant over time.
  3. 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:

Python
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()
Four panels: white noise jumping around zero; a smoother wobble that keeps returning to zero; a random walk that wanders far away; and a wobble around a steadily rising line.
Four panels: white noise jumping around zero; a smoother wobble that keeps returning to zero; a random walk that wanders far away; and a wobble around a steadily rising line.
  • 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:

Python
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}")
Two panels. On the left, 40 mean-reverting paths stay inside a fixed band around zero. On the right, 40 random walks fan out wider and wider over time.
Two panels. On the left, 40 mean-reverting paths stay inside a fixed band around zero. On the right, 40 random walks fan out wider and wider over time.

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.

Temporary or permanent? The viral moment

The difference between the last two series in the first chart matters enormously in practice. Imagine a song goes viral: a sudden boost to its audience. Two possible futures:

  • Trend-stationary: the boost fades, and the song returns to the path it was on. The shock was temporary.
  • Difference-stationary (a random walk, possibly with drift): the song's audience is permanently higher from then on. The shock was permanent.
Python
base = rng.normal(0, 0.5, T)
viral = base.copy()
viral[100] += 8                                       # one big shock at time 100

fig, ax = plt.subplots(1, 2, figsize=(10, 3.4), sharey=True)
for a, make, title in [(ax[0], lambda s: 0.03 * np.arange(T) + ar1(s, 0.8), "Trend-stationary: the shock fades"),
                       (ax[1], lambda s: np.cumsum(s + 0.03), "Random walk with drift: the shock stays")]:
    a.plot(make(base), linewidth=1.2, label="Without the viral moment")
    a.plot(make(viral), linewidth=1.2, label="With it")
    a.axvline(100, color="grey", linestyle=":", linewidth=1)
    a.set_title(title, fontsize=10)
    a.set_xlabel("Time")
ax[0].legend(loc="upper left", fontsize=8)
plt.tight_layout()
plt.show()
Two panels, each comparing a path with and without a big shock at time 100. On the left, the shocked path jumps up and then rejoins the other path within about twenty steps. On the right, the shocked path jumps up and stays the same distance above the other path forever.
Two panels, each comparing a path with and without a big shock at time 100. On the left, the shocked path jumps up and then rejoins the other path within about twenty steps. On the right, the shocked path jumps up and stays the same distance above the other path forever.

Same shock, opposite futures. On the left, within about twenty steps you can't tell the viral moment ever happened. On the right, it shifts the whole future up for good.

This is the practical reason stationarity matters. It decides whether forecasts should pull back towards a trend or simply carry on from wherever the series is now, and whether a shock (a viral moment, a playlist placement, a scandal) is something you wait out or something that changes the baseline. Telling the two apart from data is surprisingly hard, and lesson 4.1 introduces the statistical tests designed for it.

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.

Python
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()
Two panels: the loudness series with a rolling mean that rises from about −16 dB to about −7 dB; and a rolling standard deviation that is large before 1950 and small afterwards.
Two panels: the loudness series with a rolling mean that rises from about −16 dB to about −7 dB; and a rolling standard deviation that is large before 1950 and small afterwards.

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.

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

  1. 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?
  2. 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?
  3. Find the pair of yearly Spotify features with the strongest correlation in levels: years.corr(). Does it survive differencing?
  4. 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

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