Lesson 7.2Module 7: Smoothing and Granger causality50 minAdvanced

Granger causality: does social-media buzz predict streams?

Test whether one series helps forecast another, the idea Clive Granger won a Nobel prize for. It finds a planted link in simulated data, but on real pageviews it says everything causes everything, unless you remove the common causes. Learn what the test can and can't tell you.

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

Record labels want to know whether buzz drives listening: if people talk about a song today, will they stream it tomorrow? We don't have streaming or social-media data, so we'll use Wikipedia pageviews as a stand-in for attention. Does interest in the TV series Stranger Things lead interest in "Running Up That Hill"? Does one Christmas song lead another? The tool is a test proposed by Clive Granger (1969), who later shared the 2003 Nobel prize in economics for his work on time series. It's widely used, and widely over-interpreted. By the end of this lesson you'll know exactly what it measures, and you'll have seen it say something false with great confidence.

Set up

You need granger_pageviews.csv: daily Wikipedia views, 2016–2025, of the pages for Stranger Things, "Running Up That Hill", "All I Want for Christmas Is You" and Wham!'s "Last Christmas". It was downloaded with the daily_views function from lesson 6.3, so you can fetch other pages the same way.

Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.tsa.stattools import grangercausalitytests

rng = np.random.default_rng(11)

pages = pd.read_csv("granger_pageviews.csv", index_col="date", parse_dates=True)
print("Missing or zero days:", {c: int((pages[c].isna() | (pages[c] == 0)).sum()) for c in pages})
print("Stranger Things zero-view days:", list(pages.index[pages["stranger_things"] == 0].strftime("%d %b %Y")))

The Stranger Things page has 2 missing days and 4 days with zero views, all in early 2016. A page with thousands of daily readers didn't really get none at all on 4 February 2016; these are recording failures, disguised missing values of the kind lesson 5.1 warned about. We'll treat them as missing and interpolate (the log of zero would otherwise break the calculation).

Python
pages = pages.replace(0, np.nan).interpolate()     # a recording failure, not a day nobody looked (lesson 5.1)
log_pages = np.log(pages)
change = log_pages.diff().dropna()                 # daily change in log views

We'll test daily changes in log views, not the levels. Lesson 3.2 showed that two trending series can look related when they aren't, and the same trap catches this test, so the series must be stationary first.

The idea: does the past of x help forecast y?

Granger's definition is about forecasting, not about cause in the everyday sense:

x Granger-causes y if past values of x help forecast y, beyond what y's own past already tells you.

The test is two regressions, like the ones in lesson 6.2:

  1. Restricted: forecast y from its own last p values.
  2. Unrestricted: forecast y from its own last p values and the last p values of x.

If adding x's past reduces the forecast errors by more than chance would, x Granger-causes y. "More than chance" is an F-test, the same test lesson 4.4 used for the weekday dummies. Here it is written out:

Python
def granger(data, y, x, lags=1, robust=False):
    """p-value for 'x Granger-causes y': do lags 1..`lags` of x improve on y's own lags?"""
    table = pd.DataFrame({"y": data[y]})
    for k in range(1, lags + 1):
        table[f"y_lag{k}"] = data[y].shift(k)
        table[f"x_lag{k}"] = data[x].shift(k)
    table = table.dropna()
    X = sm.add_constant(table.drop(columns="y"))
    if robust:                                     # HAC errors, as in lesson 4.4
        fit = sm.OLS(table["y"], X).fit(cov_type="HAC", cov_kwds={"maxlags": 7})
    else:
        fit = sm.OLS(table["y"], X).fit()
    x_terms = ", ".join(f"x_lag{k} = 0" for k in range(1, lags + 1))
    return float(fit.f_test(x_terms).pvalue)

A test with a known answer

First, simulated data where we know the truth. "Buzz" is random. "Streams" follow their own past, plus 0.5 times the buzz from two days earlier. So buzz drives streams, and streams don't drive buzz.

Python
n = 1000
buzz = rng.normal(size=n)
streams = np.zeros(n)
for t in range(2, n):
    streams[t] = 0.6 * streams[t - 1] + 0.5 * buzz[t - 2] + rng.normal()
sim = pd.DataFrame({"buzz": buzz, "streams": streams})

for lags in (1, 2, 3):
    print(f"{lags} lag(s):  buzz -> streams p = {granger(sim, 'streams', 'buzz', lags):.2g}   "
          f"streams -> buzz p = {granger(sim, 'buzz', 'streams', lags):.2f}")

# statsmodels has the same test built in: the column order is [y, x]
check = grangercausalitytests(sim[["streams", "buzz"]], maxlag=[2])
print(f"statsmodels, 2 lags: p = {check[2][0]['ssr_ftest'][1]:.2g}")

With 2 or 3 lags, the test finds the planted link overwhelmingly (p around 10⁻⁵⁰) and correctly finds nothing the other way (p = 0.91 and 0.37). Statsmodels' built-in grangercausalitytests gives the identical p-value, so our function does what we think.

But look at the first line. With 1 lag, the test says buzz does not Granger-cause streams (p = 0.24). Buzz works with a two-day delay, and a test that only looks one day back can't see it. The number of lags is a choice you make before testing, and a wrong choice can hide a real link. A common approach is to choose the lags with an information criterion such as AIC (lesson 4.1 did this for the ADF test), and to check that the answer doesn't depend on the choice.

Real data: does the show lead the song?

Now the summer of 2022. Volume 1 of Stranger Things 4 came out on 27 May, and lesson 6.3 showed "Running Up That Hill" exploding the same day. Before any test, look at the cross-correlation: the correlation between the song's daily change and the show's daily change k days earlier.

Python
summer = change.loc["2022-05-01":"2022-08-31"]
lags = range(-5, 6)
cross = [summer["running_up_that_hill"].corr(summer["stranger_things"].shift(k)) for k in lags]
for k, c in zip(lags, cross):
    if -2 <= k <= 2:
        print(f"song today vs show {k:+d} days: {c:.2f}")

fig, ax = plt.subplots(figsize=(10, 3.2))
ax.bar(list(lags), cross, color=["C1" if k == 0 else "C0" for k in lags])
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_xticks(list(lags))
ax.set_xlabel("k: the show's change k days before the song's (negative: the show's change is after)")
ax.set_ylabel("Correlation")
ax.set_title("Daily changes in views, May to August 2022: song vs show", loc="left")
plt.show()
Bar chart of cross-correlations for k from −5 to 5. The tallest bar, highlighted, is at k = 0, about 0.7. The bar at k = 1 is the next tallest, about 0.44, and k = 2 is about 0.2. The bars at negative k are small: about 0.18 at k = −1, and slightly negative (down to about −0.14) further out.
Bar chart of cross-correlations for k from −5 to 5. The tallest bar, highlighted, is at k = 0, about 0.7. The bar at k = 1 is the next tallest, about 0.44, and k = 2 is about 0.2. The bars at negative k are small: about 0.18 at k = −1, and slightly negative (down to about −0.14) further out.

The biggest correlation, 0.69, is at k = 0: on the days the show's views jumped, the song's jumped too. Next is k = +1 (0.44): the song tends to follow the show by a day. The opposite direction, the show following the song a day later (k = −1), is much weaker, 0.18. So the picture says: mostly same-day, with a one-day echo from show to song. That's plausible: people watch an episode, then look up the song.

Granger's test ignores k = 0 completely. It asks only whether the past of the show helps. Let's run it.

Python
for lags_used in (1, 2, 7):
    p_plain = granger(summer, "running_up_that_hill", "stranger_things", lags_used)
    p_robust = granger(summer, "running_up_that_hill", "stranger_things", lags_used, robust=True)
    p_back = granger(summer, "stranger_things", "running_up_that_hill", lags_used)
    print(f"{lags_used} lag(s): show -> song p = {p_plain:.3f} (robust {p_robust:.3f});   song -> show p = {p_back:.3f}")

With 1 lag, the show's past does help forecast the song (p = 0.037). The song doesn't help forecast the show (p = 0.25). That fits the cross-correlation. But it's fragile:

  • With robust (HAC) errors, which allow for the huge, uneven swings of a viral summer, p rises to 0.17.
  • With 2 or 7 lags, it's no longer significant even with ordinary errors.

Why so weak, when the cross-correlation at k = +1 was 0.44? Because Granger's test asks what the show adds beyond the song's own past. Yesterday's jump in the show came with yesterday's jump in the song (that's the 0.69), and the song's own momentum already carries much of that into today. Only the leftover counts. With 123 days of data, the honest answer is: suggestive, not conclusive. Most of the action happened on the same day, which daily data can't split into cause and effect.

Ten years of data: everything causes everything

What if we use the whole decade, 3,650 days, to get more power?

Python
pairs = [("stranger_things", "running_up_that_hill"), ("all_i_want_for_christmas", "last_christmas")]
for a, b in pairs:
    print(f"{a} -> {b}: p = {granger(change, b, a, 7):.1g};   {b} -> {a}: p = {granger(change, a, b, 7):.1g}")

With ten years of data, the show Granger-causes the song (p = 0.003), and the song Granger-causes the show, even more strongly (p = 0.00003). For the Christmas songs it's more extreme: each "causes" the other with p-values around 10⁻²⁰ to 10⁻²⁹.

Should we conclude that Wham! drives interest in Mariah Carey and Mariah Carey drives interest in Wham!? Both directions at once is possible (it's called feedback, and buzz and streams probably do feed each other). But p-values this small, in both directions, for two songs by different artists, should make you suspicious rather than excited.

The common cause: the calendar

Here's the problem with the Christmas pair. Both songs' views rise every November and December and fall every January. Each song's past "predicts" the other's future simply because both follow the calendar. The calendar is a common cause: a third thing driving both series. Granger's test only compares x and y, so it gives the credit to whichever series happens to move first.

To test for a real link, remove the common cause first. A simple way, from lesson 3.3: take the change from the same day a year earlier (364 days, to keep weekdays aligned), which removes the regular yearly pattern, then the daily change of that, so the series is stationary.

Python
yearly = log_pages - log_pages.shift(364)
no_calendar = yearly.diff().dropna()

a, b = "all_i_want_for_christmas", "last_christmas"
for lags_used in (1, 7):
    print(f"{lags_used} lag(s): Mariah -> Wham! p = {granger(no_calendar, b, a, lags_used):.3f};   "
          f"Wham! -> Mariah p = {granger(no_calendar, a, b, lags_used):.3f}")

fig, axes = plt.subplots(1, 2, figsize=(10, 3.4))
season = log_pages.loc["2023-11-01":"2024-01-15", [a, b]]
axes[0].plot(np.exp(season[a]), label="All I Want for Christmas Is You")
axes[0].plot(np.exp(season[b]), label="Last Christmas")
axes[0].set_yscale("log")
axes[0].set_title("Daily views, Christmas 2023: one calendar", fontsize=10, loc="left")
axes[0].legend(fontsize=8, loc="lower center")
axes[0].tick_params(axis="x", labelrotation=30)
gap = no_calendar.loc["2023-11-01":"2024-01-15", [a, b]]
axes[1].plot(gap[a], linewidth=0.9)
axes[1].plot(gap[b], linewidth=0.9)
axes[1].set_title("After removing last year's pattern", fontsize=10, loc="left")
axes[1].tick_params(axis="x", labelrotation=30)
plt.tight_layout()
plt.show()
Two charts for November 2023 to mid-January 2024. Left: daily views of both songs on a log scale. All I Want for Christmas Is You starts November high, dips for two weeks, then climbs; Last Christmas climbs steadily from a lower start. Both peak at Christmas and drop together in January, ending almost level. Right: the same series after removing last year's pattern and taking daily changes: two jagged lines bouncing around zero with no shared rise and fall, except for a few spikes in the days around Christmas that still line up.
Two charts for November 2023 to mid-January 2024. Left: daily views of both songs on a log scale. All I Want for Christmas Is You starts November high, dips for two weeks, then climbs; Last Christmas climbs steadily from a lower start. Both peak at Christmas and drop together in January, ending almost level. Right: the same series after removing last year's pattern and taking daily changes: two jagged lines bouncing around zero with no shared rise and fall, except for a few spikes in the days around Christmas that still line up.

Removing the calendar changes the picture. Wham! no longer Granger-causes Mariah (p = 0.24 with 1 lag, 0.78 with 7): that link was the calendar all along. But Mariah still Granger-causes Wham! (p = 0.001 with 1 lag, 0.005 with 7), now much weaker than 10⁻²⁹, and in one direction only.

What does that leftover link mean? Perhaps "All I Want for Christmas Is You" really is the season's bellwether: in years when Christmas listening starts early, it shows up on Mariah's page first, and other Christmas songs follow. (The left-hand chart hints at this: Mariah's page is already busy on 1 November, when her song's season traditionally "starts", while Wham!'s builds up later.) Or perhaps there's another common cause we haven't removed. Christmas doesn't fall on the same weekday each year, so a 364-day shift lines up weekdays but not Christmas Day itself, and you can see the leftovers in the right-hand chart: a few spikes around Christmas that both songs still share. Granger's test can't tell those stories apart. That's the most important lesson about it: the test tells you about prediction, and you have to supply the explanation, and the doubt.

What Granger causality is, and isn't

  • It is a test of forecasting: does x's past improve forecasts of y? That's useful in itself. If buzz Granger-causes streams, buzz is worth tracking, whatever the reason.
  • It is not a test of cause in the everyday sense. A common cause that moves x first (a calendar, a news story, a TV release) makes x "Granger-cause" y. Remove the common causes you know about before testing, and remember there may be others.
  • It can't see same-day effects. If both series react within a day, daily data shows no lead. What looks like "no causality" may be causality that is too fast for the data.
  • It is sensitive to choices: the number of lags, plain or robust errors, the period studied, and whether the series were made stationary. Report all of them, and check that your answer survives reasonable changes.
  • With thousands of observations, it finds tiny effects. A p-value tells you an effect probably isn't zero, not that it is big enough to matter.

Key ideas

  • x Granger-causes y if x's past improves forecasts of y beyond y's own past. The test is an F-test comparing two regressions.
  • Test stationary series (here, daily changes in log views), or trends create false links.
  • On simulated data with a planted 2-day lead, the test finds it, and correctly finds nothing in the other direction.
  • In summer 2022 the show and the song moved mostly on the same day, which Granger's test ignores. The one-day lead was suggestive but not robust.
  • Over ten years, every pair Granger-causes the other, both ways. A common cause, the Christmas calendar, explains much of the Christmas pair's link; removing it changes the answer.
  • Granger causality is about prediction, not cause. Its name has misled people for over fifty years.

Try it yourself

  1. In the simulation, change the buzz effect from 0.5 to 0.1, and n from 1000 to 200. Does the test still find it? Try n = 5000.
  2. Add a common cause to the simulation: a random series z that drives buzz today and streams tomorrow, with no direct link from buzz to streams. What does the test say about buzz and streams?
  3. Repeat the summer 2022 test with weekly totals instead of daily views (pages.resample("W").sum()). With weekly data, can a lead of one day be seen at all?
  4. Use daily_views from lesson 6.3 to download the page for Kate Bush herself. Does interest in the artist lead interest in the song, or the other way round?

Next lesson: From forecasting to generating: how AI music models predict what comes next

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