> ## Documentation Index
> Fetch the complete documentation index at: https://calendar-effects.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# src/eventstudy/charts.py

> Final charts for the report (task #10), made from the batch event study's outputs.

`src/eventstudy/charts.py` · chapter [The batch event study](https://calendar-effects.mintlify.site/tour/06-batch-study.md), file 4 · 256 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py)

## What it does

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

## What is inside

* **`CHARTS_DIR`** · [line 33](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L33)
* **`SERIES`** · [line 38](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L38)
* **`PCT`** · [line 47](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L47)
* **`pct(v, digits)`** · [line 50](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L50): +1.3% style text, without a confusing -0.0%.
* **`short(name)`** · [line 56](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L56): Display name without its bracketed alias, e.g. 'Chinese New Year (Lunar New Year)'.
* **`titled(fig, title, subtitle)`** · [line 61](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L61): Title and subtitle above the plots, a fixed distance apart whatever the figure height.
* **`zero_line(ax, vertical)`** · [line 71](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L71)
* **`save(fig, name)`** · [line 75](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L75)
* **`window_paths(cars)`** · [line 82](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L82): 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.
* **`mean_with_ci(values_by_date)`** · [line 102](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L102): Mean across event dates and its confidence interval (one value per date).
* **`chart_car_path(cars, names, order)`** · [line 110](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L110)
* **`chart_car_by_event(summary, names, order)`** · [line 136](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L136)
* **`chart_online_vs_store(summary, names, order, groups)`** · [line 157](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L157)
* **`chart_car_over_years(cars, trend, names, order)`** · [line 184](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L184)
* **`chart_attention_vs_returns(cars)`** · [line 213](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L213)
* **`main()`** · [line 239](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/eventstudy/charts.py#L239)

## Connections

**Uses:** [`src/common/contracts.py`](https://calendar-effects.mintlify.site/reference/src/common/contracts), [`src/common/settings.py`](https://calendar-effects.mintlify.site/reference/src/common/settings), [`src/common/study.py`](https://calendar-effects.mintlify.site/reference/src/common/study), [`src/eventstudy/car.py`](https://calendar-effects.mintlify.site/reference/src/eventstudy/car), [`src/eventstudy/stats.py`](https://calendar-effects.mintlify.site/reference/src/eventstudy/stats)

**Used by:** [`scripts/export_results.py`](https://calendar-effects.mintlify.site/reference/scripts/export_results), [`src/hosting/snapshot.py`](https://calendar-effects.mintlify.site/reference/src/hosting/snapshot), [`src/hosting/publish_hf.py`](https://calendar-effects.mintlify.site/reference/src/hosting/publish_hf)

## Source

```python title="src/eventstudy/charts.py" lines expandable theme={null}
"""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()
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.