Lesson 4.3Module 4: Testing a time series45 minIntermediate
Detrending and deseasonalising: seasonally adjusted data and the loudness gap
Build a seasonally adjusted series and learn what month-on-month changes really say, see why the latest adjusted figures get revised, then detrend loudness four ways and find that the 'gap' you measure depends on the trend you chose.
Lessons 3.1 and 3.3 took trends and seasons out of a series to understand it, or to make it stationary. This lesson is about what you do with what's left. A seasonally adjusted series lets you ask "was this month good or bad?" and get a sensible answer. A detrended series shows the swings above and below the trend, which economists call the cycle. Both are produced constantly, by statistics offices, record labels and central banks. And both come with two warnings: the latest numbers will change, and the answer depends on the method.
Set up
You need christmas_pageviews.csv (lesson 2.2) and data_by_year.csv (lesson 2.1).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import STL
from statsmodels.tsa.filters.hp_filter import hpfilter
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
log_m = np.log(views.resample("MS").sum())
loud = pd.read_csv("data_by_year.csv", index_col="year")["loudness"].loc[1950:]Seasonally adjusted: was that a good month?
Here's a question a record label might ask about "All I Want for Christmas Is You": how did December 2025 go? Compared with November, views more than doubled. But views always jump in December, so that comparison says nothing. What you want to know is whether December rose more or less than a December usually does.
That's what seasonal adjustment answers. Take the season out, using the robust STL fit from lesson 3.1, and what's left is the series as it would look if every month were an ordinary month. Because we're on the log scale, subtracting the seasonal component is the same as dividing views by the seasonal factor.
fit = STL(log_m, period=12, seasonal=7, robust=True).fit()
adjusted = log_m - fit.seasonal # in logs: remove the season
fig, ax = plt.subplots(figsize=(10, 3.6))
ax.plot(log_m.index, np.exp(log_m), linewidth=1, alpha=0.6, label="Views per month")
ax.plot(adjusted.index, np.exp(adjusted), linewidth=2, label="Seasonally adjusted")
ax.set_yscale("log")
ax.set_ylabel("Views (log scale)")
ax.set_title("Seasonal adjustment removes the Christmas peaks and leaves the underlying path")
ax.legend(fontsize=8, loc="upper left")
plt.show()Notice that the adjusted line isn't smooth: the one-off spikes from lesson 2.2 (June 2022, April 2024) are still there. That's correct. Seasonal adjustment removes only the season, so the adjusted series is trend plus residual, surprises included. If it hid surprises, it would be useless for spotting them.
Now compare month-on-month changes, raw and adjusted, for the last 15 months:
def pct_change(log_series):
return (np.exp(log_series.diff()) - 1) * 100
compare = pd.DataFrame({"raw %": pct_change(log_m), "adjusted %": pct_change(adjusted)})
print(compare.loc["2024-10":"2025-12"].round(1))The raw changes are dominated by the season: up over 200% every November and December, down 91% every January. The adjusted changes are small, and they say something. December 2025: up 151% raw, but down 14% adjusted. It rose much less than Decembers usually do, so it was a weak Christmas for the song. That agrees with what lesson 3.3 found by a different route: December 2025 was 35% below December 2024. And January 2025's alarming 91% fall becomes a modest 8% dip once you allow for the usual January collapse.
This is why so many official statistics, like unemployment or retail sales, are published "seasonally adjusted". It's the only way to read one month's change without waiting a year. Year-on-year growth (lesson 3.3) is the other way, and it's simpler and needs no model, but it's slow: it tells you about the last twelve months, not the last one.
The latest figures will change
There's a catch. STL estimates each month's seasonal effect by smoothing across neighbouring years. In the middle of the data, a month has neighbours on both sides. At the end, it only has neighbours on one side, so its seasonal estimate is less certain, and it changes when next year's data arrives. To see how much, pretend it's January 2025: fit the same model on data up to December 2024, then compare its adjusted values for 2024 with the ones from the full data.
fit_then = STL(log_m.loc[:"2024-12"], period=12, seasonal=7, robust=True).fit()
adjusted_then = log_m.loc[:"2024-12"] - fit_then.seasonal
revision = (np.exp(adjusted.loc["2024"] - adjusted_then.loc["2024"]) - 1) * 100
fig, ax = plt.subplots(figsize=(10, 3.2))
ax.bar(revision.index.strftime("%b"), revision.values, color=np.where(revision > 0, "C0", "C1"))
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_ylabel("Revision (%)")
ax.set_title("How much each 2024 adjusted value changed once 2025's data arrived")
plt.show()
print(revision.round(1))Most months move by up to about 12%, but November 2024's adjusted value was revised up by 66%. With only the data to 2024, the model thought November's seasonal boost was larger than it now appears, and so it "adjusted away" too much of November 2024. A year later, with another November to compare with, it changed its mind.
Official statistics behave the same way, which is why government agencies revise seasonally adjusted figures for recent months, sometimes years after first publishing them. The practical lessons:
- Treat the most recent adjusted values as provisional. They're the least reliable numbers in the series, and often the ones people care about most.
- A change of direction in the last month or two of an adjusted series may not survive revision.
Detrending loudness: four ways to draw the line
Now the trend. Lesson 4.1 couldn't decide whether loudness since 1950 is trend-stationary, but it's still natural to ask: in which years was music louder or quieter than the trend would suggest? That's the gap between the series and its trend. Economists ask the same question about national output: the output gap is how far the economy is above or below its trend, and it's one of the main numbers central banks use to set interest rates.
The gap depends entirely on what you call the trend. Let's try four common choices:
- A straight line, as in lessons 3.3 and 4.1.
- A quadratic curve, which can bend once.
- An 11-year centred moving average, like the 2×12 average from lesson 2.2 but for yearly data.
- The Hodrick–Prescott (HP) filter, the standard tool for output gaps. It draws the smoothest curve that stays reasonably close to the data. A setting called λ (lambda) decides the balance: a large λ makes the trend stiff, close to a straight line; a small λ lets it follow the data. For yearly data, λ = 100 is the traditional choice.
years = loud.index.values.astype(float)
trends = {
"Straight line": np.polyval(np.polyfit(years, loud, 1), years),
"Quadratic": np.polyval(np.polyfit(years, loud, 2), years),
"11-year moving average": loud.rolling(11, center=True).mean().values,
"HP filter (λ = 100)": hpfilter(loud, lamb=100)[1].values,
}
gaps = pd.DataFrame({name: loud.values - tr for name, tr in trends.items()}, index=loud.index)
fig, axes = plt.subplots(2, 1, figsize=(10, 6.4), sharex=True)
axes[0].plot(loud.index, loud.values, color="grey", linewidth=1, label="Loudness")
for name, tr in trends.items():
axes[0].plot(loud.index, tr, linewidth=1.6, label=name)
axes[1].plot(gaps.index, gaps[name], linewidth=1.4)
axes[0].set_ylabel("dB")
axes[0].set_title("Four trends for loudness...", fontsize=10, loc="left")
axes[0].legend(fontsize=8, loc="upper left")
axes[1].axhline(0, color="grey", linewidth=0.8)
axes[1].set_ylabel("dB above or below trend")
axes[1].set_title("...and four different 'loudness gaps'", fontsize=10, loc="left")
plt.tight_layout()
plt.show()
summary = pd.DataFrame({
"spread (dB)": gaps.std(),
"lag-1 autocorrelation": gaps.apply(lambda g: g.dropna().autocorr(1)),
"gap in 2008 (dB)": gaps.loc[2008],
}).round(2)
print(summary)The four gaps tell different stories:
- The straight-line and quadratic gaps swing in long waves, with a spread of about 0.77 dB and a lag-1 autocorrelation of 0.77. They say the late 1960s and 1970s and the 2000s were loud relative to trend, and the late 1980s and early 1990s quiet. So were the late 2010s, as the loudness war eased.
- The moving-average and HP gaps are about half as big and much less persistent, because a flexible trend absorbs the long waves itself.
Take 2008, often called the peak of the loudness war. Against a straight line, it was 1.08 dB louder than trend, a big number. Against the HP trend, only 0.35 dB. Neither is wrong. They answer different questions: "how unusual was 2008 compared with the century's steady rise?" versus "how unusual was 2008 compared with the years around it?" When you see a gap reported, the first question to ask is: gap from what?
A filter can invent a cycle
There's a deeper problem with flexible filters. Lesson 3.3 showed that detrending a random walk with a straight line leaves slow swings that look like cycles but aren't. Flexible filters do the same, just with shorter swings. Let's run the HP filter on random walks, where there are no cycles at all:
rng = np.random.default_rng(2)
walks = [np.cumsum(rng.normal(size=len(loud))) for _ in range(500)]
cycle_lag1 = [pd.Series(hpfilter(w, lamb=100)[0]).autocorr(1) for w in walks]
print(f"Average lag-1 autocorrelation of the HP 'cycle' of a random walk: {np.mean(cycle_lag1):.2f}")
w = walks[0]
cycle, trend = hpfilter(w, lamb=100)
fig, axes = plt.subplots(2, 1, figsize=(10, 4.6), sharex=True)
axes[0].plot(w, color="grey", linewidth=1, label="A random walk")
axes[0].plot(trend, linewidth=2, label="HP trend")
axes[0].legend(fontsize=8, loc="upper left")
axes[1].plot(cycle, linewidth=1.5, color="C1")
axes[1].axhline(0, color="grey", linewidth=0.8)
axes[1].set_title("The HP 'cycle' of a series that has no cycles", fontsize=10, loc="left")
plt.tight_layout()
plt.show()The random walk's changes are pure white noise, with no rhythm at all. Yet its HP "cycle" has memory: averaged over 500 walks, its lag-1 autocorrelation is 0.44, and it tends to stay above or below zero for runs of several years, which is easy to read as a business-cycle-like rhythm. The filter created it. Economists Timothy Cogley and James Nason showed this in 1995, and in 2018 James Hamilton published a paper titled, bluntly, "Why you should never use the Hodrick–Prescott filter", proposing a regression-based alternative. The HP filter is still everywhere, but it's now used with more care.
The HP filter also suffers from the revision problem from the first half of this lesson. Its trend at the end of the data is a guess that changes as new years arrive:
_, trend_then = hpfilter(loud.loc[:2008], lamb=100)
_, trend_now = hpfilter(loud, lamb=100)
print(f"HP trend for 2008, using data up to 2008: {trend_then.loc[2008]:.2f} dB")
print(f"HP trend for 2008, using data up to 2020: {trend_now.loc[2008]:.2f} dB")Looking back from 2020, the 2008 trend is 0.43 dB lower than it looked in 2008, which makes 2008's gap 0.43 dB bigger. The end of the data is where filters are least reliable, and it's usually the part you most want to know about. Central banks face exactly this problem when they estimate today's output gap.
Which method when?
- Seasonally adjust (e.g. robust STL) when you want to compare consecutive months. Treat the last few adjusted values as provisional.
- Use year-on-year growth when you want a simple, model-free comparison and can accept that it lags.
- Detrend with a straight line only if you have good reason to think the series returns to a fixed trend (lesson 4.1's tests help, though they often can't decide).
- Use a flexible trend (moving average, HP filter) to see short-run deviations, but remember that it absorbs long swings, can manufacture cycles, and is least reliable at the end.
- Always say which trend your gap is measured from.
Key ideas
- A seasonally adjusted series shows whether a month was better or worse than usual for that time of year. Month-on-month changes only make sense after adjustment.
- The latest adjusted values get revised as new data arrives, sometimes a lot (November 2024 by 66%). Treat them as provisional.
- A detrended series, or gap, depends entirely on the trend you chose: 2008's loudness gap is 1.08 dB from a straight line, 0.35 dB from an HP trend.
- Flexible filters absorb long swings and can invent cycles: the HP filter finds rhythm in a random walk.
- All filters are least reliable at the end of the data.
Try it yourself
- Refit the seasonal adjustment with
seasonal=13instead of 7. Does December 2025 still look weak? - Repeat the revision exercise for 2023, fitting on data to December 2023. Is November revised a lot again? Why might November be particularly hard?
- Rerun the loudness gaps with the HP filter at λ = 6.25, another common choice for yearly data. How big is the 2008 gap now?
- Compute 2008's gap from the 11-year moving average using data only up to 2008. What goes wrong, and why?
Next lesson: Testing for seasonality: weekends, Christmas and New Music Friday. A huge season, a tiny one, and one the music industry changed overnight.
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