Lesson 6.3Module 6: Autocorrelation and forecasting50 minIntermediate
How forecastable is a hit?
Backtest simple forecasts on three songs' Wikipedia pageviews. A Christmas song is predictable a year ahead; a viral revival is not, and the day it arrives is a 15-standard-deviation surprise. But what happens after a hit is partly forecastable, and whether the new fans stay is the real question.
On 27 May 2022, Netflix released the fourth series of Stranger Things, with Kate Bush's 1985 song "Running Up That Hill" at the centre of an episode. Within days, a 37-year-old song was a worldwide number one. Could anyone have forecast that from the song's own history? This lesson answers with the forecaster's main tool, the backtest: pretend it's an earlier date, forecast, and score the forecast against what actually happened. We'll compare three songs: one seasonal, one revived by television, and one shaken by sad news.
Set up
You need christmas_pageviews.csv (lesson 2.2) and the daily Wikipedia pageviews for two more songs. The code below downloads them the same way as lesson 2.2, or you can download hit_pageviews.csv and put it in your working folder.
import json
import urllib.parse
import urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
ARTICLES = {"running_up_that_hill": "Running_Up_That_Hill",
"hallelujah": "Hallelujah_(Leonard_Cohen_song)"}
def daily_views(article):
"""Daily user views of an English Wikipedia article, 2016-2025 (as in lesson 2.2)."""
url = ("https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/"
f"en.wikipedia/all-access/user/{urllib.parse.quote(article, safe='')}/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"]
return pd.Series({pd.Timestamp(i["timestamp"][:8]): i["views"] for i in items})
try:
hits = pd.read_csv("hit_pageviews.csv", index_col="date", parse_dates=True)
except FileNotFoundError:
hits = pd.DataFrame({name: daily_views(a) for name, a in ARTICLES.items()}).rename_axis("date")
hits.to_csv("hit_pageviews.csv")
xmas = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
songs = {
"All I Want for Christmas Is You": np.log(xmas),
"Running Up That Hill": np.log(hits["running_up_that_hill"]),
"Hallelujah": np.log(hits["hallelujah"]),
}
for name, y in songs.items():
print(f"{name:32s} {len(y):,} days, median {np.exp(y.median()):,.0f} views a day, "
f"busiest {np.exp(y.max()):,.0f} on {y.idxmax():%d %b %Y}")As in earlier lessons, we work with the log of views, so an error of 0.1 means "about 10% out" whether the song has 300 views a day or 30,000.
fig, axes = plt.subplots(3, 1, figsize=(10, 6.6), sharex=True)
for ax, (name, y) in zip(axes, songs.items()):
ax.plot(np.exp(y), linewidth=0.6)
ax.set_yscale("log")
ax.set_title(name, loc="left", fontsize=10)
axes[1].axvline(pd.Timestamp("2022-05-27"), color="C1", linestyle=":")
axes[2].axvline(pd.Timestamp("2016-11-10"), color="C1", linestyle=":")
axes[1].set_ylabel("Daily views (log scale)")
plt.tight_layout()
plt.show()The day the hit arrived
Let's zoom in on the surprise.
ruth = songs["Running Up That Hill"]
change = ruth.diff() # daily change in log views
before = change[:"2022-05-26"]
jump = change["2022-05-27"]
print(f"26 May 2022: {np.exp(ruth['2022-05-26']):,.0f} views. 27 May: {np.exp(ruth['2022-05-27']):,.0f} views "
f"({np.exp(jump):.1f} times as many)")
print(f"Typical daily change before then: {before.std():.2f} (standard deviation of log change)")
print(f"So the jump was {jump / before.std():.1f} standard deviations")
print(f"Chance of a jump that big if daily changes were normal: {norm.sf(jump / before.std()):.0e}")
sd = change.std()
big = (change.abs() > 5 * sd).sum()
expected = len(change.dropna()) * 2 * norm.sf(5)
print(f"Days with a change over 5 standard deviations: {big} (a normal distribution expects {expected:.3f})")
fig, ax = plt.subplots(figsize=(10, 3.4))
window = ruth["2022-05-01":"2022-08-31"]
ax.plot(np.exp(window))
ax.set_yscale("log")
for day, label in [("2022-05-27", "Stranger Things 4, volume 1"), ("2022-07-01", "Volume 2")]:
ax.axvline(pd.Timestamp(day), color="C1", linestyle=":")
ax.text(pd.Timestamp(day) + pd.Timedelta(days=1), 0.05, label, transform=ax.get_xaxis_transform(),
color="C1", fontsize=9)
ax.set_title("Running Up That Hill, daily views, May to August 2022", loc="left")
ax.set_ylabel("Views (log scale)")
plt.show()Views went from 349 to 3,673 in a day, about ten times as many: a jump of 14.9 standard deviations. If daily changes followed a normal (bell-curve) distribution, a jump that large would have a probability of about 10⁻⁵⁰, which is to say it would never happen. Yet the song's history contains 19 days with changes over 5 standard deviations, where a normal distribution expects about 0.002. Attention data has fat tails: extreme days are far more common than the bell curve allows. Benoit Mandelbrot (1963) made the same discovery about cotton prices, and it's true of streams, sales and social-media shares too.
So, from its own history, this hit was not forecastable at all. Nothing in the 2,300-odd days of our file before 27 May hints at it. But the hit wasn't unforecastable to everyone. Netflix announced the release date months ahead, and anyone who had seen the episode knew the song was in it. The information needed was outside the series. That's the general lesson: a time series can forecast its own habits, but not events it has never seen. Forecasters handle known future events by adding them to the model as extra inputs. That's Module 7's subject: does one series (social-media buzz, a TV schedule) help predict another?
The second wave, after volume 2 on 1 July, is smaller and briefer: once a song is famous, the next push moves it less. You can see the same thing at the far right of the first chart. The final series of Stranger Things arrived in late 2025, and views roughly tripled to about 4,000 to 6,000 a day: a real jump, but nothing like 2022.
After the hit: what is forecastable
Once a shock has happened, how fast it fades is partly forecastable. Hallelujah gives a clean example. Leonard Cohen's death was announced on 10 November 2016, and views of the song's page leapt from a typical 2,159 a day to 159,531 on 11 November. (The smaller bump three weeks earlier, in the chart below, came with the release of his last album, You Want It Darker, on 21 October.) A simple model of the fading: the extra views, on a log scale, shrink by the same fraction every day. That's an AR(1), from lesson 6.2, applied to the excess over normal:
excess today = ρ × excess yesterday
hal = songs["Hallelujah"]
normal = hal["2016-01-01":"2016-10-31"].median() # typical log views before the news
excess = hal - normal
# Estimate rho from the first three weeks after the peak (13-30 November), by least squares
fit = excess["2016-11-13":"2016-11-30"].to_numpy()
rho = (fit[:-1] @ fit[1:]) / (fit[:-1] @ fit[:-1])
half_life = np.log(0.5) / np.log(rho)
print(f"Before the news: {np.exp(normal):,.0f} views a day. rho = {rho:.3f}, "
f"so the excess halves every {half_life:.1f} days")
# Forecast from 30 November onwards, and compare with what happened
future = hal["2016-12-01":"2017-01-31"].index
forecast = normal + excess["2016-11-30"] * rho ** np.arange(1, len(future) + 1)
actual = hal[future]
for day in ["2016-12-05", "2016-12-15", "2016-12-24", "2017-01-15", "2017-01-31"]:
print(f"{pd.Timestamp(day):%d %b %Y}: forecast {np.exp(forecast[future.get_loc(day)]):6,.0f}, "
f"actual {np.exp(actual[day]):6,.0f}")
lift = [np.exp(hal[f"{yr}-12-15":f"{yr}-12-26"].median() - hal[f"{yr}-10"].median()) for yr in range(2017, 2026)]
print(f"In 2017-2025, views in 15-26 December were {min(lift):.1f} to {max(lift):.1f} times October's")
fig, ax = plt.subplots(figsize=(10, 3.4))
ax.plot(np.exp(hal["2016-10-15":"2017-01-31"]), label="actual")
ax.plot(future, np.exp(forecast), linestyle="--", label="decay forecast from 30 Nov")
ax.axhline(np.exp(normal), color="grey", linestyle=":", linewidth=1)
ax.set_yscale("log")
ax.set_title("Hallelujah after Leonard Cohen's death", loc="left")
ax.set_ylabel("Views (log scale)")
ax.legend(loc="upper right")
plt.show()Through late November, the excess views halved about every 7 days. A forecast built on that fading is too low from the start of December, and the gap grows: on 15 December it predicts 2,804 views against 14,878 actual, and on Christmas Eve 2,397 against 26,037, more than ten times as many. The reason is in the last printed line: Hallelujah is a Christmas song too. Every December since, its views have risen to 1.4 to 2.7 times October's level. A model that knew the seasonal pattern as well as the decay would have done much better. Our file starts in January 2016, so we can't measure the 2016 Christmas pattern from earlier years, but a forecaster with a longer history could have.
By late January the views are back close to normal. In the language of lesson 3.2, Cohen's death was a temporary shock: a huge spike, then back to the old level.
Did the new fans stay?
Running Up That Hill tells a different story.
ruth_views = hits["running_up_that_hill"]
print(f"Year before the series (June 2021 - May 2022): median {ruth_views['2021-06-01':'2022-05-26'].median():,.0f} a day")
for yr in ["2023", "2024", "2025"]:
print(f"{yr}: median {ruth_views[yr].median():,.0f} a day")
hal_views = hits["hallelujah"]
print(f"Hallelujah, Jan-Oct 2016: {hal_views['2016-01':'2016-10'].median():,.0f}; "
f"Feb-Oct 2017: {hal_views['2017-02':'2017-10'].median():,.0f}")In the year before Stranger Things, the page had a median of about 360 views a day. In 2023 the median was 1,021, and even in 2025, three years on, it was 742, about twice the old level. Part of the shock was permanent: the song found a new, younger audience that stayed. Hallelujah's median, by contrast, went from 2,159 before the news to 2,300 the following year, almost unchanged.
This is the forecaster's real question about a hit. The spike itself can't be forecast from the series. But the day after it starts, the useful questions are: how fast will it fade, and to what level? Lesson 4.1's tests asked the same question of loudness: does a shock fade away, or does it shift the level for good? The answer here differs from song to song, and you can only tell by watching the data after the shock.
So, how forecastable is a hit?
- The arrival: not at all from the song's own history. It's a fat-tailed surprise that needs outside information.
- The first weeks: partly. Attention fades at a fairly steady rate, so an AR(1) on the excess gives a reasonable short-range forecast, as long as nothing else (like Christmas) is going on.
- The long run: it depends whether the hit created a new audience. Running Up That Hill kept about twice its old level; Hallelujah went back to normal.
- Regular patterns: very forecastable. The Christmas song is predictable to about ±30% a whole year ahead.
Key ideas
- A backtest forecasts from many past origins and scores each forecast against what happened. It's the honest way to measure forecastability.
- Always compare with benchmarks: naive (same as today) and seasonal naive (same as last year). Which is best depends on the horizon.
- Relative error = your error ÷ the benchmark's error. Below 1 means you've added something.
- Attention data has fat tails: Running Up That Hill had 19 days with changes over 5 standard deviations, where the normal distribution expects 0.002.
- A series can't forecast events it has never seen. Outside information (a release date) is needed, which is the subject of Module 7.
- After a shock, an AR(1) on the excess gives a half-life. But the shock can also be permanent in part, and only time tells which.
Try it yourself
- Add a third benchmark to the backtest: the average of the last 28 days. Does it beat the naive forecast at any horizon, for any song?
- Repeat the backtest for Running Up That Hill using only origins before May 2022. How forecastable was the song before the hit?
- Fit the decay model to Running Up That Hill from 15 July 2022, after the second wave, using the June 2021–May 2022 median as "normal". What half-life do you get? Why might the forecast go wrong in the long run? (Hint: look at the 2023 median.)
- Download the pageviews for a song that you know went viral, using
daily_views. Find the day it arrived, and measure the jump in standard deviations.
Next lesson: Smoothing: moving averages and loudness envelopes
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
6Autocorrelation and forecasting
7Smoothing and Granger causality
8From time series to AI music