Lesson 3.3Module 3: Decomposition and stationarity40 minIntermediate

Making a series stationary: differencing, detrending and transforming

The toolkit for turning a wandering series into a stable one: logs, differences, seasonal differences and detrending. Learn which to use when, what using the wrong one does, and why a one-off spike shows up twice.

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

Lesson 3.2 showed why non-stationary series are dangerous: they wander, they fool correlations, and their past doesn't describe their future. Most forecasting methods therefore start by making a series stationary. There's a small toolkit for it, and the skill is choosing the right tool. Use the wrong one and you don't just fail to fix the problem: you create a new one. This lesson works through the tools on simulated data, a century of loudness and the Christmas song.

The toolkit

  • Transform (usually logs): steadies a series whose wobble grows with its level, and turns multiplicative patterns into additive ones (lesson 2.3).
  • Difference: replace each value with its change since the previous value. This removes a random walk's wandering.
  • Seasonal difference: replace each value with its change since the same point one season ago (this December minus last December). This removes a repeating season.
  • Detrend: fit a trend line (or a smooth curve, as in lesson 3.1) and keep what's left over. This removes a trend that the series always returns to.

To check whether a tool worked, we'll use one number: the lag-1 autocorrelation, the correlation between a series and itself shifted by one step. Module 6 covers autocorrelation properly. For now, the two warning signs are:

  • Close to +1: the series still wanders, and each value is nearly the same as the last.
  • Close to −0.5: the series has been over-differenced: you removed something that wasn't there, and created an artificial zigzag.

Right tool, wrong tool

Lesson 3.2 described two kinds of non-stationary series. A trend-stationary series always comes back to its trend line, so the fix is to detrend it. A random walk never comes back, so the fix is to difference it. Here's what happens with each tool on each kind:

Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(3)
T = 300
t = np.arange(T)
trend_stat = 0.05 * t + rng.normal(0, 1, T)          # returns to its trend line
walk = np.cumsum(rng.normal(0, 1, T))                 # never returns

def detrend(x):
    slope, intercept = np.polyfit(t[: len(x)], x, 1)  # fit a straight line...
    return x - (intercept + slope * t[: len(x)])      # ...and keep what's left

def lag1(x):
    return pd.Series(x).autocorr(1)

results = {
    "Trend-stationary, detrended (right)": detrend(trend_stat),
    "Trend-stationary, differenced (wrong)": np.diff(trend_stat),
    "Random walk, detrended (wrong)": detrend(walk),
    "Random walk, differenced (right)": np.diff(walk),
}
fig, axes = plt.subplots(2, 2, figsize=(10, 5.4))
for ax, (name, x) in zip(axes.flat, results.items()):
    ax.plot(x, linewidth=0.8)
    ax.set_title(f"{name}\nlag-1 autocorrelation = {lag1(x):.2f}", fontsize=9)
plt.tight_layout()
plt.show()
Four panels. Top left: a detrended trend-stationary series, stable noise. Top right: the same series differenced, a jagged zigzag. Bottom left: a detrended random walk, still wandering in long swings. Bottom right: the random walk differenced, stable noise.
Four panels. Top left: a detrended trend-stationary series, stable noise. Top right: the same series differenced, a jagged zigzag. Bottom left: a detrended random walk, still wandering in long swings. Bottom right: the random walk differenced, stable noise.

The two "right" panels look like stable noise, with lag-1 autocorrelation near zero. The two "wrong" panels show the two failure modes:

  • Differencing a trend-stationary series gives a lag-1 autocorrelation of about −0.5. Each value's noise appears twice, once added and once subtracted, so neighbouring changes are pulled in opposite directions. The series is technically stationary, but it's harder to model than the original, and forecasts built on it tend to be worse.
  • Detrending a random walk removes the overall slope, but the wandering is still there (lag-1 autocorrelation about 0.95). Worse, the leftovers can look like slow cycles that aren't really there. Economists Charles Nelson and Heejoon Kang showed this in 1981, in a paper on "spurious periodicity in inappropriately detrended time series".

So the choice between differencing and detrending depends on which kind of series you have, which is exactly what the tests in lesson 4.1 are designed to tell you.

A century of loudness, differenced

The yearly loudness series from lesson 2.1 kept rising for decades. Its first difference is the change in average loudness from one year to the next. You'll need data_by_year.csv from lesson 2.1.

Python
loud = pd.read_csv("data_by_year.csv", index_col="year")["loudness"]
change = loud.diff().dropna()                         # this year minus last year, in dB

fig, ax = plt.subplots(figsize=(10, 3.4))
ax.bar(change.index, change.values, width=0.8, color=np.where(change.index < 1950, "C3", "C0"))
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_ylabel("Change in average loudness (dB)")
ax.set_title("Year-to-year change in loudness: wild before 1950, steady after")
plt.show()

for start, end in [(1922, 1949), (1950, 2020)]:
    part = change.loc[start:end]
    print(f"{start}-{end}: average change {part.mean():+.2f} dB a year, spread {part.std():.2f} dB, "
          f"lag-1 autocorrelation {part.autocorr(1):.2f}")
Bars showing each year's change in loudness. Before 1950 they swing wildly, up and down by several decibels; from 1950 on they are small and mostly slightly positive.
Bars showing each year's change in loudness. Before 1950 they swing wildly, up and down by several decibels; from 1950 on they are small and mostly slightly positive.

Differencing removed the long climb. After 1950, the changes hover around a small positive average, about +0.13 dB a year: the century's rise, expressed as a steady drift. But the chart also shows that differencing alone didn't make the whole series stationary. Before 1950 the changes are about four times as variable, which breaks the constant-variance rule.

That's a data problem more than a music one. As lesson 2.1 showed, the early years rest on far fewer tracks, so each yearly average carries a lot of sampling error. And sampling error leaves its own fingerprint: when each year's average has some independent error, differencing turns that error into the over-differencing zigzag you saw above. That's why the early years' lag-1 autocorrelation is −0.50, the over-differencing signature exactly. The sensible fix is not another transformation. It's to analyse the reliable part: 1950 onwards.

Even from 1950, the lag-1 autocorrelation is −0.33: negative enough to notice. Either the yearly averages of 2,000 tracks still carry some sampling noise, or loudness is closer to a trend-stationary series (which shouldn't be differenced) than to a random walk. Telling those apart is exactly the job of the tests in lesson 4.1.

The Christmas song: logs, then a seasonal difference

The monthly Christmas page views from lessons 2.2 and 3.1 have both a trend and a strong season. Let's apply the tools one at a time and watch the two autocorrelations that matter: lag 1 (does it still wander?) and lag 12 (is the season still there?).

Python
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
log_m = np.log(views.resample("MS").sum())

steps = {
    "1. log(views)": log_m,
    "2. First difference": log_m.diff(),
    "3. Seasonal difference (12 months)": log_m.diff(12),
    "4. Seasonal and first difference": log_m.diff(12).diff(),
}
fig, axes = plt.subplots(4, 1, figsize=(10, 7.6), sharex=True)
for ax, (name, s) in zip(axes, steps.items()):
    s = s.dropna()
    ax.plot(s.index, s.values, linewidth=1)
    ax.set_title(f"{name}:  lag-1 autocorrelation {s.autocorr(1):.2f},  lag-12 autocorrelation {s.autocorr(12):.2f}",
                 fontsize=9, loc="left")
plt.tight_layout()
plt.show()
Four stacked panels: the log series with its yearly spikes; its first difference, still showing a spike-and-drop every December and January; the seasonal difference, a fairly steady series around zero with a few large spikes; and the seasonal-plus-first difference, a jagged zigzag.
Four stacked panels: the log series with its yearly spikes; its first difference, still showing a spike-and-drop every December and January; the seasonal difference, a fairly steady series around zero with a few large spikes; and the seasonal-plus-first difference, a jagged zigzag.

Read the numbers down the panels:

  1. log(views) has a lag-12 autocorrelation of 0.96: a powerful season.
  2. A first difference removes the slow trend, but the season survives (lag 12 is still 0.92). A first difference can't remove a pattern that repeats every 12 months.
  3. A seasonal difference (this month minus the same month last year) removes the season. What's left fluctuates around zero, with a lag-1 autocorrelation of about 0.3: some memory, but no wandering.
  4. Adding a first difference on top pushes lag 1 to −0.5, the over-differencing signature. One difference too many.

So for this series, a log followed by a seasonal difference is the right amount. It also has a natural meaning. The difference of two logs is approximately a percentage change, so a seasonal difference of logs is the year-on-year growth rate: this December compared with last December.

Python
growth = (np.exp(log_m.diff(12)) - 1) * 100            # exact year-on-year change, in %
print("December, change on the previous December (%):")
print(growth[growth.index.month == 12].dropna().round(0))

December 2019 was up 60% on December 2018, the year the song reached number one in the US. December 2025 was down 35% on 2024. Year-on-year growth is how the music industry reports most numbers, and now you know it's a seasonal difference of logs.

A spike that echoes

One more thing in panel 3: its lag-12 autocorrelation is about −0.45, strongly negative. Where does that come from?

Python
seasonal_diff = log_m.diff(12)
print(seasonal_diff.loc[["2022-06-01", "2023-06-01", "2024-04-01", "2025-04-01"]].round(2))

These are the two one-off spikes investigated in lesson 2.2. A seasonal difference compares each month with the same month a year earlier, so a one-off spike appears twice: as a big rise in the month it happened (April 2024: +1.58) and as an equally big fall twelve months later, when the next April is compared with the spike (April 2025: −1.63). Each spike produces a matching echo, and those pairs are what make the lag-12 autocorrelation negative. Leave out just those four months and it shrinks from −0.45 to about −0.2.

That's a general lesson about differencing: it spreads a one-off event across two time points. Before you difference, it's worth finding and dealing with outliers, for instance by flagging them or using a robust method like the one in lesson 3.1.

Which tool when?

  • The wobble grows with the level: take logs.
  • It wanders and never comes back: take a first difference.
  • It follows a steady trend it always returns to: detrend.
  • It has a repeating season: take a seasonal difference (or use STL, lesson 3.1).
  • Lag-1 autocorrelation near −0.5 after differencing: you've over-differenced, so go back a step.
  • The variance changes because the data quality changes: use the reliable period, not another transformation.

Always check the result by plotting it and looking at its autocorrelations. And deciding formally between differencing and detrending needs a statistical test: that's the next module.

Key ideas

  • The toolkit: logs, first differences, seasonal differences and detrending.
  • Difference a random walk; detrend a trend-stationary series. The wrong choice either leaves the wandering in place (detrended random walk) or creates an artificial zigzag (over-differencing, lag-1 autocorrelation about −0.5).
  • A seasonal difference of logs is the year-on-year growth rate.
  • Differencing spreads a one-off spike across two points: a jump and an echo.
  • Sometimes non-stationarity comes from the data, not the process: changing sample sizes change the variance. The fix is to choose the reliable period.

Try it yourself

  1. Average the loudness changes over the loudness-war years alone (change.loc[1991:2008].mean()). How does that compare with the 1950–2020 average of +0.13 dB a year?
  2. Detrend the loudness series from 1950 with a straight line instead of differencing it. Plot what's left. Does it look like it returns to zero, or does it wander?
  3. Compute the year-on-year growth for every month of 2025. Which months grew and which shrank compared with 2024?
  4. Replace April 2024 with the average of March and May 2024, then redo the seasonal difference. What happens to the lag-12 autocorrelation?

Next lesson: Testing for stationarity: the ADF and KPSS tests. Two tests that ask opposite questions, and what loudness says when you put the question to them.

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