"""Significance tests on the batch CARs: is the average CAR around an event really
different from zero, does it differ between online and store retailers, and does it
change over the years? Reads the output of src/eventstudy/car.py.
Why several tests (each answers "could this average be 0 and we just got unlucky?"):
- t-test: the classic test on the mean CAR. Assumes every window is independent.
- Wilcoxon signed-rank: the same question without assuming a bell curve, so a few
extreme CARs (a meme-stock day, March 2020) cannot drive the result alone.
- BMP (Boehmer, Musumeci and Poulsen): a t-test on standardized CARs (car_z), so a
volatile stock counts as much as a calm one. Here car_z does not include BMP's small
correction for the error in estimating alpha and beta, so read it as "BMP-style".
- Clustered by event date: the main test. All 10 retailers share each Black Friday,
so their CARs move together (a market-wide shock hits all of them at once) and are
not 10 independent pieces of evidence. Clustering treats each event date as one
group; the confidence interval comes from this test.
Trend: for each event type, the average CAR of each year's occurrence regressed on the
year. The slope is the change in CAR per year.
Run from anywhere after car.py: python3 src/eventstudy/stats.py
Output: data/results/batch_car_summary.csv and batch_car_trend.csv
(contracts: batch_car_summary, batch_car_trend)
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from scipy import stats
import json
from datetime import datetime, timezone
from common.contracts import load_retailers, pandas_columns, require_contract
from common.settings import RESULTS_DIR
from common.study import CONFIDENCE
from eventstudy.car import OUTPUT as CARS
from eventstudy.car import code_version
SUMMARY = RESULTS_DIR / "batch_car_summary.csv"
TREND = RESULTS_DIR / "batch_car_trend.csv"
ALL = "all" # label for "every event type" or "every retailer"
def clustered_mean_test(car: pd.Series, cluster: pd.Series):
"""Mean of car with a standard error clustered by `cluster` (here, day 0).
Instead of treating each window as independent, the errors (car - mean) are first
summed within each cluster, so windows that move together count as one piece of
evidence. With G clusters the test has G - 1 degrees of freedom.
Returns (ci_low, ci_high, p_value); NaN when there are fewer than 2 clusters.
"""
g = cluster.nunique()
if g < 2:
return np.nan, np.nan, np.nan
mean, n = car.mean(), len(car)
sums = (car - mean).groupby(cluster).sum()
se = np.sqrt((sums ** 2).sum() * g / (g - 1)) / n
if se == 0:
return mean, mean, np.nan
t_crit = stats.t.ppf((1 + CONFIDENCE) / 2, g - 1)
p = 2 * stats.t.sf(abs(mean / se), g - 1)
return mean - t_crit * se, mean + t_crit * se, p
def one_sample_p(x: pd.Series, test):
"""p-value of a test of "the average is 0", NaN with too few values."""
x = x.dropna()
if len(x) < 2 or (x == 0).all():
return np.nan
return float(test(x).pvalue)
def summary_row(event_type, group, w: pd.DataFrame) -> dict:
ci_low, ci_high, p_clustered = clustered_mean_test(w["car"], w["day0_date"])
return {
"event_type": event_type, "group": group,
"n_windows": len(w), "n_events": w["day0_date"].nunique(), "n_tickers": w["ticker"].nunique(),
"mean_car": w["car"].mean(), "median_car": w["car"].median(),
"ci_low": ci_low, "ci_high": ci_high,
"pct_positive": (w["car"] > 0).mean(),
"p_t": one_sample_p(w["car"], lambda x: stats.ttest_1samp(x, 0)),
"p_wilcoxon": one_sample_p(w["car"], stats.wilcoxon),
"p_bmp": one_sample_p(w["car_z"], lambda x: stats.ttest_1samp(x, 0)),
"p_clustered": p_clustered,
}
def difference_row(event_type, groups, w: pd.DataFrame) -> dict | None:
"""First group minus second (e.g. online minus store), paired by event occurrence.
For each event date, take the average CAR of each group and subtract. Pairing by
date removes whatever hit both groups that day, and each date is one observation,
so this test is already clustered by event date.
"""
a, b = groups
by_date = w.groupby(["day0_date", "group"])["car"].mean().unstack()
diff = (by_date[a] - by_date[b]).dropna() if a in by_date and b in by_date else pd.Series(dtype=float)
if len(diff) < 2:
return None
t = stats.ttest_1samp(diff, 0)
ci = t.confidence_interval(CONFIDENCE)
return {
"event_type": event_type, "group": f"{a}_minus_{b}",
"n_windows": len(w), "n_events": len(diff), "n_tickers": w["ticker"].nunique(),
"mean_car": diff.mean(), "median_car": diff.median(),
"ci_low": ci.low, "ci_high": ci.high,
"pct_positive": (diff > 0).mean(),
"p_t": t.pvalue, "p_wilcoxon": one_sample_p(diff, stats.wilcoxon),
"p_bmp": np.nan, "p_clustered": t.pvalue,
}
def trend_row(event_type, w: pd.DataFrame) -> dict | None:
"""Average CAR of each occurrence regressed on its year (ordinary least squares)."""
per_event = w.groupby("day0_date")["car"].mean().reset_index()
per_event["year"] = pd.to_datetime(per_event["day0_date"]).dt.year
if per_event["year"].nunique() < 3:
return None
fit = stats.linregress(per_event["year"], per_event["car"])
t_crit = stats.t.ppf((1 + CONFIDENCE) / 2, len(per_event) - 2)
return {
"event_type": event_type, "n_events": len(per_event), "n_tickers": w["ticker"].nunique(),
"first_year": int(per_event["year"].min()), "last_year": int(per_event["year"].max()),
"slope_per_year": fit.slope,
"ci_low": fit.slope - t_crit * fit.stderr, "ci_high": fit.slope + t_crit * fit.stderr,
"p_value": fit.pvalue,
}
def build_tables(cars: pd.DataFrame, retailers: list[dict]):
labels = pd.DataFrame(retailers)[["ticker", "retailer_type"]].rename(columns={"retailer_type": "group"})
w = cars[cars["n_days"] > 0].merge(labels, on="ticker", how="left")
groups = sorted(w["group"].dropna().unique())
# "All events": two event types can share the same window (US Thanksgiving and Black
# Friday both start on the Friday), so keep each ticker's window once.
pooled = w.drop_duplicates(["ticker", "day0_date"])
by_type = [(t, g) for t, g in w.groupby("event_type")] + [(ALL, pooled)]
summary, trend = [], []
for event_type, g in by_type:
summary.append(summary_row(event_type, ALL, g))
for group in groups:
summary.append(summary_row(event_type, group, g[g["group"] == group]))
if len(groups) == 2:
row = difference_row(event_type, groups, g)
if row:
summary.append(row)
row = trend_row(event_type, g)
if row:
trend.append(row)
summary = pd.DataFrame(summary)
trend = pd.DataFrame(trend)
for df, ints in ((summary, ["n_windows", "n_events", "n_tickers"]),
(trend, ["n_events", "n_tickers", "first_year", "last_year"])):
for c in df.columns:
df[c] = df[c].astype("int32") if c in ints else df[c] if df[c].dtype == object else df[c].astype("float64")
return summary, trend
def main():
cars = pd.read_parquet(CARS)
summary, trend = build_tables(cars, load_retailers(in_scope_only=True))
require_contract("batch_car_summary", pandas_columns(summary))
require_contract("batch_car_trend", pandas_columns(trend))
summary.to_csv(SUMMARY, index=False)
trend.to_csv(TREND, index=False)
# Record which code (and which CAR file) produced the tables.
cars_info = json.loads(CARS.with_suffix(".json").read_text())
for path, table in ((SUMMARY, summary), (TREND, trend)):
info = {"code_version": code_version(), "created_utc": datetime.now(timezone.utc).isoformat(),
"rows": len(table), "cars_code_version": cars_info["code_version"]}
path.with_suffix(".json").write_text(json.dumps(info, indent=2))
pd.set_option("display.width", 200)
show = summary[summary["group"] == ALL]
print(f"Mean CAR by event (days -5..+5), {CONFIDENCE:.0%} CI and p-values; written to {SUMMARY}")
print(show[["event_type", "n_windows", "n_events", "n_tickers", "mean_car", "ci_low", "ci_high",
"p_t", "p_wilcoxon", "p_bmp", "p_clustered"]].round(4).to_string(index=False))
print("\nOnline vs store (and the difference):")
print(summary[summary["group"] != ALL][["event_type", "group", "n_events", "mean_car", "ci_low",
"ci_high", "p_clustered"]].round(4).to_string(index=False))
print(f"\nTrend of CAR per year; written to {TREND}")
print(trend.round(4).to_string(index=False))
if __name__ == "__main__":
main()