svgimpulse-response
Impulse responses
When one series gets a one-off shock, how do the others respond over the following periods?
How to read it
- Read each panel as one series' response to a one-off shock in another.
- Follow the path from period zero: how large, how long, which sign.
- Check the band: a path inside a band around zero is compatible with no response.
Watch out
- Orthogonalized shocks depend on the order of the series, and these are model responses rather than proven causal effects.
Defaults
- Rows
- All, or the target above 4 series
- Which responses and shocks to show.
- Also: All series · Target series only
Pinned in the code
- Orthogonalized responses Θ_i = Φ_i P with P the lower Cholesky factor of the residual covariance: the first listed series can move the others at once, the last only itself. Reordering changes the picture.
- Bands are percentile intervals from a residual bootstrap with the lag order and rank held fixed.
- Each row shares a y-axis so shocks can be compared for the same response; a response whose band excludes zero differs from no response at that step.
Use with care
These trace how the fitted system moves, under one assumed ordering. They support a causal reading only if that ordering reflects how the shocks really occur.
# Impulse responses — Codesplash Chart Lab (recipe "impulse-response")
# controls: scope=auto
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("impulse-response-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["responding series"] = pd.Categorical(df["responding series"].astype("string"), categories=["sales", "ad spend", "price"])
df["shock"] = pd.Categorical(df["shock"].astype("string"), categories=["sales", "ad spend", "price"])
_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")
H = "steps"
V = "response"
R = "responding series"
S = "shock"
LO = "low"
HI = "high"
responses = df[R].astype("category").cat.categories if not hasattr(df[R], "cat") else df[R].cat.categories
shocks = df[S].astype("category").cat.categories if not hasattr(df[S], "cat") else df[S].cat.categories
fig, axes = plt.subplots(len(responses), len(shocks), figsize=(8, 6), sharex=True, sharey="row", squeeze=False)
for i, r in enumerate(responses):
for j, s in enumerate(shocks):
ax = axes[i][j]
d = df[(df[R] == r) & (df[S] == s)].sort_values(H)
if LO and HI:
ax.fill_between(d[H], d[LO], d[HI], color=PALETTE[0], alpha=0.2, linewidth=0)
ax.axhline(0, color=REF, linewidth=0.8)
ax.plot(d[H], d[V], color=PALETTE[0], linewidth=1.5)
if i == 0:
ax.set_title(f"Shock: {s}", fontsize=9)
if j == 0:
ax.set_ylabel(str(r), fontsize=9)
fig.supxlabel("steps after the shock", fontsize=9)
plt.show()Needs pandas, numpy, matplotlib · reads impulse-response-demo.csv · app theme from the optional codesplash helper
# Impulse responses — Codesplash Chart Lab (recipe "impulse-response")
# controls: scope=auto
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("impulse-response-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["responding series"] = pd.Categorical(df["responding series"].astype("string"), categories=["sales", "ad spend", "price"])
df["shock"] = pd.Categorical(df["shock"].astype("string"), categories=["sales", "ad spend", "price"])
_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")
from plotly.subplots import make_subplots
H = "steps"
V = "response"
R = "responding series"
S = "shock"
LO = "low"
HI = "high"
responses = list(pd.unique(df[R]))
shocks = list(pd.unique(df[S]))
fig = make_subplots(rows=len(responses), cols=len(shocks), shared_xaxes=True, column_titles=[f"Shock: {s}" for s in shocks], row_titles=[str(r) for r in responses])
for i, r in enumerate(responses):
for j, s in enumerate(shocks):
d = df[(df[R] == r) & (df[S] == s)].sort_values(H)
if LO and HI:
fig.add_trace(go.Scatter(x=list(d[H]) + list(d[H])[::-1], y=list(d[HI]) + list(d[LO])[::-1], fill="toself", fillcolor="rgba(70,110,200,0.2)", line=dict(width=0), showlegend=False, hoverinfo="skip"), row=i + 1, col=j + 1)
fig.add_trace(go.Scatter(x=d[H], y=d[V], mode="lines", line=dict(color=PALETTE[0]), showlegend=False), row=i + 1, col=j + 1)
fig.add_hline(y=0, line=dict(color=REF, width=1), row=i + 1, col=j + 1)
fig.show()Needs pandas, numpy, plotly · reads impulse-response-demo.csv · app theme from the optional codesplash helper
# Impulse responses — Codesplash Chart Lab (recipe "impulse-response")
# controls: scope=auto
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("impulse-response-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["responding series"]] <- factor(df[["responding series"]], levels = c("sales", "ad spend", "price"))
df[["shock"]] <- factor(df[["shock"]], levels = c("sales", "ad spend", "price"))
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
H <- "steps"
V <- "response"
R <- "responding series"
S <- "shock"
LO <- "low"
HI <- "high"
d <- data.frame(h = df[[H]], v = df[[V]], response = df[[R]], shock = df[[S]])
if (!is.null(LO) && !is.null(HI)) { d$lo <- df[[LO]]; d$hi <- df[[HI]] }
d <- d[order(d$h), ]
p <- ggplot(d, aes(h, v))
if (!is.null(d$lo)) p <- p + geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.2)
p <- p + geom_hline(yintercept = 0, colour = ref_col, linewidth = 0.3) +
geom_line(colour = cs_cat[1], linewidth = 0.6) +
facet_grid(response ~ shock, scales = "free_y", labeller = labeller(shock = function(s) paste("Shock:", s))) +
labs(x = "steps after the shock", y = NULL)
print(p)Needs ggplot2 · reads impulse-response-demo.csv · app theme from the optional codesplashr helper