svgcross-correlation
Cross-correlation
Does one series lead or lag the other, and by how many steps?
How to read it
- Find the tallest bar: that lag aligns the two series best.
- A negative lag means the first series moves first.
- Bars inside the band are compatible with no correlation.
- Callout 1: The tallest bar: the best alignment.
- Callout 2: Dashed band: the range for white noise.
- 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
# Cross-correlation — Codesplash Chart Lab (recipe "cross-correlation")
# controls: lagMax=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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
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 = go.Figure(go.Bar(x=ks, y=r, width=0.3, marker_color=np.where(np.abs(r) > bound, PALETTE[0], GREY)))
fig.add_hrect(y0=-bound, y1=bound, fillcolor=GREY, opacity=0.4, line_width=0)
fig.update_layout(xaxis_title=f"lag k: cor({A}[t + k], {B}[t])", yaxis_title="correlation")
fig.show()Needs pandas, numpy, plotly · reads cross-correlation-demo.csv · app theme from the optional codesplash helper
# Cross-correlation — Codesplash Chart Lab (recipe "cross-correlation")
# controls: lagMax=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cross-correlation-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- NULL
a_col <- "leading"
b_col <- "following"
LAG_MAX <- 0
d <- ordered(df, x_col, c(a_col, b_col))
n <- nrow(d)
L <- if (LAG_MAX > 0) min(LAG_MAX, n - 2) else max(1, min(n - 1, floor(10 * log10(n))))
cc <- stats::ccf(d[[a_col]], d[[b_col]], lag.max = L, plot = FALSE) # r_k = cor(a[t + k], b[t])
r <- data.frame(lag = as.numeric(cc$lag), r = as.numeric(cc$acf))
bound <- 1.959963984540054 / sqrt(n)
p <- ggplot(r, aes(lag, r)) +
annotate("rect", xmin = -Inf, xmax = Inf, ymin = -bound, ymax = bound, fill = grey_col, alpha = 0.4) +
geom_hline(yintercept = 0, colour = "grey50") + geom_segment(aes(xend = lag, y = 0, yend = r, colour = abs(r) > bound), linewidth = 1.2) +
scale_colour_manual(values = c("FALSE" = grey_col, "TRUE" = cs_cat[1]), guide = "none") +
labs(x = sprintf("lag k: cor(%s[t + k], %s[t])", a_col, b_col), y = "correlation") + theme_cs
print(p)Needs ggplot2 · reads cross-correlation-demo.csv · app theme from the optional codesplashr helper