Skip to content
svgcoint-spread

Cointegration spread

Does the gap between series that should move together keep returning to its mean?

Demo data · seed 20261101 · 160 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the line as the gap between the series after removing their long-run link.
  2. A cointegrated spread keeps crossing its mean.
  3. A spread that drifts away for long stretches suggests no stable link.
  1. Callout 1: The mean: the spread should keep coming back here.
  2. Callout 2: Excursions beyond the band.
  3. Callout 3: Crossing the mean often: a good sign.

Watch out

  • Looking mean-reverting by eye isn't the test. Use the cointegration result on the same regression.

Defaults

Band (SD)
2
How many standard deviations the band spans around the mean.
Range 0.5 to 4, step 0.5

Pinned in the code

  • The spread is y₀ − fitted from the Engle–Granger regression of the first series on the others (with its deterministic terms).
  • Band: mean ± k × sample SD (n − 1). A spread that wanders off and stays away suggests no cointegration.
# Cointegration spread — Codesplash Chart Lab (recipe "coint-spread")
# controls: k=2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("coint-spread-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["quarter"] = pd.to_datetime(df["quarter"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "quarter"
Y = "spread"
K = 2  # band = mean ± K·sd
d = ordered(df, X, [Y])
t, v = time_of(d, X), d[Y].to_numpy(dtype=float)
m, sd = v.mean(), v.std(ddof=1)
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhspan(m - K * sd, m + K * sd, color=GREY, alpha=0.35, lw=0)
ax.axhline(m, color=REF, linewidth=1)
ax.plot(t, v, color=PALETTE[0], linewidth=1.4)
out = np.abs(v - m) > K * sd
ax.scatter(np.asarray(t)[out], v[out], color="#ce5342", s=14, zorder=3)
ax.set_xlabel("quarter")
ax.set_ylabel(Y)
plt.show()

Needs pandas, numpy, matplotlib · reads coint-spread-demo.csv · app theme from the optional codesplash helper