"""Build the recorded stream and event history the dashboard shows (decisions 0010 and 0013).
The dashboard's Replay and Event history views (src/dashboard/app.py) read these files, on a
laptop and hosted, so the hosted app works without Kafka or Spark. They are committed (derived
statistics only, about 1 MB), so a fresh clone can show them too. This script writes three
files into hosting/snapshot/:
replay.json the streaming job's output for every year (rows in replay_rows.parquet), which
the Replay view plays day by day: each stock-day's abnormal return, z-scores,
Wikipedia views and alerts, the big-move model's prediction, and each
event window's CAR on the day it closes. It plays the model's test years by
default, the only years the model never saw in training.
events.json for each event type: every year's average cumulative abnormal return
over the window (days -5..+5), the average across the years, a
straight-line trend through the years extended one year ahead with a
prediction interval, and what the big-move model expected on each day
of the window in the test years against what happened.
meta.json when and from which commit it was built, and the model's test scores.
Nothing here is a price, a volume or a raw return: Yahoo's terms do not allow
republishing those. Abnormal returns, z-scores and CARs are our own statistics, and
Wikipedia pageviews are public (CC0).
Run after run_everything.sh (it needs the batch study, the model and a streaming run):
python3 src/hosting/snapshot.py
Then look at it: streamlit run src/dashboard/app.py (views Replay and Event history)
"""
from __future__ import annotations
import bisect
import json
import math
from datetime import datetime, timezone
import numpy as np
import pandas as pd
from scipy import stats
from common.contracts import expand_events, load_event_types, load_retailers
from common.settings import (BIG_MOVE_MODEL_INFO, RESULTS_DIR, SNAPSHOT_DIR, STREAM_DIR,
STREAM_SUBDIRS)
from common.study import (ABNORMAL_RETURN_Z, ATTENTION_SPIKE_Z, CONFIDENCE, EVENT_WINDOW,
ML_TEST_START_YEAR, STUDY_END_YEAR, STUDY_START_YEAR)
from eventstudy.car import OUTPUT as CARS
from eventstudy.car import code_version
from eventstudy.charts import mean_with_ci, short, window_paths
from eventstudy.stats import ALL, SUMMARY, TREND
TEST_PREDICTIONS = RESULTS_DIR / "ml_test_predictions.parquet"
DAYS = list(range(EVENT_WINDOW[0], EVENT_WINDOW[1] + 1))
FORECAST_YEAR = STUDY_END_YEAR + 1
def clean(value, digits: int):
"""A JSON-safe rounded number: NaN and None become null."""
if value is None or (isinstance(value, float) and math.isnan(value)):
return None
return round(float(value), digits)
def column(values, digits: int) -> list:
return [clean(v, digits) for v in values]
def whole(values) -> list:
"""Counts and 0/1 flags as JSON integers (null when missing)."""
return [None if pd.isna(v) else int(v) for v in values]
def read_stream(dataset: str) -> pd.DataFrame:
"""Every micro-batch of one streaming output that Spark finished writing."""
folder = STREAM_DIR / STREAM_SUBDIRS[dataset]
done = [p for p in folder.glob("batch_id=*") if (p / "_SUCCESS").exists()]
if not done:
raise SystemExit(f"No finished micro-batches in {folder}: run the streaming job first.")
df = pd.concat([pd.read_parquet(p) for p in done], ignore_index=True)
for col in ("date", "day0_date", "event_date"):
if col in df:
df[col] = pd.to_datetime(df[col])
return df
# ---------------------------------------------------------------- event history and forecast
def trend_forecast(years, values, at: int, confidence: float = CONFIDENCE) -> dict | None:
"""Straight line through (year, value) by ordinary least squares, extended to year `at`.
The interval is a prediction interval: where one new year's value should fall, not
just the line. It is wider than the line's own confidence band because a single year
scatters around the line: t * s * sqrt(1 + 1/n + (at - mean year)^2 / Sxx).
None with fewer than three years.
"""
x = np.asarray(years, dtype=float)
y = np.asarray(values, dtype=float)
ok = ~np.isnan(y)
x, y = x[ok], y[ok]
n = len(x)
if n < 3:
return None
fit = stats.linregress(x, y)
s = np.sqrt(((y - (fit.intercept + fit.slope * x)) ** 2).sum() / (n - 2))
t = stats.t.ppf((1 + confidence) / 2, n - 2)
mid = fit.intercept + fit.slope * at
half = t * s * np.sqrt(1 + 1 / n + (at - x.mean()) ** 2 / ((x - x.mean()) ** 2).sum())
return {"mid": mid, "lo": mid - half, "hi": mid + half, "n": n,
"slope": fit.slope, "intercept": fit.intercept, "p": fit.pvalue,
"slope_lo": fit.slope - t * fit.stderr, "slope_hi": fit.slope + t * fit.stderr}
def yearly_paths(paths: pd.DataFrame, tickers: set | None = None) -> pd.DataFrame:
"""Average cumulative abnormal return on each window day, one row per event
occurrence (columns: event_type, day0_date, year, n_tickers, then one per day).
`paths` comes from eventstudy.charts.window_paths; `tickers` limits it to a group."""
if tickers is not None:
paths = paths[paths["ticker"].isin(tickers)]
wide = (paths.groupby(["event_type", "day0_date", "day"])["car"].mean()
.unstack("day").reindex(columns=DAYS))
wide.columns = [str(d) for d in wide.columns]
counts = paths.groupby(["event_type", "day0_date"])["ticker"].nunique().rename("n_tickers")
out = wide.join(counts).reset_index()
out.insert(2, "year", pd.to_datetime(out["day0_date"]).dt.year)
return out
def distinct_event_types(cars: pd.DataFrame) -> list[tuple[str, list[str]]]:
"""Event types in config order, merging types that share every window.
US Thanksgiving falls on a market holiday, so its day 0 is Black Friday and the two
have the same windows. They are shown once, under the type whose calendar date is a
trading day; the other is listed as `also`.
"""
order = [e["event_type"] for e in load_event_types(in_scope_only=True)]
day0s = {t: frozenset(cars.loc[cars["event_type"] == t, "day0_date"]) for t in order}
on_day0 = {t: (cars.loc[cars["event_type"] == t, "event_date"].astype(str)
== cars.loc[cars["event_type"] == t, "day0_date"].astype(str)).mean() for t in order}
shown, seen = [], set()
for t in order:
if t in seen or not day0s[t]:
continue
same = [u for u in order if day0s[u] == day0s[t]]
keep = max(same, key=lambda u: (on_day0[u], -order.index(u)))
seen.update(same)
shown.append((keep, [u for u in same if u != keep]))
return shown
def model_by_day(cars: pd.DataFrame, test: pd.DataFrame, trading_days: list) -> pd.DataFrame:
"""What the big-move model expected on each window day, against what happened.
A prediction made on day t is about day t+1, so window day d is scored by the row of
the trading day before it. Only windows in the model's test years are used.
Columns: event_type, ticker, day, flag (1 if the model flagged it), y (1 if it was a big move).
`test` must carry the flag column (see build_events).
"""
index = {pd.Timestamp(d): i for i, d in enumerate(trading_days)}
windows = cars[pd.to_datetime(cars["day0_date"]).dt.year >= ML_TEST_START_YEAR]
rows = []
for w in windows.itertuples():
i0 = index.get(pd.Timestamp(w.day0_date))
if i0 is None:
continue
for d in DAYS:
j = i0 + d - 1
if 0 <= j < len(trading_days):
rows.append((w.event_type, w.ticker, d, pd.Timestamp(trading_days[j])))
frame = pd.DataFrame(rows, columns=["event_type", "ticker", "day", "date"])
test = test.assign(date=pd.to_datetime(test["date"]))
out = frame.merge(test, on=["ticker", "date"], how="inner")
return out.rename(columns={"big_move_next": "y"})[["event_type", "ticker", "day", "flag", "y"]]
def group_block(event_type, rows: pd.DataFrame, summary: pd.DataFrame, group: str,
risk: pd.DataFrame, test: pd.DataFrame) -> dict:
"""Everything the event view draws for one event type and one retailer group."""
rows = rows[rows["event_type"] == event_type].sort_values("year")
days = [str(d) for d in DAYS]
years = rows["year"].tolist()
mean, lo, hi, forecast = [], [], [], {"mid": [], "lo": [], "hi": []}
for d in days:
m, a, b = mean_with_ci(rows[d].dropna())
mean.append(m), lo.append(a), hi.append(b)
f = trend_forecast(rows["year"], rows[d], FORECAST_YEAR)
for k in forecast:
forecast[k].append(f[k] if f else None)
trend = trend_forecast(rows["year"], rows[days[-1]], FORECAST_YEAR)
s = summary[(summary["event_type"] == event_type) & (summary["group"] == group)]
s = s.iloc[0] if len(s) else None
r = risk[risk["event_type"] == event_type].groupby("day").agg(
flag=("flag", "mean"), y=("y", "mean"), n=("y", "size")).reindex(DAYS)
return {
"years": years,
"n_tickers": rows["n_tickers"].astype(int).tolist(),
"paths": [column(rows.loc[rows["year"] == y, days].iloc[0], 5) for y in years],
"mean": column(mean, 5), "mean_lo": column(lo, 5), "mean_hi": column(hi, 5),
"forecast": {k: column(v, 5) for k, v in forecast.items()},
"trend": None if trend is None else {k: (clean(v, 6) if k != "n" else int(v)) for k, v in trend.items()},
"summary": None if s is None else {
"mean_car": clean(s["mean_car"], 5), "ci_low": clean(s["ci_low"], 5),
"ci_high": clean(s["ci_high"], 5), "p_clustered": clean(s["p_clustered"], 4),
"n_windows": int(s["n_windows"]), "n_events": int(s["n_events"]),
"n_tickers": int(s["n_tickers"])},
# Shares, so the two lines share one axis: the model's scores are not calibrated
# probabilities (training weighted both classes equally), but its flags are countable.
"model": {"flagged": column(r["flag"], 4), "big_move": column(r["y"], 4),
"n": [int(v) if not pd.isna(v) else 0 for v in r["n"]],
"flag_rate": clean(test["flag"].mean(), 4),
"base_rate": clean(test["big_move_next"].mean(), 4)},
}
def build_events(cars: pd.DataFrame, paths: pd.DataFrame, summary: pd.DataFrame,
test: pd.DataFrame, trading_days: list, alert_cutoff: float) -> dict:
test = test.assign(flag=(test["p_big_move_next"] >= alert_cutoff).astype(int))
retailers = load_retailers(in_scope_only=True)
names = {e["event_type"]: short(e["name"]) for e in load_event_types()}
groups = {ALL: None} | {g: {r["ticker"] for r in retailers if r["retailer_type"] == g}
for g in sorted({r["retailer_type"] for r in retailers})}
risk_all = model_by_day(cars[cars["n_days"] > 0], test, trading_days)
next_dates = {e["event_type"]: str(e["event_date"]) for e in expand_events(FORECAST_YEAR, FORECAST_YEAR)}
rows_by_group = {g: yearly_paths(paths, t) for g, t in groups.items()}
event_types = []
for event_type, also in distinct_event_types(cars[cars["n_days"] > 0]):
blocks = {}
for g, tickers in groups.items():
risk = risk_all if tickers is None else risk_all[risk_all["ticker"].isin(tickers)]
t = test if tickers is None else test[test["ticker"].isin(tickers)]
blocks[g] = group_block(event_type, rows_by_group[g], summary, g, risk, t)
event_types.append({"event": event_type, "name": names[event_type],
"also": [names[a] for a in also],
"next_date": next_dates.get(event_type), "groups": blocks})
return {"days": DAYS, "groups": list(groups), "forecast_year": FORECAST_YEAR,
"first_year": STUDY_START_YEAR, "last_year": STUDY_END_YEAR,
"test_years": [ML_TEST_START_YEAR, STUDY_END_YEAR],
"confidence": CONFIDENCE, "event_types": event_types}
def check_against_stats(events: dict, trend_table: pd.DataFrame):
"""The forecast's last day is the CAR, so its slope must equal stats.py's trend."""
for e in events["event_types"]:
mine = e["groups"][ALL]["trend"]
theirs = trend_table[trend_table["event_type"] == e["event"]]
if mine and len(theirs) and not np.isclose(mine["slope"], theirs["slope_per_year"].iloc[0], atol=1e-6):
raise SystemExit(f"{e['event']}: trend slope {mine['slope']} differs from "
f"{TREND.name} ({theirs['slope_per_year'].iloc[0]}). Re-run stats.py?")
# ---------------------------------------------------------------- replay of the stream
def build_replay(signals: pd.DataFrame, predictions: pd.DataFrame, windows: pd.DataFrame) -> tuple[dict, pd.DataFrame]:
"""The whole recorded stream, every year, for the Replay view: an index (days, tickers, event
windows, markers; JSON) and one row per stock-day (Parquet, about 1.5 MB). `start` is the first
day of the model's test years, which the view plays by default."""
retailers = load_retailers(in_scope_only=True)
tickers = [r["ticker"] for r in retailers]
signals = signals[signals["ticker"].isin(tickers)].sort_values(["ticker", "date"])
# Whether the NEXT trading day was a big move: the outcome each prediction is judged on.
signals = signals.assign(next_big=signals.groupby("ticker")["abnormal_return"].shift(-1))
days = [pd.Timestamp(d) for d in sorted(signals["date"].unique())]
start = next(i for i, d in enumerate(days) if d.year >= ML_TEST_START_YEAR)
day_index = {d: i for i, d in enumerate(days)}
rows = signals[signals["date"] >= days[0]].merge(
predictions[["ticker", "date", "p_big_move_next", "big_move_alert"]], on=["ticker", "date"], how="left")
rows = rows.assign(d=rows["date"].map(lambda d: day_index[pd.Timestamp(d)]),
t=rows["ticker"].map(tickers.index)).sort_values(["d", "t"])
closes = []
for w in windows.itertuples():
d0 = bisect.bisect_left(days, pd.Timestamp(w.day0_date))
close = d0 + EVENT_WINDOW[1]
if pd.Timestamp(w.day0_date) >= days[0] and close < len(days) and w.ticker in tickers:
closes.append({"close": close, "day0": pd.Timestamp(w.day0_date).strftime("%Y-%m-%d"),
"event": w.event_type, "t": tickers.index(w.ticker),
"car": clean(w.car, 5), "car_z": clean(w.car_z, 3),
"n_ab": int(w.n_abnormal_days), "n_sp": int(w.n_spike_days)})
closes.sort(key=lambda c: (c["close"], c["t"]))
names = {e["event_type"]: short(e["name"]) for e in load_event_types()}
markers = {}
first_year, last_year = pd.Timestamp(days[0]).year, pd.Timestamp(days[-1]).year
for e in expand_events(first_year, last_year):
d0 = bisect.bisect_left(days, pd.Timestamp(e["event_date"]))
if d0 < len(days) and pd.Timestamp(e["event_date"]) >= days[0]:
label = names[e["event_type"]]
markers.setdefault((d0, e["ticker"]), [])
if label not in markers[(d0, e["ticker"])]:
markers[(d0, e["ticker"])].append(label)
table = pd.DataFrame({
"d": rows["d"].astype("int32"), "t": rows["t"].astype("int16"),
"ar": rows["ar"].round(5), "z_ar": rows["z_ar"].round(2),
"ab": rows["abnormal_return"].astype("Int8"), "views": rows["views"].round().astype("Int64"),
"z_views": rows["z_views"].round(2), "sp": rows["attention_spike"].astype("Int8"),
"p": rows["p_big_move_next"].round(4), "alert": rows["big_move_alert"].astype("Int8"),
"next_big": rows["next_big"].astype("Int8")}).reset_index(drop=True)
return {
"days": [pd.Timestamp(d).strftime("%Y-%m-%d") for d in days],
"start": start,
"tickers": [{"ticker": r["ticker"], "company": r["company"], "type": r["retailer_type"]}
for r in retailers],
"rows": "replay_rows.parquet",
"windows": closes,
"events": [{"d": d, "ticker": t, "names": n} for (d, t), n in sorted(markers.items())],
"event_names": names,
"abnormal_z": ABNORMAL_RETURN_Z, "spike_z": ATTENTION_SPIKE_Z,
}, table
def write_meta(folder=SNAPSHOT_DIR):
"""meta.json: provenance and the model's test scores."""
info = json.loads(BIG_MOVE_MODEL_INFO.read_text()) if BIG_MOVE_MODEL_INFO.exists() else {}
meta = {"built_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"code_version": code_version(),
"model": {k: info.get(k) for k in ("model", "params", "alert_cutoff", "alert_top_share",
"fit_years", "test_years", "test")}}
folder.mkdir(parents=True, exist_ok=True)
(folder / "meta.json").write_text(json.dumps(meta, indent=2))
def write(name: str, payload: dict):
SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
path = SNAPSHOT_DIR / name
path.write_text(json.dumps(payload, separators=(",", ":"), allow_nan=False))
print(f"wrote {path} ({path.stat().st_size / 1e6:.2f} MB)")
def main():
cars = pd.read_parquet(CARS)
summary = pd.read_csv(SUMMARY)
trend_table = pd.read_csv(TREND)
test = pd.read_parquet(TEST_PREDICTIONS)
signals = read_stream("stream_signals")
trading_days = [pd.Timestamp(d) for d in sorted(signals["date"].unique())]
print("Event paths...")
cutoff = json.loads(BIG_MOVE_MODEL_INFO.read_text())["alert_cutoff"]
events = build_events(cars, window_paths(cars), summary, test, trading_days, cutoff)
check_against_stats(events, trend_table)
write("events.json", events)
replay, rows = build_replay(signals, read_stream("stream_predictions"), read_stream("stream_event_car"))
write("replay.json", replay)
rows.to_parquet(SNAPSHOT_DIR / replay["rows"], index=False)
print(f"wrote {SNAPSHOT_DIR / replay['rows']} ({(SNAPSHOT_DIR / replay['rows']).stat().st_size / 1e6:.2f} MB)")
write_meta()
print(f"replay: {len(replay['days'])} trading days ({replay['days'][0]} to {replay['days'][-1]}; plays from "
f"{replay['days'][replay['start']]} by default), {len(rows):,} stock-days, {len(replay['windows'])} event windows")
if __name__ == "__main__":
main()