"""Batch event study: one cumulative abnormal return (CAR) per stock per event.
This is the "answer key" the streaming job is compared against (decision 0004).
The idea, for one stock and one event (say Walmart on Black Friday 2023):
1. Normal behaviour. Over the ESTIMATION_DAYS trading days before the event window,
fit the market model by ordinary least squares (OLS):
ret_stock = alpha + beta * ret_market + error
beta says how much the stock usually moves when the market (SPY) moves.
2. Abnormal return (AR) on each day of the event window (days -5..+5 around day 0):
AR = actual return - (alpha + beta * market return)
i.e. what the stock did minus what the model expected from the market that day.
3. CAR = the sum of the window's ARs. A CAR of 0.03 means the stock beat its normal
behaviour by about 3% over the 11 days.
Rules shared with the streaming job (src/common/study.py, decision 0004):
- simple returns, SPY as the market, window -5..+5, 120 estimation days (at least 100)
- day 0 = first trading day on or after the event date (weekend events move to Monday)
- events come from the calendar (expand_events), not from master's event_type column
- the estimation window ends before day -5, so the event never leaks into its own
baseline ("no look-ahead")
It also scores attention exactly like the stream: each day's Wikipedia views against
the ATTENTION_BASELINE_DAYS days that end ESTIMATION_GAP_DAYS earlier, in standard
deviations (z_views); a spike is z_views >= ATTENTION_SPIKE_Z.
This file is deliberately written apart from src/streaming/signals.py (numpy on whole
arrays instead of the stream's day-by-day state), so matching numbers mean both are right.
Run from anywhere: python3 src/eventstudy/car.py
Output: data/results/batch_event_car.parquet (contract: batch_event_car)
"""
from __future__ import annotations
import json
import subprocess
from datetime import datetime, timezone
import numpy as np
import pandas as pd
from common.contracts import (MARKET_WIDE_TICKER, expand_events, pandas_columns, price_tickers,
require_contract)
from common.settings import REPO_ROOT, RESULTS_DIR, clean_path
from common.study import (ABNORMAL_RETURN_Z, ATTENTION_BASELINE_DAYS, ATTENTION_SPIKE_Z,
ESTIMATION_DAYS, ESTIMATION_GAP_DAYS, EVENT_WINDOW, MARKET_TICKER,
MIN_ATTENTION_DAYS, MIN_ESTIMATION_DAYS, STUDY_END_YEAR,
STUDY_START_YEAR)
OUTPUT = RESULTS_DIR / "batch_event_car.parquet"
PRE_DAYS, POST_DAYS = -EVENT_WINDOW[0], EVENT_WINDOW[1]
def fit_market_model(ret: np.ndarray, mkt: np.ndarray):
"""OLS fit of ret = alpha + beta * mkt on the days where both are present.
Returns (alpha, beta, residual standard deviation, days used), or None when there
are fewer than MIN_ESTIMATION_DAYS days or the market never moved.
The residual standard deviation divides by n - 2 because two numbers (alpha and
beta) were estimated from the same data, which uses up two "degrees of freedom".
"""
ok = ~np.isnan(ret) & ~np.isnan(mkt)
r, m = ret[ok], mkt[ok]
n = len(r)
if n < MIN_ESTIMATION_DAYS or np.var(m) == 0:
return None
beta, alpha = np.polyfit(m, r, 1) # slope first, then intercept
residuals = r - (alpha + beta * m)
return alpha, beta, float(np.sqrt((residuals ** 2).sum() / (n - 2))), n
def attention_z(views: np.ndarray) -> np.ndarray:
"""z-score of each day's views against its baseline, NaN without enough baseline.
Day i's baseline is the ATTENTION_BASELINE_DAYS trading days that end
ESTIMATION_GAP_DAYS before it, the same gap as the market model, so a spike that
builds up during an event window does not raise its own baseline.
"""
z = np.full(len(views), np.nan)
for i in range(len(views)):
end = max(0, i - ESTIMATION_GAP_DAYS)
base = views[max(0, end - ATTENTION_BASELINE_DAYS):end]
base = base[~np.isnan(base)]
if np.isnan(views[i]) or len(base) < MIN_ATTENTION_DAYS:
continue
sd = base.std(ddof=1) # sample standard deviation
if sd > 0:
z[i] = (views[i] - base.mean()) / sd
return z
def event_car(ticker, event, dates, ret, mkt, z_views):
"""The CAR row for one ticker and one event occurrence, or None when the event is
outside this ticker's data or its window is not complete yet."""
event_date = np.datetime64(event["event_date"])
if event_date < dates[0]:
return None
day0 = int(np.searchsorted(dates, event_date)) # first trading day on or after the event
if day0 + POST_DAYS >= len(dates):
return None
start, stop = max(0, day0 - PRE_DAYS), day0 + POST_DAYS + 1
# Estimation window: ESTIMATION_DAYS days that end right before day -5.
model = fit_market_model(ret[max(0, start - ESTIMATION_DAYS):start],
mkt[max(0, start - ESTIMATION_DAYS):start])
alpha, beta, sd, n_est = model if model else (None, None, None, 0)
r, m = ret[start:stop], mkt[start:stop]
ok = ~np.isnan(r) & ~np.isnan(m)
ars = r[ok] - (alpha + beta * m[ok]) if model else np.array([])
car = float(ars.sum()) if len(ars) else None
window_z = z_views[start:stop]
window_z = window_z[~np.isnan(window_z)]
return {
"ticker": ticker,
"event_type": event["event_type"],
"event_date": event["event_date"],
"event_end_date": event["event_end_date"],
"day0_date": pd.Timestamp(dates[day0]).date(),
"alpha": alpha,
"beta": beta,
"ar_sd": sd,
"estimation_days": n_est,
"car": car,
# If each AR has spread sd, a sum of n independent ARs has spread sd * sqrt(n).
# car_z says how many of those spreads the CAR is away from 0.
"car_z": car / (sd * np.sqrt(len(ars))) if car is not None and sd else None,
"n_days": len(ars),
"n_abnormal_days": int((np.abs(ars / sd) >= ABNORMAL_RETURN_Z).sum()) if sd else 0,
"max_z_views": float(window_z.max()) if len(window_z) else None,
"n_spike_days": int((window_z >= ATTENTION_SPIKE_Z).sum()),
}
def compute_cars(master: pd.DataFrame, events: list[dict]) -> pd.DataFrame:
"""batch_event_car rows for every retailer in master and every calendar event."""
master = master.assign(date=pd.to_datetime(master["date"]))
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(["ticker", "date"]).groupby("ticker"):
dates = g["date"].to_numpy()
ret = g["ret"].to_numpy(dtype=float)
mkt = g["mkt_ret"].to_numpy(dtype=float)
z_views = attention_z(g["views"].to_numpy(dtype=float))
for event in events:
if event["ticker"] in (MARKET_WIDE_TICKER, ticker):
row = event_car(ticker, event, dates, ret, mkt, z_views)
if row:
rows.append(row)
out = pd.DataFrame(rows).sort_values(["event_date", "event_type", "ticker"], ignore_index=True)
# Store the types the contract asks for (pandas would otherwise guess).
for c in ["estimation_days", "n_days", "n_abnormal_days", "n_spike_days"]:
out[c] = out[c].astype("int32")
for c in ["alpha", "beta", "ar_sd", "car", "car_z", "max_z_views"]:
out[c] = out[c].astype("float64")
return out
def code_version() -> str:
"""The git commit the results came from, marked -dirty if files were changed since."""
def git(*args):
return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True).stdout.strip()
commit = git("rev-parse", "--short", "HEAD") or "unknown"
return commit + ("-dirty" if git("status", "--porcelain", "--untracked-files=no") else "")
def main():
master = pd.read_parquet(clean_path("master"))
# Only the in-scope retailers (and the market), even if master is older than config/.
master = master[master["ticker"].isin(price_tickers())]
events = expand_events(STUDY_START_YEAR, STUDY_END_YEAR)
cars = compute_cars(master, events)
require_contract("batch_event_car", pandas_columns(cars))
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
cars.to_parquet(OUTPUT, index=False)
info = {"code_version": code_version(), "created_utc": datetime.now(timezone.utc).isoformat(),
"rows": len(cars)}
OUTPUT.with_suffix(".json").write_text(json.dumps(info, indent=2))
scored = cars[cars["n_days"] > 0]
print(f"{len(cars)} event windows, {len(scored)} with a CAR "
f"({cars['ticker'].nunique()} tickers, {cars[['event_type', 'event_date']].drop_duplicates().shape[0]} "
f"event occurrences); written to {OUTPUT}")
print(scored.groupby("event_type")["car"].agg(["count", "mean", "median"]).round(4))
if __name__ == "__main__":
main()