Lesson 3.1Module 3: Decomposition and stationarity40 minIntermediate
Decomposition: classical and STL, and a season that changes
Split a series into trend, season and residual in one line of code, check it against the version you built by hand, then use STL to let the Christmas season shrink over the decade and to stop an outlier from bending the trend.
In lesson 2.2 you took the Christmas song's page views apart by hand: a moving average for the trend, monthly averages for the season, and whatever was left as noise. Lesson 2.3 found two weaknesses in that approach: it forces the season to be identical every year, and one strange month can bend the trend. This lesson does the same decomposition in one line of code, proves it's the same thing, and then switches to STL, a method that fixes both problems.
Set up
You need one more free library, statsmodels, which provides many of the statistical tools in the rest of this course:
pip install statsmodelsWe'll keep using the monthly page views for "All I Want for Christmas Is You" from lesson 2.2 (christmas_pageviews.csv), on the log scale:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import STL, seasonal_decompose
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
monthly = views.resample("MS").sum()
log_m = np.log(monthly)
print(len(log_m), "months")And a small function to draw any decomposition as four stacked panels, so every method looks the same:
def plot_parts(observed, trend, season, resid, title):
fig, ax = plt.subplots(4, 1, figsize=(10, 7), sharex=True)
ax[0].plot(observed.index, observed.values, linewidth=1)
ax[1].plot(trend.index, trend.values, linewidth=2, color="C1")
ax[2].plot(season.index, season.values, linewidth=1, color="C2")
ax[3].bar(resid.index, resid.values, width=20, color="C3")
ax[3].axhline(0, color="grey", linewidth=0.8)
for a, name in zip(ax, ["Observed: log(views)", "Trend", "Season", "Residual"]):
a.set_title(name, fontsize=9, loc="left")
fig.suptitle(title, fontsize=11)
plt.tight_layout()
plt.show()Classical decomposition in one line
The method you built by hand has a name: classical decomposition. statsmodels does it with seasonal_decompose. Because we're working with logs, we ask for the additive version (lesson 2.3 explained why logs turn a multiplicative series into an additive one):
classical = seasonal_decompose(log_m, model="additive", period=12)
plot_parts(log_m, classical.trend, classical.seasonal, classical.resid,
"Classical decomposition of log(monthly views)")Is it really what you built by hand in lesson 2.2? Let's check rather than trust:
weights = np.array([0.5] + [1] * 11 + [0.5]) / 12
by_hand_trend = log_m.rolling(13, center=True).apply(lambda w: np.dot(w, weights), raw=True)
detrended = log_m - by_hand_trend
by_hand_season = detrended.groupby(detrended.index.month).mean()
by_hand_season = by_hand_season - by_hand_season.mean()
print("Largest difference in trend: ", np.nanmax(np.abs(classical.trend - by_hand_trend)))
print("Largest difference in season:", np.abs(classical.seasonal.values - by_hand_season.reindex(log_m.index.month).values).max())Both differences are zero. The library function is exactly the centred 2×12 moving average plus monthly averages from lesson 2.2. That's worth doing whenever you can: check that a function does what you think before you rely on it.
It also has exactly the same weaknesses:
- The trend stops six months short of each end, because the centred window runs out of data.
- The season is identical every year. Look at the third panel: the same shape, copied ten times. Lesson 2.3 showed that's wrong for this song.
- Outliers leak into the trend. A moving average gives one strange month (April 2024) a twelfth of the weight in every trend value around it.
STL: a season that can change
STL stands for Seasonal-Trend decomposition using LOESS, a method published by Robert Cleveland and colleagues in 1990. LOESS is a smoothing technique: it fits many small, local curves, each using only nearby data. STL uses it twice, over and over: once to smooth the trend, and once to smooth the season. The key difference is how it handles the season. Instead of averaging all ten Decembers into one number, STL smooths the Decembers as their own series, December 2016 to December 2025, so December's effect can drift gradually from year to year. The same goes for every other month.
The main setting is seasonal, the length of that smoother in years. It must be an odd number. A small value lets the season change quickly; a very large one makes it almost fixed, like classical decomposition. We'll use 7.
stl = STL(log_m, period=12, seasonal=7).fit()
plot_parts(log_m, stl.trend, stl.seasonal, stl.resid, "STL decomposition: the season can change over time")Two things are different. The trend now reaches both ends of the data (though, as with any method, estimates at the very ends are the least certain). And the seasonal peaks shrink. To see it clearly, compare December's seasonal effect, year by year, under both methods:
dec = log_m.index.month == 12
factors = pd.DataFrame({
"classical": np.exp(classical.seasonal[dec].values),
"STL": np.exp(stl.seasonal[dec].values),
}, index=log_m.index[dec].year).round(1)
print(factors)
ax = factors.plot(figsize=(10, 3.2), marker="o", linewidth=2)
ax.set_ylabel("December, × the trend")
ax.set_title("December's seasonal factor: fixed by classical decomposition, shrinking under STL")
plt.show()Classical decomposition says December is always about 16.6 times the trend: one average for the whole decade. STL says December was about 21 times the trend in 2016 and has shrunk steadily to about 13 times. That's what lesson 2.3 discovered: the song's year-round audience grew much faster than its Christmas peak.
And the patterned leftovers from lesson 2.3 should now be gone. They are:
print("December residuals, classical:", classical.resid[dec].dropna().round(2).tolist())
print("December residuals, STL: ", stl.resid[dec].round(2).tolist())Under classical decomposition, December's residuals drift from clearly positive to clearly negative. Under STL they're small, and they bounce around zero with no drift. The model now captures what the data was doing.
Robust STL: don't let one month bend the trend
April 2024 is still a problem. Lesson 2.2's detective work suggested that its huge spike (about 30,000 views in a single April day, almost none of them from the Wikipedia app) was probably automated traffic, not people. But both methods so far let it pull the trend upward.
STL has a robust option. It fits the decomposition, looks for months with unusually large residuals, gives them less weight, and fits again, repeating until things settle down. Outliers end up in the residual, where they belong, instead of distorting the trend and the season.
robust = STL(log_m, period=12, seasonal=7, robust=True).fit()
window = slice("2023-01", "2025-06")
ax = np.exp(log_m[window]).plot(figsize=(10, 3.4), logy=True, linewidth=1, alpha=0.5, label="Monthly views")
np.exp(stl.trend[window]).plot(ax=ax, linewidth=2, label="STL trend")
np.exp(robust.trend[window]).plot(ax=ax, linewidth=2, label="Robust STL trend")
ax.set_ylabel("Views per month (log scale)")
ax.set_title("A robust fit keeps the April 2024 spike out of the trend")
ax.legend(loc="upper right", fontsize=8)
plt.show()
print("Residual for April 2024: STL", round(stl.resid["2024-04-01"], 2), "| robust STL", round(robust.resid["2024-04-01"], 2))
print("Weight the robust fit gave April 2024:", round(robust.weights["2024-04-01"], 2))The ordinary STL trend humps up around April 2024, about 15% higher than the robust trend at that point. The robust trend runs flatter through it, because the robust fit gave that month a weight of zero, ignoring it completely when estimating the trend and season, and moved its spike into the residual. When you suspect your data contains glitches, and real data usually does, a robust method is a sensible default.
But check what it threw away. Run (robust.weights == 0).sum() and you'll find the robust fit ignored 11 of the 120 months completely, including both of the spikes investigated in lesson 2.2 (June 2022 and April 2024). STL's robust weighting drops any month whose residual is more than six times the typical residual, and this series fits so well that its typical residual is tiny. So some ordinary wobbles get treated as outliers too. That's fine for estimating a trend, but it means "the robust fit ignored it" doesn't prove a month was a glitch.
How strong are the trend and the season?
A decomposition also lets you measure how much of a series is trend and how much is season. A common measure compares the residual's variance with the variance of each component plus the residual. It runs from 0 (no trend or season worth speaking of) to 1 (the component dominates):
def strength(component, resid):
return max(0.0, 1 - resid.var() / (component + resid).var())
print("Strength of season:", round(strength(robust.seasonal, robust.resid), 2))
print("Strength of trend: ", round(strength(robust.trend, robust.resid), 2))The season's strength is about 0.97: this series is almost all season, which is no surprise for a Christmas song. The trend is clearly present but weaker. These two numbers are a quick way to compare many series. For a song with no Christmas connection, the seasonal strength would be close to zero.
Which method should you use?
- Classical decomposition is simple and transparent, and good for a first look. But it fixes the season, loses the ends, and is thrown off by outliers.
- STL handles a changing season, reaches the ends of the data, and with
robust=Trueresists outliers. It's the better default for real data. - STL's
seasonalsetting is a judgment call. Too small and the season soaks up noise; too large and it can't change. Try a few values and check the residuals: they should have no pattern left.
Key ideas
- Classical decomposition (
seasonal_decompose) is exactly the moving-average method from lesson 2.2. Check library functions against a version you understand. - Its weaknesses: a fixed season, a trend that misses the ends, and sensitivity to outliers.
- STL smooths each month's seasonal effect across the years, so the season can change over time.
- Robust STL down-weights outliers so they land in the residual instead of the trend.
- Seasonal and trend strength summarise a decomposition in two numbers between 0 and 1.
- The residuals are the test of any decomposition: no pattern should be left in them.
Try it yourself
- Refit STL with
seasonal=3, thenseasonal=21. How does December's factor change from year to year in each case? Which looks more believable? - Run robust STL on the page views of a song with no seasonal pattern, such as
"Bohemian_Rhapsody"(download it as in lesson 2.2). What is its seasonal strength? - Decompose the levels (
monthly, notlog_m) with STL. Lesson 2.3 found the season closer to additive in levels. Does December's seasonal effect, measured in views, still shrink? - List the months the robust fit ignored completely:
robust.weights[robust.weights == 0]. Do they include the surprises from lesson 2.2? Pick one you haven't investigated and look at its daily data. Is it people, or something else?
Next lesson: Stationary and non-stationary series: why some trends fool you. Random walks, viral moments that do or don't last, and a −0.95 correlation that means nothing.
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