Lesson 2.2Module 2: Seeing patterns40 minBeginner
Trend, seasonality and noise: the Christmas song that comes back every year
Download ten years of daily Wikipedia page views for 'All I Want for Christmas Is You' and pull the series apart into its three ingredients: a long-run trend, a yearly season and the noise that's left, which sometimes turns out to be news.
Every November, one song starts climbing back up the charts: Mariah Carey's "All I Want for Christmas Is You", first released in 1994. It's the clearest seasonal pattern in pop music. In this lesson you'll download ten years of real daily data about it and learn to see the three ingredients that almost every time series is made of: trend, seasonality and noise.
Three ingredients
Lesson 1.1 simulated a new single's streams as a trend, plus a weekly rhythm, plus noise. Real series are built from the same three ingredients, and naming them is the first step in any analysis:
- Trend: the long-run direction, up or down, over years. Lesson 2.1's rising loudness was a trend.
- Seasonality: a pattern that repeats over a fixed period, such as every year, week or day: Christmas music in December, more streams on Fridays, more listening in the evening.
- Noise (also called the irregular or residual part): everything else. Day-to-day randomness, but also one-off events that aren't part of any regular pattern.
Seasonality needs data measured more often than its period. Lesson 2.1's data had one value per year, so it couldn't show anything that happens within a year. For that you need daily or monthly data.
Get the data
We can't get daily Spotify streams for free, but Wikipedia page views are a good free stand-in for public interest, and the Wikimedia Foundation publishes them for every article, every day, since July 2015. The data is free to use, and no account or key is needed:
import json
import urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
article = "All_I_Want_for_Christmas_Is_You"
url = ("https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/"
f"en.wikipedia/all-access/user/{article}/daily/20160101/20251231")
request = urllib.request.Request(url, headers={"User-Agent": "music-data-course-example/1.0 (learning pandas)"})
with urllib.request.urlopen(request) as response:
items = json.load(response)["items"]
views = pd.Series({pd.Timestamp(i["timestamp"][:8]): i["views"] for i in items}, name="views")
views.index.name = "date"
views.to_csv("christmas_pageviews.csv") # keep a copy, so you don't need to download it again
print(len(views), "days:", views.index.min().date(), "to", views.index.max().date())
print(views.describe().round(0))A few details in that code:
userin the address asks for views by people, leaving out known automated bots.- Wikimedia asks every program that uses its service to say who it is in the
User-Agentheader. For your own projects, put your project name and an email address there. - If you're offline, you can download the same data as a file: christmas_pageviews.csv. Then use
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"].
Notice the summary: the median day has a few hundred views, but the busiest day has tens of thousands. A series that spans that range calls for a log scale.
Look first
ax = views.plot(figsize=(10, 3.6), linewidth=0.7, logy=True)
ax.set_ylim(top=250_000) # leave room above the peaks for a label
ax.annotate("Dec 2019: reaches No. 1 in the US for the first time, 25 years after release",
xy=(pd.Timestamp("2019-12-17"), 44_634), xytext=(pd.Timestamp("2016-03-01"), 110_000),
arrowprops={"arrowstyle": "->", "color": "C1"}, color="C1", fontsize=8)
ax.set_xlabel("")
ax.set_ylabel("Daily page views (log scale)")
ax.set_title("'All I Want for Christmas Is You' on English Wikipedia, 2016–2025")
plt.show()All three ingredients are visible at once. The seasonal spike every December is unmissable. Underneath it, the summer baseline creeps upward over the decade: a trend. And everything wobbles from day to day: noise. The 2019 spike also arrives a week before Christmas, unlike the others. Keep that in mind.
Seeing the season: one line per year
Daily data is noisy, so let's add it up by month and draw a seasonal plot: one line per year, with the months of the year along the bottom. If a pattern repeats every year, the lines will have the same shape.
monthly = views.resample("MS").sum() # "MS" = month start: total views in each calendar month
by_year = pd.DataFrame({"year": monthly.index.year, "month": monthly.index.month, "views": monthly.values})
table = by_year.pivot(index="month", columns="year", values="views")
ax = table.plot(figsize=(10, 3.8), logy=True, linewidth=1.3, colormap="plasma")
ax.set_xticks(range(1, 13), ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
ax.set_xlabel("")
ax.set_ylabel("Views per month (log scale)")
ax.set_title("The same shape every year: quiet in spring and summer, rising from October, peaking in December")
ax.legend(ncol=5, fontsize=7, loc="upper left")
plt.show()
print((table.mean(axis=1) / 1000).round(0)) # average views per month, in thousandsTen years, one shape. The average December gets about 30 times the views of an average summer month. The season doesn't switch on overnight, either: interest rises through October and November, the "it's too early for Christmas music" weeks, before the December peak.
Seeing the trend: a moving average
To see the trend, we need to remove the season. The classic tool is a moving average that spans exactly one full season: each month is replaced by the average of the twelve months around it. Because every window contains one of each month, the December spikes are averaged away, and only the slow movement remains.
There's one wrinkle. Twelve is an even number, so a 12-month window has no middle month. The standard fix is a centred 2×12 moving average: average 13 months, giving the two end months half weight.
weights = np.array([0.5] + [1] * 11 + [0.5]) / 12 # 13 weights that add up to 1
def centred_2x12(series):
return series.rolling(13, center=True).apply(lambda window: np.dot(window, weights), raw=True)
trend = centred_2x12(monthly)
ax = monthly.plot(figsize=(10, 3.6), logy=True, linewidth=1, alpha=0.6, label="Monthly views")
trend.plot(ax=ax, linewidth=2.5, color="C1", label="Trend (centred 2×12 moving average)")
ax.set_xlabel("")
ax.set_ylabel("Views per month (log scale)")
ax.set_title("Removing the season reveals the trend")
ax.legend(loc="upper left", fontsize=8)
plt.show()The trend line has no December spikes left in it, and you can see the slow story underneath: interest in the article grew for most of the decade. Look closely, though, and the trend steps up around 2019–20 and bumps up in 2024. A moving average spreads one unusually big month (the record-breaking December 2019, and a strange spike in April 2024 that we'll investigate below) across the whole year around it. Moving averages are simple and useful, but they're not immune to outliers. The line also stops six months before each end of the data, because a centred 13-month window needs six months on each side. That's the price of centring: you can't see the trend at the very edges of your data.
Be careful about what the trend means. This is interest in a Wikipedia article, which is only a proxy for interest in the song. Anything that changes how people use Wikipedia changes the series too. In 2025 the Wikimedia Foundation reported that human page views across Wikipedia were falling, and suggested that people getting answers directly from search engines and AI tools was one reason. So a dip at the end of the trend might reflect Wikipedia as much as the song.
Pulling it apart: trend, season and noise
Now we can take the series apart completely. We'll work with the log of the monthly views, for the same reason we've been plotting on a log scale: the series runs from about 6,000 views in a quiet month to nearly 500,000 in a busy December, and on the log scale a change means the same thing (the same percentage) at any level. On the log scale we write:
log(views) = trend + season + noise
That's a modelling assumption: it says the season multiplies the views by the same factor every year. Whether that's true is a question you can test, and lesson 2.3 does exactly that. The answer for this song is not what you might expect.
log_m = np.log(monthly)
log_trend = centred_2x12(log_m)
detrended = log_m - log_trend # season + noise
season = detrended.groupby(detrended.index.month).mean() # the average for each calendar month
season = season - season.mean() # centred, so the season averages to zero
noise = detrended - season.reindex(detrended.index.month).values
print("Seasonal factors (x times the trend):")
print(np.exp(season).round(2))The seasonal factors say how far each month typically sits above or below the trend. December's factor is far above 1, and the spring and summer months are below it.
fig, ax = plt.subplots(3, 1, figsize=(10, 6.4))
ax[0].plot(log_m.index, log_m, linewidth=1, alpha=0.6, label="log(views)")
ax[0].plot(log_trend.index, log_trend, linewidth=2.2, color="C1", label="Trend")
ax[0].set_title("1. Trend")
ax[0].legend(loc="upper left", fontsize=8)
ax[1].bar(range(1, 13), season.values, color="C2")
ax[1].set_xticks(range(1, 13), ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"])
ax[1].set_title("2. Season: each month's typical distance from the trend (log scale)")
ax[2].bar(noise.index, noise.values, width=20, color="C3")
ax[2].axhline(0, color="grey", linewidth=0.8)
ax[2].set_title("3. Noise: what's left over")
plt.tight_layout()
plt.show()
print("Biggest surprises:")
print(noise.abs().nlargest(4).round(2))That's a decomposition: one series split into three. Module 3 does it with a single function call. Doing it by hand first shows exactly what that function does.
Reading the noise
Noise is what the trend and the season can't explain, and it's worth reading rather than ignoring. Look at the biggest surprises the code listed. They aren't in December at all: they're April 2024 and June 2022, months when the series was about three times and twice what trend and season predict.
Meanwhile December 2019, when the song topped the US chart for the first time, doesn't stand out. The December season is so large that even a record-breaking week barely moves the monthly total away from what the season predicts. Whether something counts as a surprise depends on the scale you look at. At the daily scale, 17 December 2019 is obvious. At the monthly scale, it disappears into the season.
So what happened in April 2024 and June 2022? Zooming in to the daily data shows a single huge day each time: about 30,000 views on 24 April 2024, and about 7,300 on 4 June 2022. Wikimedia splits page views by how people reached the article (desktop browser, mobile browser or the Wikipedia app), and comparing them is a good forensic test:
def daily_views(access, start, end):
url = ("https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/"
f"en.wikipedia/{access}/user/{article}/daily/{start}/{end}")
request = urllib.request.Request(url, headers={"User-Agent": "music-data-course-example/1.0 (learning pandas)"})
with urllib.request.urlopen(request) as response:
return [i["views"] for i in json.load(response)["items"]]
for start, end in [("20220603", "20220605"), ("20240423", "20240425")]:
print(f"{start} to {end} (the day before, the spike, the day after):")
for access in ["desktop", "mobile-web", "mobile-app"]:
print(f" {access:<11}", daily_views(access, start, end))The two spikes look completely different:
- June 2022 rose on every channel, including the app (from about 20 views to about 300), and faded over several days. That's what a real burst of human interest looks like, perhaps a news story or a post that went viral. Finding out which is the next step: search the news for that date.
- April 2024 came mostly from desktop browsers, and the app didn't move at all. Real people use all three. A spike that skips the app entirely looks much more like automated traffic that Wikipedia's bot filter didn't catch. We can't prove it from this data, but it's strong enough evidence that you'd treat that day with suspicion before using it.
That's the real value of the noise. Some of it is genuine randomness. But a large leftover means something happened: a news event, a chart record, a viral post, or a problem with the data itself. Every one of those is worth knowing about, and you only find them by modelling the trend and the season first.
Key ideas
- Most time series are a mix of trend (long-run direction), seasonality (patterns that repeat over a fixed period) and noise (everything else).
- You can only see seasonality if you measure more often than the season repeats: monthly or daily data for a yearly season.
- A seasonal plot (one line per year) shows whether the pattern really repeats.
- A moving average spanning exactly one season removes the season and reveals the trend. For an even period like 12 months, use a centred 2×12 average. It can't reach the ends of the data.
- Working on the log scale turns a season that multiplies into one that adds. Whether the season really does multiply is something to test (lesson 2.3).
- Noise isn't always random: big leftovers point to real events or to data problems. Whether something stands out depends on the time scale.
- Free data is often a proxy (page views stand in for interest). Changes in the proxy itself can look like changes in what you care about.
Try it yourself
- Is there a weekly season too? Take the days from March to September only (
views[views.index.month.isin(range(3, 10))]) and compare the median views on each day of the week with.groupby(...index.day_of_week).median(). Is the pattern strong or weak? - Swap in another seasonal song: try
"Last_Christmas"or"Jingle_Bell_Rock". Are the seasonal factors bigger or smaller than Mariah Carey's? - Try a song with no season at all, such as
"Bohemian_Rhapsody". What does the seasonal plot look like? Can you find any one-off spikes in the noise, and match them to news events? - Replace the 2×12 moving average with a plain 12-month rolling mean (
monthly.rolling(12).mean()). Plot both. Why does the plain version lag behind?
Next lesson: Additive or multiplicative? Letting the data decide. We test the assumption behind this lesson's decomposition, and the Christmas song surprises us.
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