"""Final charts for the report (task #10), made from the batch event study's outputs.
car_path.png average cumulative abnormal return, day -5 to +5, per event
car_by_event.png mean CAR per event with its 95% confidence interval
online_vs_store.png the same, split into online and store retailers
car_over_years.png mean CAR of each year's event, per event type
attention_vs_returns.png Wikipedia attention spikes against CAR, one dot per window
Every confidence interval is clustered by event date (see src/eventstudy/stats.py):
the retailers share each event date, so each date counts once, not once per stock.
Every chart states how many events and tickers it uses.
Run from anywhere after car.py and stats.py: python3 src/eventstudy/charts.py
Output: data/results/charts/*.png
"""
from __future__ import annotations
import matplotlib
matplotlib.use("Agg") # draw to files, no window
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.ticker import FuncFormatter, MultipleLocator
from scipy import stats
from common.contracts import load_event_types, load_retailers
from common.settings import RESULTS_DIR, clean_path
from common.study import ATTENTION_SPIKE_Z, CONFIDENCE, EVENT_WINDOW, MARKET_TICKER
from eventstudy.car import OUTPUT as CARS
from eventstudy.stats import ALL, SUMMARY, TREND
CHARTS_DIR = RESULTS_DIR / "charts"
# Colors: a validated, colorblind-safe pair (blue, orange) on a near-white surface,
# with text in gray inks rather than series colors.
SURFACE, INK, INK_2, MUTED, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#898781", "#e6e5e0"
SERIES = ["#2a78d6", "#eb6834"]
plt.rcParams.update({
"figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE,
"axes.edgecolor": MUTED, "axes.labelcolor": INK_2, "xtick.color": MUTED, "ytick.color": MUTED,
"text.color": INK, "axes.spines.top": False, "axes.spines.right": False,
"axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.8, "axes.axisbelow": True,
"font.size": 10, "axes.titlesize": 11, "axes.titleweight": "bold", "lines.linewidth": 2,
"legend.frameon": False,
})
PCT = FuncFormatter(lambda v, _: f"{round(v * 100, 1):+g}%" if round(v * 100, 1) else "0%")
def pct(v, digits=1):
"""+1.3% style text, without a confusing -0.0%."""
v = round(v * 100, digits)
return f"{v:+.{digits}f}%" if v else f"{0:.{digits}f}%"
def short(name):
"""Display name without its bracketed alias, e.g. 'Chinese New Year (Lunar New Year)'."""
return name.split(" (")[0]
def titled(fig, title, subtitle):
"""Title and subtitle above the plots, a fixed distance apart whatever the figure height."""
from matplotlib.transforms import ScaledTranslation
top = fig.transFigure
fig.text(0.01, 1, subtitle, ha="left", va="bottom", color=INK_2, fontsize=9.5,
transform=top + ScaledTranslation(0, 6 / 72, fig.dpi_scale_trans))
fig.text(0.01, 1, title, ha="left", va="bottom", fontsize=13, fontweight="bold",
transform=top + ScaledTranslation(0, 22 / 72, fig.dpi_scale_trans))
def zero_line(ax, vertical=False):
(ax.axvline if vertical else ax.axhline)(0, color=MUTED, linewidth=1, zorder=1)
def save(fig, name):
CHARTS_DIR.mkdir(parents=True, exist_ok=True)
fig.savefig(CHARTS_DIR / name, dpi=200, bbox_inches="tight")
plt.close(fig)
print("wrote", CHARTS_DIR / name)
def window_paths(cars: pd.DataFrame) -> pd.DataFrame:
"""Cumulative abnormal return on each day of each window, using the window's own
alpha and beta from car.py, so the path ends exactly at that window's CAR."""
master = pd.read_parquet(clean_path("master"))
market = master[master["ticker"] == MARKET_TICKER].set_index("date")["ret"].rename("mkt_ret")
stocks = master[master["ticker"] != MARKET_TICKER].join(market, on="date")
rows = []
for ticker, g in stocks.sort_values("date").groupby("ticker"):
dates = list(g["date"])
ar = g["ret"].to_numpy()
mkt = g["mkt_ret"].to_numpy()
for w in cars[(cars["ticker"] == ticker) & (cars["n_days"] > 0)].itertuples():
i0 = dates.index(w.day0_date)
days = range(max(0, i0 + EVENT_WINDOW[0]), i0 + EVENT_WINDOW[1] + 1)
path = np.nancumsum([ar[i] - (w.alpha + w.beta * mkt[i]) for i in days])
rows += [{"event_type": w.event_type, "day0_date": w.day0_date, "ticker": ticker,
"day": i - i0, "car": c} for i, c in zip(days, path)]
return pd.DataFrame(rows)
def mean_with_ci(values_by_date: pd.Series):
"""Mean across event dates and its confidence interval (one value per date)."""
n = len(values_by_date)
mean = values_by_date.mean()
half = stats.t.ppf((1 + CONFIDENCE) / 2, n - 1) * values_by_date.std(ddof=1) / np.sqrt(n) if n > 1 else np.nan
return mean, mean - half, mean + half
def chart_car_path(cars, names, order):
paths = window_paths(cars)
cols = 3
rows = int(np.ceil(len(order) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(11, 3.3 * rows), sharex=True, sharey=True)
for ax, event_type in zip(axes.flat, order):
p = paths[paths["event_type"] == event_type]
per_date = p.groupby(["day", "day0_date"])["car"].mean() # average over tickers per event date
line = per_date.groupby("day").apply(lambda s: pd.Series(mean_with_ci(s), index=["m", "lo", "hi"])).unstack()
ax.fill_between(line.index, line["lo"], line["hi"], color=SERIES[0], alpha=0.15, linewidth=0)
ax.plot(line.index, line["m"], color=SERIES[0], marker="o", markersize=4)
zero_line(ax)
ax.axvline(0, color=MUTED, linewidth=1, linestyle=":")
ax.set_title(f"{names[event_type]} ({p['day0_date'].nunique()} events, {p['ticker'].nunique()} tickers)",
loc="left", fontsize=10)
ax.yaxis.set_major_formatter(PCT)
for ax in axes.flat[len(order):]:
ax.set_visible(False)
for ax in axes[-1]:
ax.set_xlabel("Trading days from the event (day 0)")
titled(fig, "How retail stocks move around each event",
f"Average cumulative abnormal return vs the market model; shaded: {CONFIDENCE:.0%} interval across event dates")
fig.tight_layout()
save(fig, "car_path.png")
def chart_car_by_event(summary, names, order):
s = summary[summary["group"] == ALL].set_index("event_type").loc[order[::-1]]
fig, ax = plt.subplots(figsize=(8, 0.55 * len(s) + 1.6))
y = np.arange(len(s))
ax.hlines(y, s["ci_low"], s["ci_high"], color=SERIES[0], linewidth=2)
ax.plot(s["mean_car"], y, "o", color=SERIES[0], markersize=8, markeredgecolor=SURFACE, markeredgewidth=2)
for yi, (_, r) in zip(y, s.iterrows()):
ax.annotate(f"{pct(r['mean_car'])} (p = {r['p_clustered']:.2f})", (r["ci_high"], yi),
xytext=(6, 0), textcoords="offset points", va="center", color=INK_2, fontsize=9)
zero_line(ax, vertical=True)
ax.set_yticks(y, [f"{names[e]} ({int(s.loc[e, 'n_events'])} events)" for e in s.index])
ax.xaxis.set_major_formatter(PCT)
ax.set_xlabel("Mean CAR, days -5 to +5")
ax.grid(axis="y", visible=False)
ax.set_xlim(right=s["ci_high"].max() + 0.035)
titled(fig, "Mean cumulative abnormal return by event",
f"{CONFIDENCE:.0%} intervals clustered by event date; {int(s['n_tickers'].max())} retailers")
fig.tight_layout()
save(fig, "car_by_event.png")
def chart_online_vs_store(summary, names, order, groups):
fig, ax = plt.subplots(figsize=(8, 0.75 * len(order) + 1.6))
y = np.arange(len(order))[::-1]
for k, group in enumerate(groups):
s = summary[summary["group"] == group].set_index("event_type").loc[order]
yy = y + (0.15 if k == 0 else -0.15)
ax.hlines(yy, s["ci_low"], s["ci_high"], color=SERIES[k], linewidth=2)
ax.plot(s["mean_car"], yy, "o", color=SERIES[k], markersize=8, markeredgecolor=SURFACE,
markeredgewidth=2, label=group.capitalize())
diff = summary[summary["group"].str.contains("_minus_")].set_index("event_type").loc[order]
for yi, e in zip(y, order):
ax.annotate(f"difference p = {diff.loc[e, 'p_clustered']:.2f}", (1.0, yi), xycoords=("axes fraction", "data"),
xytext=(6, 0), textcoords="offset points", va="center", color=INK_2, fontsize=9)
zero_line(ax, vertical=True)
ax.set_yticks(y, [names[e] for e in order])
ax.xaxis.set_major_formatter(PCT)
ax.set_xlabel("Mean CAR, days -5 to +5")
ax.grid(axis="y", visible=False)
ax.legend(loc="lower left", bbox_to_anchor=(0, 1.0), ncol=2, handletextpad=0.3)
n = summary[summary["group"].isin(groups)].groupby("group")["n_tickers"].max()
titled(fig, "Online vs store retailers",
f"Mean CAR with {CONFIDENCE:.0%} intervals; " + ", ".join(f"{n[g]} {g}" for g in groups) +
" tickers; p tests the difference, paired by event date")
fig.tight_layout()
save(fig, "online_vs_store.png")
def chart_car_over_years(cars, trend, names, order):
w = cars[cars["n_days"] > 0].assign(year=lambda d: pd.to_datetime(d["day0_date"]).dt.year)
cols = 3
rows = int(np.ceil(len(order) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(11, 3.1 * rows), sharex=True, sharey=True)
t = trend.set_index("event_type")
for ax, event_type in zip(axes.flat, order):
per_year = w[w["event_type"] == event_type].groupby("year")["car"].mean()
ax.bar(per_year.index, per_year.values, width=0.7, color=SERIES[0])
zero_line(ax)
r = t.loc[event_type]
ax.set_title(f"{names[event_type]} ({int(r['n_events'])} events)", loc="left", fontsize=10)
ax.yaxis.set_major_locator(MultipleLocator(0.05))
ax.text(0.02, 0.95, f"trend {r['slope_per_year'] * 100:+.2f} pp/year, p = {r['p_value']:.2f}",
transform=ax.transAxes, va="top", color=INK_2, fontsize=8.5)
ax.yaxis.set_major_formatter(PCT)
ax.grid(axis="x", visible=False)
for ax in axes.flat[len(order):]:
ax.set_visible(False)
years = sorted(w["year"].unique())
for ax in axes.flat:
ax.set_xticks(years[::2])
titled(fig, "Has the event effect changed over the years?",
f"Mean CAR of each year's event across {w['ticker'].nunique()} retailers; "
"trend = OLS slope of yearly mean CAR on year")
fig.tight_layout()
save(fig, "car_over_years.png")
def chart_attention_vs_returns(cars):
w = cars[(cars["n_days"] > 0) & cars["max_z_views"].notna()].drop_duplicates(["ticker", "day0_date"])
fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(w["max_z_views"], w["car"], s=22, color=SERIES[0], alpha=0.55, edgecolor=SURFACE, linewidth=0.6)
zero_line(ax)
ax.axvline(ATTENTION_SPIKE_Z, color=MUTED, linewidth=1, linestyle=":")
ax.annotate("spike threshold", (ATTENTION_SPIKE_Z, 1), xycoords=("data", "axes fraction"),
xytext=(4, -4), textcoords="offset points", va="top", color=INK_2, fontsize=8.5)
# Spearman correlation compares ranks, so the few huge attention days do not dominate it.
rho, p = stats.spearmanr(w["max_z_views"], w["car"])
spiked = w["n_spike_days"] > 0
ax.text(0, -0.17,
f"Spearman correlation {rho:+.2f} (p = {p:.2f}). Mean CAR in windows with a spike: "
f"{pct(w.loc[spiked, 'car'].mean())} ({spiked.sum()} windows); "
f"without: {pct(w.loc[~spiked, 'car'].mean())} ({(~spiked).sum()} windows).",
transform=ax.transAxes, ha="left", va="top", color=INK_2, fontsize=8.5)
ax.yaxis.set_major_formatter(PCT)
ax.set_xlabel("Highest Wikipedia attention in the window (standard deviations above normal)")
ax.set_ylabel("CAR, days -5 to +5")
titled(fig, "Do attention spikes go with bigger stock moves?",
f"One dot per ticker-event window: {len(w)} windows, {w['day0_date'].nunique()} event dates, "
f"{w['ticker'].nunique()} tickers")
fig.tight_layout()
save(fig, "attention_vs_returns.png")
def main():
cars = pd.read_parquet(CARS)
summary, trend = pd.read_csv(SUMMARY), pd.read_csv(TREND)
names = {e["event_type"]: short(e["name"]) for e in load_event_types()}
# Events in calendar order, as the calendar lists them.
order = [e["event_type"] for e in load_event_types(in_scope_only=True) if e["event_type"] in set(cars["event_type"])]
groups = sorted({r["retailer_type"] for r in load_retailers(in_scope_only=True)})
chart_car_path(cars, names, order)
chart_car_by_event(summary, names, order)
if len(groups) == 2:
chart_online_vs_store(summary, names, order, groups)
chart_car_over_years(cars, trend, names, order)
chart_attention_vs_returns(cars)
if __name__ == "__main__":
main()