""" Event study around the first clean crossing of a review-label cutoff. For each game and cutoff we find the first day t0 where the lagged score S_{t-1} crosses c (up: from below to above; down: from above to below), requiring a clean crossing: - PRE_CLEAN days before t0 the score stayed on the old side, - PERSIST days from t0 the score stayed on the new side. Then, in a +-EV_WIN day window around t0: ln(1+R) = event FE + date FE + sum_k b_k * 1[bin(k)=k] (reference bin: -1) Plots b_k (event-study) and the share of days above the cutoff (first stage). Also a step estimate: ln(1+R) = post + k + k*post | event FE + date FE. Expected sign if the label matters: positive for up-crossings, negative for down-crossings. """ import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import pyfixest as pf from game_test import load, add_groups, build, boot_p, DATA_GLOB, MIN_REVIEWS # ----------------------------------------------------------------- settings EV_WIN = 30 # days before/after the crossing EV_BIN = 3 # bin width in days (daily data is too noisy) PRE_CLEAN = 14 # days before crossing that must be on the old side PERSIST = 7 # days from crossing that must be on the new side (1 = intent-to-treat) REAL_CUTS = [0.70, 0.80] # 0.95 adds almost no events PLACEBO_CUTS = [0.75, 0.85] # no label change here MIN_EVENTS = 15 # skip cells with fewer events BOOT_REPS = 499 # ----------------------------------------------------------------- events def find_events(df, cutoffs, direction): out = [] for sheet, g in df.groupby("sheet"): g = g.sort_values("date") grp = g["group"].iloc[0] g = g.set_index("date") g = g.reindex(pd.date_range(g.index.min(), g.index.max(), freq="D")) S, L, N = g["S_lag"].to_numpy(), g["lnR"].to_numpy(), g["N_lag"].to_numpy() n, dates = len(S), g.index known = ~np.isnan(S) for c in cutoffs: above = S >= c if direction == "up": hits = np.where(above[1:] & ~above[:-1] & known[1:] & known[:-1])[0] + 1 else: hits = np.where(~above[1:] & above[:-1] & known[1:] & known[:-1])[0] + 1 for t in hits: if t < PRE_CLEAN or t + PERSIST > n or not N[t] >= MIN_REVIEWS: continue pre, post = S[t - PRE_CLEAN:t], S[t:t + PERSIST] pk, qk = ~np.isnan(pre), ~np.isnan(post) if pk.mean() < 0.7 or qk.mean() < 0.7: continue if direction == "up": ok = (pre[pk] < c).all() and (post[qk] >= c).all() else: ok = (pre[pk] >= c).all() and (post[qk] < c).all() if not ok: continue idx = np.arange(max(t - EV_WIN, 0), min(t + EV_WIN, n)) k = idx - t fr = pd.DataFrame({"sheet": sheet, "group": grp, "cutoff": c, "eid": f"{sheet}_{c:.2f}", "k": k, "kb": np.floor_divide(k, EV_BIN), "lnR": L[idx], "D": above[idx].astype(int), "date": dates[idx]}) out.append(fr.dropna(subset=["lnR"])) break # first clean crossing only return pd.concat(out, ignore_index=True) if out else pd.DataFrame() # ----------------------------------------------------------------- estimation def estimate(ev): ev = ev.copy() ev["gid"] = pd.factorize(ev["sheet"])[0] # integer cluster id (numba) ev["eid_i"] = pd.factorize(ev["eid"])[0] ev["date_i"] = pd.factorize(ev["date"])[0] ref = -1 names = {} for b in sorted(ev["kb"].unique()): if b == ref: continue nm = f"k_{'m' if b < 0 else 'p'}{abs(b)}" ev[nm] = (ev["kb"] == b).astype(int) names[b] = nm cl = {"CRV1": "gid"} m = pf.feols(f"lnR ~ {' + '.join(names.values())} | eid_i + date_i", data=ev, vcov=cl) t = m.tidy() coefs = [] for b, nm in names.items(): if nm in t.index: e, s = float(t.loc[nm, "Estimate"]), float(t.loc[nm, "Std. Error"]) coefs.append((b, e, s)) coefs.append((ref, 0.0, 0.0)) coefs = pd.DataFrame(coefs, columns=["kb", "est", "se"]).sort_values("kb") ev["post"] = (ev["k"] >= 0).astype(int) ev["k_post"] = ev["k"] * ev["post"] ms = pf.feols("lnR ~ post + k + k_post | eid_i + date_i", data=ev, vcov=cl) ts = ms.tidy() step = dict(est=float(ts.loc["post", "Estimate"]), se=float(ts.loc["post", "Std. Error"]), p_cluster=float(ts.loc["post", "Pr(>|t|)"])) first_stage = ev.groupby("kb")["D"].mean() return coefs, step, first_stage def plot(coefs, first_stage, title, path): fig, (a1, a2) = plt.subplots(2, 1, figsize=(8, 7), sharex=True, gridspec_kw={"height_ratios": [3, 1.3]}) x = coefs["kb"] * EV_BIN a1.errorbar(x, coefs["est"], yerr=1.96 * coefs["se"], fmt="o-", capsize=3) a1.axhline(0, color="grey", lw=0.8) a1.axvline(-0.5, color="red", ls="--", lw=0.8) a1.set_ylabel("ln(1+reviews) vs bin -1") a1.set_title(title) a2.plot(first_stage.index * EV_BIN, first_stage.values, "s-") a2.axvline(-0.5, color="red", ls="--", lw=0.8) a2.set_ylim(0, 1) a2.set_ylabel("share above cutoff") a2.set_xlabel(f"days since crossing (bin start, {EV_BIN}-day bins)") fig.tight_layout() fig.savefig(path, dpi=150) plt.close(fig) def pooled_signed(ev_up, ev_down): ev = pd.concat([ev_up.assign(sgn=1, dirn="up"), ev_down.assign(sgn=-1, dirn="down")], ignore_index=True) ev["eid"] = ev["eid"] + "_" + ev["dirn"] ev["gid"] = pd.factorize(ev["sheet"])[0] ev["eid_i"] = pd.factorize(ev["eid"])[0] ev["date_dir"] = pd.factorize(ev["date"].astype(str) + "_" + ev["dirn"])[0] # date FE per direction ev["post"] = (ev["k"] >= 0).astype(int) ev["post_s"] = ev["post"] * ev["sgn"] # +post for up, -post for down up = (ev["sgn"] == 1).astype(int) ev["kp_up"] = ev["k"] * ev["post"] * up # linear trend is absorbed by the FEs, ev["kp_dn"] = ev["k"] * ev["post"] * (1 - up) # only the change at the crossing is identified m = pf.feols("lnR ~ post_s + kp_up + kp_dn | eid_i + date_dir", data=ev, vcov={"CRV1": "gid"}) t = m.tidy() return (float(t.loc["post_s", "Estimate"]), float(t.loc["post_s", "Std. Error"]), float(t.loc["post_s", "Pr(>|t|)"]), ev["eid"].nunique(), ev["sheet"].nunique()) # ----------------------------------------------------------------- run if __name__ == "__main__": import warnings warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest") df = build(add_groups(load(DATA_GLOB))) rows, pooled = [], [] for kind, cuts in [("real", REAL_CUTS), ("placebo", PLACEBO_CUTS)]: ups, downs = find_events(df, cuts, "up"), find_events(df, cuts, "down") # ---- pooled signed step (up and down combined) if not ups.empty and not downs.empty: e, s, p, n_ev, n_g = pooled_signed(ups, downs) print(f"{kind}: signed step {e:.4f} (SE {s:.4f}, p {p:.3f}), " f"{n_ev} events, {n_g} games, {100*(np.exp(e)-1):.1f}%") pooled.append(dict(kind=kind, est=e, se=s, p_cluster=p, events=n_ev, games=n_g, pct=100 * (np.exp(e) - 1))) # ---- per direction and group, with plots for direction, ev_all in [("up", ups), ("down", downs)]: if ev_all.empty: print(f"[{kind} {direction}] no events") continue for grp in [None, "sp", "mp", "both"]: ev = ev_all if grp is None else ev_all[ev_all["group"] == grp] n_ev = ev["eid"].nunique() label = f"{kind} {direction} {grp or 'all'}" if n_ev < MIN_EVENTS: print(f"[{label}] only {n_ev} events, skipped") continue coefs, step, fs = estimate(ev) rows.append(dict(kind=kind, direction=direction, group=grp or "all", cutoffs=",".join(f"{c:.2f}" for c in cuts), events=n_ev, games=ev["sheet"].nunique(), pct=100 * (np.exp(step["est"]) - 1), **step)) if grp is None: plot(coefs, fs, f"{kind}: {direction}-crossings of {cuts}, {n_ev} events", f"event_{kind}_{direction}.png") fake = [0.725, 0.775, 0.825, 0.875, 0.925] out = [] for c in fake: u, d = find_events(df, [c], "up"), find_events(df, [c], "down") if u.empty or d.empty or u["eid"].nunique() < 10 or d["eid"].nunique() < 10: print(f"fake {c}: too few events, skipped") continue e, s, p, n_ev, n_g = pooled_signed(u, d) out.append(dict(cutoff=c, est=e, se=s, p=p, events=n_ev)) pl = pd.DataFrame(out) print(pl.to_string(index=False)) print("real est 0.104 vs placebo estimates above bigger:", int((pl["est"] > 0.104).sum()), "of", len(pl)) real_est = pooled[0]["est"] # the "real" row, computed in the loop above print(f"real est {real_est:.3f}; placebo estimates larger: " f"{int((pl['est'] > real_est).sum())} of {len(pl)}") pd.set_option("display.float_format", lambda x: f"{x:.4f}") pd.set_option("display.width", 220) res = pd.DataFrame(rows).drop(columns=["p_boot"], errors="ignore") # p_boot is broken here print("\nSTEP ESTIMATES (post = jump at crossing, log points; use p_cluster):") print(res.to_string(index=False)) res.to_csv("event_results.csv", index=False) pd.DataFrame(pooled).to_csv("event_pooled.csv", index=False) print("Saved event_results.csv, event_pooled.csv and event_*.png")