Lesson 4.4Module 4: Testing a time series40 minIntermediate
Testing for seasonality: weekends, Christmas and New Music Friday
Is a repeating pattern real, or chance? Test a huge season, a tiny weekly one and a season that changed overnight, when the music industry moved release day to Friday in July 2015.
A season is any pattern that repeats with a fixed period: every year, every week, every day. Some seasons are obvious. Nobody needs a test to know that a Christmas song peaks in December. Others are small enough that you can't tell by looking whether they're real or chance. This lesson tests three: the Christmas peak, a weekend effect in the same song's daily page views, and the day of the week on which music is released, a season that the industry deliberately changed in 2015.
Set up
You'll need christmas_pageviews.csv (lesson 2.2) and, for the last section, the track-level file data.csv from the Spotify dataset in lesson 2.1. We also use SciPy, which was installed alongside statsmodels.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
from scipy import stats
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
log_daily = np.log(views)The recipe
Every seasonality test follows the same three steps:
- Remove the trend (and any other season), so that it can't masquerade as the one you're testing.
- Group the values by season: by month for a yearly season, by weekday for a weekly one.
- Test whether the groups differ by more than chance would produce.
For step 3, we'll use two tests. The Kruskal–Wallis test asks whether the groups come from the same distribution. It uses only the ranks of the values, so a few extreme values (like the spikes from lesson 2.2) can't dominate it. A regression with seasonal dummies puts one on/off variable for each month or weekday into a regression, and an F-test asks whether they're all zero together. The regression is more flexible, as you'll see. Both have the null hypothesis: no season.
A huge season: Christmas
First, a test we know the answer to. Remove the trend with the centred 2×12 moving average from lesson 2.2, group the detrended values by month, and test:
log_m = np.log(views.resample("MS").sum())
weights = np.array([0.5] + [1] * 11 + [0.5]) / 12
trend = log_m.rolling(13, center=True).apply(lambda w: np.dot(w, weights), raw=True)
detrended = (log_m - trend).dropna()
by_month = [g.values for _, g in detrended.groupby(detrended.index.month)]
print(f"Kruskal-Wallis, Christmas song by month: p = {stats.kruskal(*by_month).pvalue:.1e}")
rng = np.random.default_rng(0)
no_season = pd.Series(rng.normal(size=len(detrended)), index=detrended.index)
by_month_ns = [g.values for _, g in no_season.groupby(no_season.index.month)]
print(f"Kruskal-Wallis, random numbers by month: p = {stats.kruskal(*by_month_ns).pvalue:.2f}")The Christmas song's p-value is tiny, as it should be. Alongside it, a negative control: random numbers with the same dates, where there is no season by construction. Their p-value is 0.09: above the usual 0.05 cut-off, so no evidence of a season, though it's a reminder that chance alone can come fairly close. Running a test where you know the answer, in both directions, is a good habit before trusting it on a question you don't know the answer to.
A tiny season: weekends
Does the song get more page views at weekends? This time the trend isn't the only thing in the way: the huge yearly season is too. One tool removes both. A centred 7-day moving average contains each day of the week exactly once, so it cancels out any weekly pattern, while following everything slower: the trend and the Christmas rise and fall. Subtracting it leaves the weekly pattern plus noise.
weekly = (log_daily - log_daily.rolling(7, center=True).mean()).dropna()
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
df = pd.DataFrame({"x": weekly, "day": pd.Categorical(weekly.index.day_name().str[:3], categories=days)})
effect = df.groupby("day", observed=True)["x"].agg(["mean", "sem"])
factor = np.exp(effect["mean"])
fig, ax = plt.subplots(figsize=(10, 3.4))
ax.bar(days, (factor - 1) * 100, yerr=1.96 * effect["sem"] * 100, capsize=4, ecolor="grey",
color=["C1" if d in ("Sat", "Sun") else "C0" for d in days])
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_ylabel("% above or below the 7-day average")
ax.set_title("A small weekend lift in daily page views (bars show 95% intervals)")
plt.show()
groups = [g["x"].values for _, g in df.groupby("day", observed=True)]
print(f"Kruskal-Wallis by weekday: p = {stats.kruskal(*groups).pvalue:.1e}")
print((factor - 1).mul(100).round(1))The weekend effect is real: Saturday and Sunday are each about 3% above the weekly average, and Monday to Thursday about 1 to 2% below. The p-value is astronomically small. With ten years of daily data, about 3,650 values, even a 3% difference is impossible to explain by chance.
Significant isn't the same as important
But is it important? December multiplies the song's views by about 17 (lesson 3.1). The weekend multiplies them by about 1.03. Both are "statistically significant"; only one matters for anyone planning around this song. A p-value tells you whether an effect is there, not whether it's big. Always report the size of the effect alongside the test.
A fairer test: allowing for memory
The tests so far assume each day is independent of the others, and lesson 4.2 taught us to check that. The weekly series has a lag-1 autocorrelation of about 0.2: neighbouring days are related. When that's true, ordinary tests are overconfident, because 3,650 related days carry less information than 3,650 independent ones.
The regression version of the test can fix this. HAC standard errors (heteroskedasticity- and autocorrelation-consistent, often called Newey–West after the economists who popularised them in 1987) adjust the test for memory in the data:
model = smf.ols("x ~ C(day)", data=df)
plain = model.fit()
robust = model.fit(cov_type="HAC", cov_kwds={"maxlags": 14})
print(f"F-test, assuming independent days: p = {plain.f_pvalue:.1e}")
print(f"F-test, allowing for memory (HAC): p = {robust.f_pvalue:.1e}")Both p-values are tiny, so the weekly season survives. When an effect is this clear, the correction doesn't change the verdict. When an effect is borderline, it often does, and the corrected version is the one to believe.
A season that changed overnight: New Music Friday
For decades, new music came out on different days in different countries: Tuesday in the US, Monday in the UK, Friday in Australia and Germany. On 10 July 2015, the industry moved to a single Global Release Day: Friday, everywhere. That's a weekly season, in the days on which music is released, that was changed by a decision. Can we see it in the data?
The Spotify track file has a release date for each of its 170,000 tracks. Before counting weekdays, though, we need to check the dates.
tracks = pd.read_csv("data.csv", usecols=["release_date", "year"])
exact = tracks[tracks["release_date"].str.len() == 10].copy() # full dates only, not just a year
exact["date"] = pd.to_datetime(exact["release_date"])
print(f"{len(exact):,} of {len(tracks):,} tracks have a full release date")
print(f"Share of those dated 1 January: {(exact['date'].dt.strftime('%m-%d') == '01-01').mean():.0%}")Almost three in ten "full" dates are 1 January, far more than the 1 in 365 you'd expect. These are almost certainly placeholders: when only the year was known, a database filled in 1 January. Kept in, they would add a fake spike to whichever weekday 1 January happened to fall on that year. (In 2010, that was a Friday.) So we drop them, then measure each year's share of releases by weekday:
exact = exact[exact["date"].dt.strftime("%m-%d") != "01-01"]
exact["day"] = exact["date"].dt.day_name().str[:3]
share = pd.crosstab(exact["year"], exact["day"], normalize="index").loc[1995:2020]
fig, ax = plt.subplots(figsize=(10, 3.6))
for day, colour in [("Tue", "C0"), ("Mon", "C3"), ("Fri", "C1")]:
ax.plot(share.index, share[day] * 100, marker="o", markersize=3, linewidth=2, color=colour, label=day)
ax.axvline(2015.5, color="grey", linestyle="--", linewidth=1)
ax.set_ylabel("% of the year's releases")
ax.set_title("Release day moves to Friday: Global Release Day, July 2015")
ax.legend(fontsize=8, loc="upper left")
plt.show()Until 2014, Tuesday dominates, and Monday is second: the US and UK release days. Then the lines cross. From 2016, about 70% of releases come out on a Friday, and Tuesday falls to about 5%. 2015 itself is the year of the switch, so let's split it at 10 July:
y2015 = exact[exact["year"] == 2015]
before = y2015[y2015["date"] < "2015-07-10"]
after = y2015[y2015["date"] >= "2015-07-10"]
print(f"2015, before 10 July: {(before['day'] == 'Fri').mean():.0%} on a Friday ({len(before)} tracks)")
print(f"2015, from 10 July: {(after['day'] == 'Fri').mean():.0%} on a Friday ({len(after)} tracks)")From 15% to 75%, in the same year. Releases are counts, not measurements, so the right test here is the chi-squared test. It compares counts in categories with what you'd expect if nothing were going on. First, did the weekly pattern change between 2010–2014 and 2016–2020?
exact["period"] = pd.cut(exact["year"], [2009, 2014, 2015, 2020], labels=["2010-14", "2015", "2016-20"])
table = pd.crosstab(exact["period"], exact["day"]).loc[["2010-14", "2016-20"]] # leave out 2015, the switch year
chi2, p, dof, _ = stats.chi2_contingency(table)
print(table[["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]])
print(f"Chi-squared = {chi2:,.0f} with {dof} degrees of freedom, p = {p:.1e}")The chi-squared statistic is over 6,500; with 6 degrees of freedom, anything above about 12.6 would be significant at 5%. The p-value is so small that the computer rounds it to zero. The weekly season of releases didn't just change, it flipped. This is a break in a seasonal pattern, caused by a policy decision on a known date. In most data the dates of breaks aren't known in advance, and finding them is a subject of its own, coming later in this course.
Two caveats worth stating. This dataset is Spotify's selection of popular tracks, not every release, and re-issued albums can carry the re-issue date rather than the original one. Neither would create a jump of this size in a single month, but both are reasons to call these shares estimates.
Which test when?
- Comparing measurements across months or weekdays: Kruskal–Wallis (robust to outliers) or a regression with dummies and an F-test.
- Comparing counts across categories: a chi-squared test.
- Data with memory: use HAC standard errors in the regression version, or test on residuals that pass lesson 4.2's white-noise check.
- Before any of them: remove the trend and any other season.
- After any of them: report how big the season is, not just the p-value.
Key ideas
- Testing for seasonality: remove the trend, group by season, test whether the groups differ.
- A centred moving average as long as the season removes that season exactly while keeping slower movements. That makes it a neat way to isolate a short season (weekly) from a long one (yearly).
- Run a negative control, a series with no season, to check that a test behaves.
- Statistically significant isn't important: a 3% weekend effect and a 17-fold Christmas effect are both significant.
- Memory in the data makes ordinary tests overconfident. HAC (Newey–West) standard errors correct for it.
- Seasons can change: in July 2015, the weekly pattern of music releases moved from Tuesday to Friday almost overnight.
- Check dates for placeholders like 1 January before counting by day.
Try it yourself
- Run the weekday test on the daily views for November to January only, then for the rest of the year. Is the weekend effect the same size in and out of the Christmas season?
- Compute the weekend effect separately for each year. Is it stable, or does it come and go?
- Use a regression with month dummies on the monthly
detrendedseries and compare its F-test p-value with the Kruskal–Wallis result. - Look at the share of releases by weekday in the 1970s. Something odd is going on. Can you suggest what?
Next: Module 5, handling missing values (coming soon).
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