Files
Valve_research/matched_study.py
T
2026-11-27 00:13:33 +01:00

177 lines
7.7 KiB
Python

"""
Matched stacked event study.
For each clean crossing (event_study.find_events) build a stack: the crossing game plus up to K_CTRL
look-alike games that, over the same calendar window, never change label bucket.
Controls match on: same group (sp/mp/both), genre overlap, review count, age, pre-crossing inflow,
and score within S_BAND of the cutoff on the event date.
ln(1+R) = unit FE (game within stack) + date FE (within stack) + treat x post | donut dropped
Signed: down-crossings are flipped so one coefficient = "label effect". Cluster: treated game.
"""
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, DATA_GLOB, MIN_REVIEWS
from event_study import find_events, EV_WIN, EV_BIN
ALL_CUTS = [0.20, 0.40, 0.70, 0.80, 0.95] # controls must not cross ANY of these in the window
REAL_CUTS, PLACEBO_CUTS = [0.70, 0.80], [0.75, 0.85]
K_CTRL = 3 # controls per event
S_BAND = 0.03 # control score within 3 pp of the cutoff on the event date
N_TOL = np.log(2) # review count within a factor 2
AGE_TOL = 0.7 # |ln(1+age) difference|
PRE_TOL = 0.5 # |difference in mean ln(1+R), days -30..-7|
MIN_JACC = 0.34 # minimum genre overlap
MIN_COV = 0.8 # control needs lnR on 80% of window days
DONUT = 3 # drop days -3..-1 from the step estimate
REF_BIN = -3 # reference bin = days -9..-7 (not the burst days)
MIN_EVENTS = 20
def jacc(a, b):
return len(a & b) / len(a | b) if (a | b) else 0.0
def match(ev_all, L, S, N, meta):
stacks, dropped = [], 0
for eid, e in ev_all.groupby("eid"):
e = e.sort_values("k")
s0, c = e["sheet"].iloc[0], e["cutoff"].iloc[0]
t0 = e["date"].iloc[0] - pd.Timedelta(days=int(e["k"].iloc[0]))
dates = pd.date_range(t0 - pd.Timedelta(days=EV_WIN), t0 + pd.Timedelta(days=EV_WIN - 1))
kk = np.arange(-EV_WIN, EV_WIN)
pre = (kk >= -30) & (kk <= -7)
cand = meta.index[(meta["group"] == meta.at[s0, "group"]) & (meta.index != s0)]
Lw = L.reindex(dates)[cand]
keep = Lw.notna().mean() >= MIN_COV
cand = cand[keep.to_numpy()]
Lw, Sw = Lw[cand], S.reindex(dates)[cand]
if len(cand) == 0:
dropped += 1
continue
d = pd.DataFrame(index=cand)
d["near"] = (Sw.loc[t0] - c).abs() <= S_BAND
d["dN"] = (np.log(N.loc[t0, cand].clip(lower=1)) - np.log(max(N.loc[t0, s0], 1))).abs()
d["dAge"] = (np.log1p((t0 - meta.loc[cand, "first"]).dt.days)
- np.log1p((t0 - meta.at[s0, "first"]).days)).abs()
d["dPre"] = (Lw[pre].mean() - L.reindex(dates)[s0][pre].mean()).abs()
d["jac"] = [jacc(meta.at[x, "genres"], meta.at[s0, "genres"]) for x in cand]
d = d[d["near"] & (d["dN"] <= N_TOL) & (d["dAge"] <= AGE_TOL)
& (d["dPre"] <= PRE_TOL) & (d["jac"] >= MIN_JACC) & (N.loc[t0, d.index] >= MIN_REVIEWS)]
# same label bucket for the whole window (no label change for the control)
ok = []
for x in d.index:
b = np.digitize(Sw[x].dropna().to_numpy(), ALL_CUTS)
ok.append(len(b) > 0 and b.min() == b.max())
d = d[ok]
if d.empty:
dropped += 1
continue
d["dist"] = d["dPre"] / PRE_TOL + d["dN"] / N_TOL + d["dAge"] / AGE_TOL + (1 - d["jac"])
ctrl = list(d.sort_values("dist").index[:K_CTRL])
for sheet, treat in [(s0, 1)] + [(x, 0) for x in ctrl]:
f = pd.DataFrame({"date": dates, "k": kk, "lnR": L.reindex(dates)[sheet].to_numpy()})
f["stack"], f["treat"], f["sheet"], f["tsheet"] = eid, treat, sheet, s0
f["unit"] = f"{eid}|{sheet}"
stacks.append(f)
print(f" events without a usable control: {dropped}")
return pd.concat(stacks, ignore_index=True) if stacks else pd.DataFrame()
def prep(st):
st = st.dropna(subset=["lnR"]).copy()
st["gid"] = pd.factorize(st["tsheet"])[0]
st["unit_i"] = pd.factorize(st["unit"])[0]
st["sk"] = pd.factorize(st["stack"] + "_" + st["k"].astype(str))[0]
st["kb"] = np.floor_divide(st["k"], EV_BIN)
return st
def estimate(st):
cl = {"CRV1": "gid"}
names = {}
for b in sorted(st["kb"].unique()):
if b == REF_BIN:
continue
nm = f"t_{'m' if b < 0 else 'p'}{abs(b)}"
st[nm] = ((st["kb"] == b) & (st["treat"] == 1)).astype(int) * st["sgn"]
names[b] = nm
m = pf.feols(f"lnR ~ {' + '.join(names.values())} | unit_i + sk", data=st, vcov=cl)
t = m.tidy()
co = [(b, float(t.loc[nm, "Estimate"]), float(t.loc[nm, "Std. Error"]))
for b, nm in names.items() if nm in t.index] + [(REF_BIN, 0.0, 0.0)]
co = pd.DataFrame(co, columns=["kb", "est", "se"]).sort_values("kb")
d = st[~st["k"].between(-DONUT, -1)].copy()
d["tp"] = ((d["k"] >= 0) & (d["treat"] == 1)).astype(int) * d["sgn"]
ms = pf.feols("lnR ~ tp | unit_i + sk", data=d, vcov=cl)
ts = ms.tidy()
step = dict(est=float(ts.loc["tp", "Estimate"]), se=float(ts.loc["tp", "Std. Error"]),
p=float(ts.loc["tp", "Pr(>|t|)"]))
return co, step
def plot(co, title, path):
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.errorbar(co["kb"] * EV_BIN, co["est"], yerr=1.96 * co["se"], fmt="o-", capsize=3)
ax.axhline(0, color="grey", lw=0.8)
ax.axvline(-0.5, color="red", ls="--", lw=0.8)
ax.set_xlabel(f"days since crossing ({EV_BIN}-day bins)")
ax.set_ylabel("treated minus matched controls (signed)")
ax.set_title(title)
fig.tight_layout()
fig.savefig(path, dpi=150)
plt.close(fig)
if __name__ == "__main__":
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest")
df = build(add_groups(load(DATA_GLOB)))
L = df.pivot(index="date", columns="sheet", values="lnR")
S = df.pivot(index="date", columns="sheet", values="S_lag")
N = df.pivot(index="date", columns="sheet", values="N_lag")
meta = df.groupby("sheet").agg(group=("group", "first"), first=("date", "min"),
genres=("genres", "first"))
meta["genres"] = meta["genres"].fillna("").map(lambda s: {g for g in s.split(";") if g and g != "none"})
L, S, N = L[meta.index], S[meta.index], N[meta.index]
rows = []
for kind, cuts in [("real", REAL_CUTS), ("placebo", PLACEBO_CUTS)]:
parts = []
for direction, sgn in [("up", 1), ("down", -1)]:
print(f"[{kind} {direction}] matching...")
ev = find_events(df, cuts, direction)
if ev.empty:
continue
st = match(ev, L, S, N, meta)
if st.empty:
continue
st["sgn"] = sgn
parts.append((direction, st))
for label, sts in [(d, [s]) for d, s in parts] + [("pooled", [s for _, s in parts])]:
st = prep(pd.concat(sts, ignore_index=True))
n_ev = st.loc[st["treat"] == 1, "stack"].nunique()
if n_ev < MIN_EVENTS:
print(f"[{kind} {label}] only {n_ev} matched events, skipped")
continue
co, step = estimate(st)
rows.append(dict(kind=kind, sample=label, events=n_ev,
games=st.loc[st["treat"] == 1, "tsheet"].nunique(),
ctrl_per_event=st.loc[st["treat"] == 0, "unit"].nunique() / n_ev,
pct=100 * (np.exp(step["est"]) - 1), **step))
plot(co, f"{kind} {label}: matched stacked event study, {n_ev} events",
f"matched_{kind}_{label}.png")
res = pd.DataFrame(rows)
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
pd.set_option("display.width", 200)
print(res.to_string(index=False))
res.to_csv("matched_results.csv", index=False)