Correlation of the two levels: 0.93
Correlation vs cointegration: simulating butter prices and the S&P 500

I want to show that sometimes, even though you get a high correlation, it can be only a spurious correlation, and how you should handle that issue to figure out whether there is indeed a true relationship between two time series. The butter comes from a well-known example where butter production in Bangladesh “explained” the S&P 500.
Normally, when you focus on the levels of two series that both drift over time, they will be correlated. I simulate a butter price and an S&P 500 that are unrelated, but both drift upward. Their correlation is 0.93, but they fail a cointegration test.
Simulating the data
I simulate both series, so I know that they are unrelated. Each month, each series adds a fixed drift and some noise,
\[B_t = B_{t-1} + 0.10 + \varepsilon_t, \qquad S_t = S_{t-1} + 0.30 + \eta_t,\]
where \(B_t\) is the butter price, starting at 50, and \(S_t\) is the S&P 500, starting at 100. The noise has a standard deviation of 1 for butter and 2 for the S&P 500, over 600 months.
import numpy as np
import matplotlib.pyplot as plt
SEED = 6 # one fixed draw, so the post reproduces the same numbers every time
MONTHS = 600
random_generator = np.random.default_rng(SEED)
# Each series is a random walk with drift. Every month it takes a step, and the step is a
# fixed drift plus that month's own noise. cumsum adds the steps up, so the level wanders
# upward. The two sets of steps are drawn separately, so nothing connects them.
butter_steps = 0.10 + random_generator.normal(0, 1.0, MONTHS) # small drift, small noise
sp500_steps = 0.30 + random_generator.normal(0, 2.0, MONTHS) # larger drift, larger noise
butter = 50 + np.cumsum(butter_steps) # base 50, plus the accumulated steps
sp500 = 100 + np.cumsum(sp500_steps) # base 100, plus the accumulated steps
# corrcoef returns a 2x2 table of every pair, so the number wanted is off the diagonal
correlation = np.corrcoef(butter, sp500)[0, 1]
print(f"Correlation of the two levels: {correlation:.2f}")Here are both series, each on its own scale.
RED, TEAL, ORANGE, GREY = "#C0392B", "#17868A", "#D2822B", "#888888"
# The site's chart colours: a cream background, a light grid and a pale frame, so every chart
# on the site has the same look.
BG, INK, GRID, SPINE, AXIS_TEXT = "#FCEFE3", "#1f1f1f", "#EADCCC", "#D5C6B4", "#4a4a4a"
def style_chart(figure, axis):
"""Give a finished chart the site's cream background, light grid and pale frame."""
figure.patch.set_facecolor(BG)
axis.set_facecolor(BG)
axis.grid(True, axis="y", color=GRID, lw=1.0)
axis.set_axisbelow(True)
for side in ("top", "right"):
axis.spines[side].set_visible(False)
for side in ("left", "bottom"):
axis.spines[side].set_color(SPINE)
axis.tick_params(axis="both", length=0, colors=INK, pad=6)
axis.xaxis.label.set_color(AXIS_TEXT)
axis.yaxis.label.set_color(AXIS_TEXT)
axis.title.set_color(INK)
# Each legend entry in the colour of what it labels: a line's colour or a bar's fill.
# get_legend() returns None when the chart has no legend.
legend = axis.get_legend()
if legend is not None:
for text, handle in zip(legend.get_texts(), legend.legend_handles):
if hasattr(handle, "get_color"):
text.set_color(handle.get_color())
else:
text.set_color(handle.get_facecolor())
fig, butter_axis = plt.subplots(figsize=(9, 5))
butter_axis.plot(butter, color=ORANGE, lw=1.5)
butter_axis.set_xlabel("month")
sp500_axis = butter_axis.twinx() # a second y-axis on the same x-axis
sp500_axis.plot(sp500, color=TEAL, lw=1.5)
plt.title("Butter and the S&P 500, both drifting up (simulated, unrelated)")
style_chart(fig, butter_axis)
# style_chart styles the left axis. The right axis keeps only its own frame line on the right,
# and each y label takes the colour of its line, so the labels say which line is which.
for side in ("top", "left", "bottom"):
sp500_axis.spines[side].set_visible(False)
sp500_axis.spines["right"].set_color(SPINE)
sp500_axis.tick_params(axis="y", length=0, colors=INK, pad=6)
sp500_axis.title.set_color(INK)
butter_axis.set_ylabel("butter price", color=ORANGE)
sp500_axis.set_ylabel("S&P 500", color=TEAL)
fig.tight_layout()
plt.savefig("nr44_butter_spx.png", dpi=120, bbox_inches="tight", facecolor=BG)
plt.show()
Both lines go up, with a correlation of 0.93, and the reason they seem highly correlated is that, on the level, they are both drifting upwards.
Regressing the S&P 500 on butter prices
I regress the S&P 500 on the butter price,
\[S_t = a + b\,B_t + e_t,\]
where \(e_t\) is the residual, the part of the S&P 500 that the line does not fit.
import statsmodels.api as sm
# add_constant puts a column of ones beside butter, so the line being fitted has an
# intercept as well as a slope. Without it the line would be forced through zero.
regression = sm.OLS(sp500, sm.add_constant(butter)).fit()
# The fit returns one number per column, in the order the columns were given. Position 0
# is the intercept and position 1 is butter, which is the one being tested.
butter_t_statistic = regression.tvalues[1]
butter_p_value = regression.pvalues[1]
print(f"R-squared: {regression.rsquared:.2f} "
f"(the regression fits {regression.rsquared:.0%} of the variation in the S&P 500)")
print(f"t-statistic: {butter_t_statistic:.0f} (past about 2 counts as significant)")
print(f"p-value: {butter_p_value:.0e} (looks highly significant here)")R-squared: 0.87 (the regression fits 87% of the variation in the S&P 500)
t-statistic: 63 (past about 2 counts as significant)
p-value: 9e-267 (looks highly significant here)
The R-squared is 0.87, the t-statistic is 63, and the p-value is below 0.001, so by the textbook, butter prices are strongly related to the S&P 500. But the two series are unrelated, and the t-statistic only works when the residual is noise around a stable average. Here, the residual drifts with the two series.
What cointegration requires
The difference between stationary and non-stationary is that a stationary series has a constant mean and standard deviation, and the correlation between two of its values depends only on how far apart they are. The mean stays the same over time. A non-stationary series does not have the same mean, and you can think of a price level that is trending upwards.
Cointegration needs both series to be non-stationary in levels but stationary in their monthly changes, written I(1). The Augmented Dickey-Fuller (ADF) test checks both conditions. It fits
\[\Delta y_t = \alpha + \gamma\,y_{t-1} + \dots + u_t,\]
where \(\Delta y_t\) is the change and \(y_{t-1}\) is the level the month before. If \(\gamma = 0\), the series has a unit root and wanders.
from statsmodels.tsa.stattools import adfuller
def adf_pvalue(series):
"""The p-value of the Augmented Dickey-Fuller test on one series.
The test asks whether the series has a unit root, meaning it wanders instead of
returning to a fixed level. A low p-value, below 0.05, is evidence against a unit
root. A high p-value only means the test could not rule a unit root out, which is not
the same as proving there is one.
"""
result = adfuller(series, autolag="AIC")
return result[1] # adfuller returns several numbers; the p-value is the second
# np.diff subtracts each month from the next, giving the absolute change in the level.
# That is a first difference, in price units. A percentage return divides instead of subtracting.
butter_changes = np.diff(butter)
sp500_changes = np.diff(sp500)
print(" levels first difference")
print(f"butter ADF p: {adf_pvalue(butter):.2f} {adf_pvalue(butter_changes):.0e}")
print(f"S&P 500 ADF p: {adf_pvalue(sp500):.2f} {adf_pvalue(sp500_changes):.0e}")
print("\nHigh in levels, about zero in differences: both series behave as I(1).") levels first difference
butter ADF p: 0.57 1e-17
S&P 500 ADF p: 0.94 0e+00
High in levels, about zero in differences: both series behave as I(1).
In levels, the p-values are 0.57 and 0.94, far above 0.05, so the test cannot rule out a unit root. In monthly changes, they are near zero. So both series are I(1), as they were built to be.
Testing for cointegration
You can think of cointegration as a drunk man and his dog. Even though they walk randomly and you never know which direction, they always walk together because of the leash between them. Two cointegrated series have such a leash, since the spread between them, \(e_t = S_t - a - b\,B_t\), keeps returning to its average.
I use the Engle-Granger test, which tests whether the spread from the regression is stationary. A p-value below 0.05 is evidence of cointegration.
from statsmodels.tsa.stattools import coint
# The Engle-Granger test: regress one series on the other, then ask whether what is left
# over, the spread, is stationary.
result = coint(sp500, butter)
cointegration_p_value = result[1] # coint returns three things; the p-value is the second
print(f"Cointegration p-value: {cointegration_p_value:.2f}"
f" (low = evidence of cointegration; high = no evidence of cointegration)")Cointegration p-value: 0.45 (low = evidence of cointegration; high = no evidence of cointegration)
The cointegration test gives a p-value of 0.45, so I find no evidence of cointegration. In truth, the two series are not cointegrated, because I simulated them independently.
Conclusion
When you see two series with a high correlation, always think of whether they are stationary or non-stationary. If both are non-stationary, compare their stationary monthly changes, then test the levels for cointegration.
So the conclusion is that the single most important thing is that you use economic reasoning. Why should there be a relationship? Even if something passes the cointegration test, it may still be a spurious correlation. If you cannot find a reason, there is maybe no relationship, even if it passes all tests.
References
Granger, C. W. J., & Newbold, P. (1974). Spurious regressions in econometrics. Journal of Econometrics, 2(2), 111–120. https://doi.org/10.1016/0304-4076(74)90034-7
Leinweber, D. J. (2007). Stupid data miner tricks: Overfitting the S&P 500. The Journal of Investing, 16(1), 15–22. https://doi.org/10.3905/joi.2007.681820
Disclaimer: a teaching example on simulated data. Not investment advice.