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.

Part of the free course Music as Data: Time Series with Python · taught by Terence D. Agbeyegbe and Tone Agbeyegbe

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.

Python
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.

Python
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()
Three panels of daily views on a log scale, 2016 to 2025. All I Want for Christmas Is You: a regular spike every December, from a few hundred views to tens of thousands. Running Up That Hill: flat at a few hundred a day until a dotted line at May 2022, where it leaps to over 40,000, then falls back over the following months to a level clearly above where it started, with another jump in the last weeks of 2025. Hallelujah: steady at around 2,000 a day, with a huge spike at a dotted line in November 2016 and a smaller bump every December.
Three panels of daily views on a log scale, 2016 to 2025. All I Want for Christmas Is You: a regular spike every December, from a few hundred views to tens of thousands. Running Up That Hill: flat at a few hundred a day until a dotted line at May 2022, where it leaps to over 40,000, then falls back over the following months to a level clearly above where it started, with another jump in the last weeks of 2025. Hallelujah: steady at around 2,000 a day, with a huge spike at a dotted line in November 2016 and a smaller bump every December.

Forecastable tomorrow, or next year?

We'll test two of the simplest forecasts there are. They are the benchmarks any cleverer method must beat:

  • Naive: the forecast for any future day is today's value. "Tomorrow will be like today."
  • Seasonal naive: the forecast is the value on the same day a year earlier (364 days, so weekdays line up, as in lesson 4.4). "This Christmas will be like last Christmas."

A backtest (also called rolling-origin evaluation; Leonard Tashman, 2000, reviews the method) repeats the forecast from every possible starting day, called the origin, and averages the errors. For each horizon h (how many days ahead we forecast), we use every origin from 2017 onwards, so the seasonal naive always has a year of history to copy.

Python
HORIZONS = [1, 7, 30, 90, 180, 364]


def backtest(y, h, method):
    """Average absolute error (in log views) of forecasting h days ahead, from every origin."""
    v = y.to_numpy()
    origins = np.arange(364, len(v) - h)
    if method == "naive":
        forecast = v[origins]                         # today's value
    else:
        forecast = v[origins + h - 364]               # same day, one year before the target
    return np.mean(np.abs(v[origins + h] - forecast))


results = pd.DataFrame({(name, m): [backtest(y, h, m) for h in HORIZONS]
                        for name, y in songs.items() for m in ("naive", "seasonal naive")},
                       index=HORIZONS)
print("Typical miss, as a % of the true views:")
print((100 * (np.exp(results) - 1)).round(0).T.to_string())

fig, axes = plt.subplots(1, 3, figsize=(10, 3.4), sharey=True)
for ax, name in zip(axes, songs):
    for m in ("naive", "seasonal naive"):
        ax.plot(HORIZONS, 100 * (np.exp(results[(name, m)]) - 1), marker="o", label=m)
    ax.set_xscale("log")
    ax.set_xticks(HORIZONS, [str(h) for h in HORIZONS])
    ax.set_title(name, fontsize=9, loc="left")
    ax.set_xlabel("Days ahead")
axes[0].set_ylabel("Typical miss (%)")
axes[0].legend(loc="upper left", fontsize=8)
plt.tight_layout()
plt.show()
Three line charts of typical forecast miss against days ahead (1 to 364, log scale). All I Want for Christmas Is You: the naive forecast's miss climbs from 13% at one day to about 220% at 90 days and 290% at 180 days, then falls back to 29% at 364 days; the seasonal naive stays flat at 29% at every horizon. Running Up That Hill: the naive miss climbs steadily from 11% to 95%; the seasonal naive is flat at 85 to 95%. Hallelujah: the naive miss rises from 12% to 43% at 180 days and falls back to 25% at 364; the seasonal naive is flat at 25 to 28%.
Three line charts of typical forecast miss against days ahead (1 to 364, log scale). All I Want for Christmas Is You: the naive forecast's miss climbs from 13% at one day to about 220% at 90 days and 290% at 180 days, then falls back to 29% at 364 days; the seasonal naive stays flat at 29% at every horizon. Running Up That Hill: the naive miss climbs steadily from 11% to 95%; the seasonal naive is flat at 85 to 95%. Hallelujah: the naive miss rises from 12% to 43% at 180 days and falls back to 25% at 364; the seasonal naive is flat at 25 to 28%.

Three lessons from one chart:

  • Tomorrow, all three songs are equally forecastable. "Tomorrow will be like today" misses by 11 to 13% for every song. Attention changes slowly from day to day: that's the lag-1 autocorrelation of 0.98 from lesson 6.2.
  • A year ahead, the Christmas song is the most forecastable. The seasonal naive misses it by 29% whether you look a week or a year ahead, because every December is like the last. The naive forecast is hopeless at 90 to 180 days, because it forecasts June from December. Which forecast is best depends on the horizon.
  • Running Up That Hill is the least forecastable at long horizons. A year ahead, both benchmarks miss it by about 95%. Copying last year never helps (its seasonal naive is worse than the naive at every horizon), because its history holds no yearly pattern to copy, only one enormous surprise. Hallelujah sits in between: a small Christmas pattern makes the seasonal naive the better choice beyond about a month.

Forecasters judge every method this way: by its relative error, its error divided by a benchmark's. Rob Hyndman and Anne Koehler (2006) built a widely used measure on this idea, the MASE (mean absolute scaled error), which divides by the error of the naive forecast. Below 1 means "better than doing nothing clever". It's a useful habit: a model that sounds sophisticated but can't beat "same as last year" isn't worth using.

The day the hit arrived

Let's zoom in on the surprise.

Python
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()
Daily views of Running Up That Hill on a log scale, May to August 2022. Flat at about 300 to 350 a day until a dotted line at 27 May, labelled Stranger Things 4, volume 1. Views then climb over four days to about 40,000, stay between about 30,000 and 45,000 through June, and dip to about 15,000 in late June. At a second dotted line, 1 July, labelled Volume 2, they rise again to about 30,000, then fall steadily to about 5,000 by the end of August.
Daily views of Running Up That Hill on a log scale, May to August 2022. Flat at about 300 to 350 a day until a dotted line at 27 May, labelled Stranger Things 4, volume 1. Views then climb over four days to about 40,000, stay between about 30,000 and 45,000 through June, and dip to about 15,000 in late June. At a second dotted line, 1 July, labelled Volume 2, they rise again to about 30,000, then fall steadily to about 5,000 by the end of August.

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

Python
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()
Daily views of Hallelujah on a log scale, mid-October 2016 to January 2017. Around 2,000 to 3,000 a day, with a bump to about 10,000 in late October, then a spike to about 160,000 on 11 November and a quick fall. The dashed decay forecast, starting on 30 November, glides smoothly down towards the dotted pre-news level of about 2,200. The actual views instead level off and rise through December to a peak of about 26,000 on Christmas Eve, before falling in January back towards the forecast.
Daily views of Hallelujah on a log scale, mid-October 2016 to January 2017. Around 2,000 to 3,000 a day, with a bump to about 10,000 in late October, then a spike to about 160,000 on 11 November and a quick fall. The dashed decay forecast, starting on 30 November, glides smoothly down towards the dotted pre-news level of about 2,200. The actual views instead level off and rise through December to a peak of about 26,000 on Christmas Eve, before falling in January back towards the forecast.

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.

Python
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

  1. 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?
  2. Repeat the backtest for Running Up That Hill using only origins before May 2022. How forecastable was the song before the hit?
  3. 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.)
  4. 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

Course home
  1. 1Music as a time series

  2. 2Seeing patterns

  3. 3Decomposition and stationarity

  4. 4Testing a time series

  5. 5Missing values

  6. 6Autocorrelation and forecasting

  7. 7Smoothing and Granger causality

  8. 8From time series to AI music