Skip to content
svgcross-correlation

Cross-correlation

Does one series lead or lag the other, and by how many steps?

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

How to read it

  1. Find the tallest bar: that lag aligns the two series best.
  2. A negative lag means the first series moves first.
  3. Bars inside the band are compatible with no correlation.
  1. Callout 1: The tallest bar: the best alignment.
  2. Callout 2: Dashed band: the range for white noise.
  3. Callout 3: The lag axis says which series leads.

Watch out

  • Shared trends inflate cross-correlations. Difference the series first, or prewhiten them.
  • Leading does not mean causing.

Defaults

Max lag (0 = R default)
0
How many lags to show; 0 uses R's rule based on the series length.
Range 0 to 200, step 1

Pinned in the code

  • r_k = Σ (a_{t+k} − ā)(b_t − b̄) / (n s_a s_b), as R's ccf(a, b) (denominator n at every lag).
  • Bounds ±1.96/√n assume at least one series is white noise; autocorrelated series produce spurious peaks — prewhiten first.
  • Default max lag ⌊10 log₁₀ n⌋.
# Cross-correlation — Codesplash Chart Lab (recipe "cross-correlation")
# controls: lagMax=0
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("cross-correlation-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

_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)
def ccf(a, b, L):
    """R's ccf(a, b): r_k = Σ (a_{t+k} − ā)(b_t − b̄) / √(Σ(a − ā)² Σ(b − b̄)²), k = −L…L."""
    n = len(a)
    a, b = a - a.mean(), b - b.mean()
    den = np.sqrt((a * a).sum() * (b * b).sum())
    ks = np.arange(-L, L + 1)
    r = [sum(a[t + k] * b[t] for t in range(max(0, -k), min(n, n - k))) / den for k in ks]
    return ks, np.array(r)
X = None
A = "leading"
B = "following"
LAG_MAX = 0  # 0 = ⌊10 log₁₀ n⌋
d = ordered(df, X, [A, B])
a, b = d[A].to_numpy(dtype=float), d[B].to_numpy(dtype=float)
n = len(a)
L = min(LAG_MAX, n - 2) if LAG_MAX > 0 else max(1, min(n - 1, int(np.floor(10 * np.log10(n)))))
ks, r = ccf(a, b, L)
bound = 1.959963984540054 / np.sqrt(n)
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhspan(-bound, bound, color=GREY, alpha=0.4, lw=0)
ax.vlines(ks, 0, r, colors=np.where(np.abs(r) > bound, PALETTE[0], GREY), linewidth=3)
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_xlabel(f"lag k: cor({A}[t + k], {B}[t]) — negative k: {A} leads")
ax.set_ylabel("correlation")
plt.show()

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