scripts/export_results.py · chapter The batch event study, file 5 · 331 lines · open in the repository
What it does
Gather the final results into docs/results/ for the report, the slides and the video (decision 0013). Everything a teammate needs to write about the results, without running anything: every number with where it comes from, the tables, the charts, and the full output of the checks that prove the stream is right. The numbers are written by this script from the run’s outputs, so the summary cannot drift from them. Run after a full run (./run_everything.sh) and python3 src/hosting/snapshot.py:python3 scripts/export_results.py
python3 scripts/export_results.py --cluster-stream data/cluster/stream --cluster-note "..."
What is inside
OUT· line 42TABLES· line 43CHARTS· line 44: file: captionLINK_NAMES· line 53pct(v, digits)· line 57p(v)· line 64stars(pv)· line 68run_check(args, name)· line 72: Run a check script, keep its full output in docs/results/checks/, return (ok, output).lines_with(text)· line 83in_window_rates(signals, cars)· line 87: Share of stock-days with an abnormal return or an attention spike, inside event windows (days −5..+5) and outside them.main()· line 103
Connections
Uses:src/common/contracts.py, src/common/settings.py, src/common/study.py, src/eventstudy/car.py, src/eventstudy/charts.py, src/eventstudy/stats.py, src/hosting/snapshot.py
Source
scripts/export_results.py
"""Gather the final results into docs/results/ for the report, the slides and the video (decision 0013).
Everything a teammate needs to write about the results, without running anything: every
number with where it comes from, the tables, the charts, and the full output of the checks
that prove the stream is right. The numbers are written by this script from the run's
outputs, so the summary cannot drift from them.
Run after a full run (./run_everything.sh) and python3 src/hosting/snapshot.py:
python3 scripts/export_results.py
With the SFU cluster run copied back to data/cluster/stream (see AGENTS.md, Commands):
python3 scripts/export_results.py --cluster-stream data/cluster/stream --cluster-note "..."
Writes (committed; small):
docs/results/README.md the results, section by section, with tables and charts
docs/results/tables/*.csv the batch study's summary and trend tables, the model's metrics
docs/results/charts/*.png the report's charts
docs/results/checks/*.txt the full output of check_streaming.py and compare_stream_batch.py
"""
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import pandas as pd
from common.contracts import load_event_types, load_retailers
from common.settings import (BIG_MOVE_MODEL_INFO, DOCS_DIR, LINKS, REPO_ROOT, RESULTS_DIR, SNAPSHOT_DIR, STREAM_DIR,
clean_path)
from common.study import (ABNORMAL_RETURN_Z, ATTENTION_SPIKE_Z, CONFIDENCE, ESTIMATION_DAYS, EVENT_WINDOW,
MARKET_TICKER, STUDY_END_YEAR, STUDY_START_YEAR)
from eventstudy.car import OUTPUT as CARS
from eventstudy.charts import CHARTS_DIR, short
from eventstudy.stats import ALL, SUMMARY, TREND
from hosting.snapshot import read_stream
OUT = DOCS_DIR / "results"
TABLES = [SUMMARY, TREND, RESULTS_DIR / "ml_metrics.csv", RESULTS_DIR / "ml_feature_importance.csv"]
CHARTS = { # file: caption
"car_path.png": "Average cumulative abnormal return from day −5 to +5, per event, with its 95% confidence band (clustered by event date).",
"car_by_event.png": "Mean CAR per event with its 95% confidence interval.",
"online_vs_store.png": "Mean CAR per event for online and store retailers.",
"car_over_years.png": "Mean CAR of each year's occurrence, per event type, with the trend.",
"attention_vs_returns.png": "Wikipedia attention spikes against CAR, one dot per window.",
"ml_roc_pr.png": "The big-move model on the test years: ROC and precision-recall curves against the baseline.",
"ml_feature_importance.png": "Which inputs the big-move model relies on (gradient-boosted trees).",
}
LINK_NAMES = {"dashboard": "Dashboard (live and replay)", "docs": "Docs site (tour of the code)",
"dataset": "Dataset", "model": "Model", "github": "GitHub", "huggingface": "Hugging Face"}
def pct(v, digits=1) -> str:
if pd.isna(v):
return "–"
r = round(v * 100, digits)
return f"{0:.{digits}f}%" if r == 0 else f"{r:+.{digits}f}%"
def p(v) -> str:
return "–" if pd.isna(v) else ("< 0.001" if v < 0.001 else f"{v:.3f}")
def stars(pv) -> str:
return "" if pd.isna(pv) else "**" if pv < 0.05 else "*" if pv < 0.10 else ""
def run_check(args: list[str], name: str) -> tuple[bool, str]:
"""Run a check script, keep its full output in docs/results/checks/, return (ok, output)."""
out = subprocess.run([sys.executable, *args], cwd=REPO_ROOT, capture_output=True, text=True)
text = out.stdout + (("\n" + out.stderr) if out.returncode else "")
command = " ".join(args)
for local in (str(REPO_ROOT) + "/", str(REPO_ROOT)): # repo-relative paths: no one's home folder
text, command = text.replace(local, ""), command.replace(local, "")
(OUT / "checks" / f"{name}.txt").write_text(f"$ python3 {command}\n\n{text}")
return out.returncode == 0 and "FAILED" not in text, text
def lines_with(text: str, *words) -> list[str]:
return [l.strip() for l in text.splitlines() if any(w in l for w in words)]
def in_window_rates(signals: pd.DataFrame, cars: pd.DataFrame) -> pd.DataFrame:
"""Share of stock-days with an abnormal return or an attention spike, inside event
windows (days −5..+5) and outside them."""
s = signals.dropna(subset=["abnormal_return"]).sort_values(["ticker", "date"]).copy()
s["i"] = s.groupby("ticker").cumcount()
index = s.set_index(["ticker", "date"])["i"]
inside = set()
for w in cars[cars["n_days"] > 0].itertuples():
i0 = index.get((w.ticker, pd.Timestamp(w.day0_date)))
if i0 is not None:
inside.update((w.ticker, i) for i in range(i0 + EVENT_WINDOW[0], i0 + EVENT_WINDOW[1] + 1))
s["window"] = [(t, i) in inside for t, i in zip(s["ticker"], s["i"])]
return s.groupby("window").agg(stock_days=("ticker", "size"), abnormal=("abnormal_return", "mean"),
spikes=("attention_spike", "mean"))
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--cluster-stream", help="the SFU cluster run's stream folder, copied back")
parser.add_argument("--cluster-note", default="", help="how the cluster run was made (shown in the summary)")
args = parser.parse_args()
events_json = SNAPSHOT_DIR / "events.json"
if not events_json.exists():
raise SystemExit("Run python3 src/hosting/snapshot.py first (the forecasts come from it).")
for d in ("tables", "charts", "checks"):
shutil.rmtree(OUT / d, ignore_errors=True)
(OUT / d).mkdir(parents=True)
retailers = load_retailers(in_scope_only=True)
names = {e["event_type"]: short(e["name"]) for e in load_event_types()}
master = pd.read_parquet(clean_path("master"))
cars = pd.read_parquet(CARS)
summary, trend = pd.read_csv(SUMMARY), pd.read_csv(TREND)
metrics = pd.read_csv(RESULTS_DIR / "ml_metrics.csv")
importance = pd.read_csv(RESULTS_DIR / "ml_feature_importance.csv").sort_values("importance", ascending=False)
info = json.loads(BIG_MOVE_MODEL_INFO.read_text())
events = json.loads(events_json.read_text())
signals = read_stream("stream_signals")
cars_info = json.loads(CARS.with_suffix(".json").read_text())
for t in TABLES:
shutil.copy(t, OUT / "tables" / t.name)
for c in CHARTS:
if (CHARTS_DIR / c).exists():
shutil.copy(CHARTS_DIR / c, OUT / "charts" / c)
local_ok, local_check = run_check(["scripts/check_streaming.py", str(STREAM_DIR)], "local_check_streaming")
local_cmp_ok, local_cmp = run_check(["scripts/compare_stream_batch.py", "--stream", str(STREAM_DIR)],
"local_compare_stream_batch")
cluster = None
if args.cluster_stream:
c_ok, c_check = run_check(["scripts/check_streaming.py", args.cluster_stream], "cluster_check_streaming")
c_cmp_ok, c_cmp = run_check(["scripts/compare_stream_batch.py", "--stream", args.cluster_stream],
"cluster_compare_stream_batch")
cluster = (c_ok, c_check, c_cmp_ok, c_cmp)
scored = cars[cars["n_days"] > 0]
online = [r for r in retailers if r["retailer_type"] == "online"]
rates = in_window_rates(signals, cars)
test = metrics[metrics["split"] == "test"].set_index("features")
L = []
add = L.append
add("# Results")
add("")
add("Everything the report, the slides and the video need, in one place. This file is written by "
"`scripts/export_results.py` from a full run, so every number here comes from the run itself. "
"Re-run that script after a new run; do not edit this file by hand.")
add("")
add(f"- **Results from commit:** `{cars_info['code_version']}` (batch study), "
f"`{info.get('code_version')}` (model); exported {datetime.now(timezone.utc):%Y-%m-%d}.")
add("- **Links:** " + " · ".join(f"[{name}]({LINKS[k]})" for k, name in LINK_NAMES.items()))
add("- **Significance marks below:** \\*\\* p < 0.05, \\* p < 0.10, from the test clustered by event date "
f"(each event date counts once), at {CONFIDENCE:.0%} confidence.")
add("")
add("## 1. The data")
add("")
add(f"- **{len(retailers)} US-listed retailers** ({len(online)} online, {len(retailers) - len(online)} store), "
f"plus {MARKET_TICKER} as the market, daily from {STUDY_START_YEAR} to {STUDY_END_YEAR}: "
f"**{len(master):,} stock-days** in `clean/master.parquet` ({master['date'].nunique():,} trading days).")
add(f"- **Events:** {', '.join(names[e['event_type']] for e in load_event_types(in_scope_only=True))}. "
f"**{len(scored):,} event windows** with a CAR (one per retailer and event occurrence; "
f"{scored[['event_type', 'day0_date']].drop_duplicates().shape[0]} occurrences).")
add(f"- **The stream scored {len(signals):,} stock-days** (the first {ESTIMATION_DAYS} trading days of each "
"stock only build its baseline).")
add("- **Attention:** daily Wikipedia pageviews of each company (real users, no bots). GDELT news and the "
"Census retail sales are out of scope (decision 0012).")
add("")
add("## 2. Is the stream right?")
add("")
add("Three independent computations of the same numbers must agree: the streaming job (day by day, with "
"state, late data), a direct numpy recomputation (`scripts/check_streaming.py`), and the batch event "
"study (`src/eventstudy/car.py`, the answer key; `scripts/compare_stream_batch.py`).")
add("")
add("| Run | Stream vs direct computation | Stream vs batch answer key |")
add("|---|---|---|")
def verdict(ok, text, words):
found = lines_with(text, *words)
return ("**OK** · " if ok else "**FAILED** · ") + "; ".join(found[:2]).replace("|", "/")
add(f"| Laptop, local files, 2% of messages 3 days late | {verdict(local_ok, local_check, ['event CAR:', 'daily:'])} "
f"| {verdict(local_cmp_ok, local_cmp, ['joined on'])} |")
if cluster:
add(f"| SFU cluster, course Kafka, YARN{(' · ' + args.cluster_note) if args.cluster_note else ''} "
f"| {verdict(cluster[0], cluster[1], ['event CAR:', 'daily:'])} | {verdict(cluster[2], cluster[3], ['joined on'])} |")
add("")
add("The full output of each check is in [`checks/`](checks/).")
add("")
add("## 3. Do retail stocks move abnormally around events?")
add("")
add(f"Mean cumulative abnormal return (CAR) over trading days {EVENT_WINDOW[0]} to +{EVENT_WINDOW[1]}, "
f"with its {CONFIDENCE:.0%} confidence interval and the clustered p-value.")
add("")
add("| Event | All retailers | Online | Store | Online − store |")
add("|---|---|---|---|---|")
order = [e["event_type"] for e in load_event_types(in_scope_only=True)] + [ALL]
groups = ["all", "online", "store", "online_minus_store"]
for ev in order:
row = summary[summary["event_type"] == ev].set_index("group")
if row.empty:
continue
cells = []
for g in groups:
if g in row.index:
r = row.loc[g]
cells.append(f"{pct(r.mean_car)}{stars(r.p_clustered)} [{pct(r.ci_low)}, {pct(r.ci_high)}] "
f"p={p(r.p_clustered)}")
else:
cells.append("–")
label = "All events (each window once)" if ev == ALL else names.get(ev, ev)
add(f"| {label} | " + " | ".join(cells) + " |")
add("")
sig = summary[summary["p_clustered"] < 0.10].sort_values("p_clustered")
add("**What stands out** (p < 0.10):")
add("")
for r in sig.itertuples():
label = "all events" if r.event_type == ALL else names.get(r.event_type, r.event_type)
group = r.group.replace("_minus_", " minus ").replace("all", "all retailers")
add(f"- {label}, {group}: {pct(r.mean_car)} (p = {p(r.p_clustered)}, {r.n_events} event dates, "
f"{r.n_windows} windows)")
add("")
add(f"Note: US Thanksgiving's market is closed, so its window is Black Friday's; the two rows are the same windows.")
add("")
add(f"## 4. Is the effect changing? Trends and a {events['forecast_year']} forecast")
add("")
add(f"Each year's average CAR regressed on the year; the forecast extends that line to "
f"{events['forecast_year']} with a {CONFIDENCE:.0%} prediction interval (where one year's value should fall).")
add("")
add(f"| Event | Change per year | p | {events['forecast_year']} forecast | Prediction interval |")
add("|---|---|---|---|---|")
for e in events["event_types"]:
g = e["groups"]["all"]
tr = g["trend"]
f = g["forecast"]
add(f"| {e['name']} | {pct(tr['slope'], 2)} | {p(tr['p'])}{stars(tr['p'])} | {pct(f['mid'][-1])} "
f"| {pct(f['lo'][-1])} to {pct(f['hi'][-1])} |")
add("")
add("The intervals are wide: ten yearly values cannot pin down next year's CAR. Read the forecast as the "
"trend, not a prediction of the market.")
add("")
add("## 5. Attention: does Wikipedia move with the events?")
add("")
add("| Stock-days | How many | With an abnormal return | With an attention spike |")
add("|---|---|---|---|")
for inside, r in rates.iterrows():
add(f"| {'Inside event windows' if inside else 'Outside event windows'} | {int(r.stock_days):,} "
f"| {r.abnormal:.1%} | {r.spikes:.1%} |")
if {True, False} <= set(rates.index):
add("")
add(f"Inside event windows, attention spikes (views ≥ {ATTENTION_SPIKE_Z} sd above their recent level) are "
f"{rates.loc[True, 'spikes'] / rates.loc[False, 'spikes']:.1f}× as common, and abnormal returns "
f"(|z| ≥ {ABNORMAL_RETURN_Z}) {rates.loc[True, 'abnormal'] / rates.loc[False, 'abnormal']:.1f}× as common.")
add("")
add("## 6. The big-move model (Spark MLlib)")
add("")
add(f"Predicts whether tomorrow's |abnormal return| will be at least {ABNORMAL_RETURN_Z} times its usual size. "
f"Fitted on {info['fit_years'][0]}–{info['fit_years'][1]}, chosen on the validation year, tested once on "
f"{info['test_years'][0]}–{info['test_years'][1]} (a purged time split). Model: {info['model']} "
f"({', '.join(f'{k}={v}' for k, v in info['params'].items())}).")
add("")
add("| Model (test years) | ROC-AUC | PR-AUC | Big moves among the top 5% flags | Lift over the base rate |")
add("|---|---|---|---|---|")
labels = {"all": "Gradient-boosted trees, all features", "no_attention": "Same, without the Wikipedia features",
"abs_z_ar": "Baseline: today's |z_ar| alone"}
for feat, label in labels.items():
if feat in test.index:
r = test.loc[feat]
add(f"| {label} | {r.auc_roc:.3f} | {r.auc_pr:.3f} | {r.precision_top:.1%} | {r.lift_top:.1f}× |")
add("")
add(f"Base rate: {info['test']['base_rate']:.1%} of test stock-days are big moves. "
f"Top inputs: {', '.join(importance['feature'].head(5))}.")
add("")
bf = next((e for e in events["event_types"] if e["groups"]["all"]["model"]["big_move"]), None)
if bf:
m = bf["groups"]["all"]["model"]
peak = int(np.nanargmax(m["big_move"]))
add(f"Around {bf['name']} in the test years, big moves peak on day {events['days'][peak]:+d} "
f"({m['big_move'][peak]:.0%} of retailers, against {m['base_rate']:.1%} on an ordinary day), and the "
f"model flags most on day {events['days'][int(np.nanargmax(m['flagged']))]:+d}. It mostly reacts to a "
"burst of big moves rather than anticipating the first one.")
add("")
add("## 7. Charts")
add("")
for c, caption in CHARTS.items():
if (OUT / "charts" / c).exists():
add(f"**{caption}**")
add("")
add(f"")
add("")
add("## 8. Limitations")
add("")
add("- One-factor market model (S&P 500 only); a Fama-French model could change individual CARs.")
add(f"- About ten occurrences per event: the trends and the {events['forecast_year']} forecasts have wide intervals.")
add("- The retailers share each event date, so the evidence is the number of event dates, not windows; "
"the clustered test accounts for this, and some p-values are near 0.05–0.10.")
add("- Many tests at once (events × groups): a few p < 0.05 results are expected by chance alone.")
add("- The big-move model ranks days (ROC-AUC ~0.69) but is not calibrated and is not a trading strategy.")
add("- Wikipedia is the only attention measure; GDELT and retail sales are future work (decision 0012).")
add("")
add("## 9. How to reproduce")
add("")
add("```bash")
add("./run_everything.sh --skip-etl --late-test # stream, checks, batch study, comparison, model")
add("python3 src/hosting/snapshot.py # the dashboard's recording and forecasts")
add("python3 scripts/export_results.py # this folder")
add("```")
add("")
(OUT / "README.md").write_text("\n".join(L) + "\n")
print(f"wrote {OUT}/README.md, {len(TABLES)} tables, {len(list((OUT / 'charts').glob('*.png')))} charts, "
f"{len(list((OUT / 'checks').glob('*.txt')))} check outputs")
print(f"local checks: stream vs direct {'OK' if local_ok else 'FAILED'}, stream vs batch {'OK' if local_cmp_ok else 'FAILED'}"
+ (f"; cluster: {'OK' if cluster[0] else 'FAILED'}, {'OK' if cluster[2] else 'FAILED'}" if cluster else ""))
if __name__ == "__main__":
main()