""" Label-cutoff RD: difference-in-discontinuities ("did") and triple difference ("triple"). Memory-lean version: each game is processed on its own, only rows near a cutoff are kept, the trimmed panel is cached, and models are fitted one at a time. Inputs: game_tags.csv columns: sheet, genres, group ("sp"/"mp"/"both"), price data/.csv columns: date, positive, negative Usage: python game_test.py did --spec rd --group mp both sp --w 0.02 python game_test.py did --spec crossers --group mp both python game_test.py triple --spec rd crossers --w 0.02 python game_test.py did --spec rd --group sp --n-sp 300 # subsample single-player python game_test.py did --reps 299 # wild bootstrap (slow) python game_test.py did --rebuild # rebuild cached panel Install: pip install pandas numpy pyfixest """ import argparse import gc import os import warnings import numpy as np import pandas as pd # ----------------------------------------------------------------- settings DATA_DIR = "data" TAGS_FILE = "game_tags.csv" OUT_DID = "ell_did.csv" OUT_TRIPLE = "ell_triple.csv" GAME_GENRES = { 'Action', 'Indie', 'Simulation', 'Strategy', 'RPG', 'Early Access', 'Casual', 'Adventure', 'Free To Play', 'Massively Multiplayer', 'Racing', 'Sports', 'Episodic', } MIN_SPAN_DAYS = 365 MAX_SPAN_DAYS = 10 * 365 MIN_TOTAL_REVIEWS = 2000 MIN_REVIEWS = 500 # min cumulative reviews before a game-day is used TRIM_Q = 0.99 # drop each game's top 1% burst days (None = off) MIN_GAMES = 10 # per cell TIME_FE = "month" CUTOFFS = [0.70, 0.80, 0.95] PLACEBOS = [0.60, 0.75, 0.85, 0.90] SEED = 42 PANEL_W = 0.03 # panel keeps rows within this distance of any cutoff, PANEL_FILE = "panel_w03.pkl" # so any --w up to 0.03 can reuse it KEEP = ["sheet", "group", "MP", "BOTH", "lnR", "S_lag", "N_lag", "ln_N", "ln_age", "ln_price", "no_price", "month", "rel_year"] # ----------------------------------------------------------------- panel def load_tags(): tags = pd.read_csv(TAGS_FILE, dtype={"sheet": str}) tags["sheet"] = tags["sheet"].str.strip() tags = tags.drop_duplicates("sheet") tags["group"] = tags["group"].astype(str).str.strip().str.lower() if "price" not in tags.columns: tags["price"] = np.nan tags["price"] = pd.to_numeric(tags["price"], errors="coerce") return tags def process_game(d, sheet): """Score, lags, controls for one game; keep only rows near a cutoff.""" d = d.sort_values("date").reset_index(drop=True) R = d["positive"] + d["negative"] cum_tot = R.cumsum() score = d["positive"].cumsum() / cum_tot.replace(0, np.nan) out = pd.DataFrame({"S_lag": score.shift(1), "N_lag": cum_tot.shift(1), "R": R}) first = d["date"].iloc[0] out["lnR"] = np.log1p(R) out["ln_N"] = np.log(out["N_lag"].clip(lower=1)) out["ln_age"] = np.log1p((d["date"] - first).dt.days) out["month"] = d["date"].dt.to_period("M").astype(str) out["rel_year"] = str(first.year) if TRIM_Q is not None: out = out[out["R"] <= R.quantile(TRIM_Q)] out = out.dropna(subset=["S_lag", "N_lag"]) out = out[out["N_lag"] >= MIN_REVIEWS] cuts = np.array(CUTOFFS + PLACEBOS) near = (np.abs(out["S_lag"].to_numpy()[:, None] - cuts[None, :]) <= PANEL_W).any(axis=1) out = out[near].drop(columns="R") if out.empty: return None out["sheet"] = sheet return out def build_panel(tags): mask = tags["genres"].fillna("").str.split(";").apply( lambda gs: any(g.strip() in GAME_GENRES for g in gs)) games = tags[mask] print(f"tag rows: {len(tags)}, real games (genre filter): {len(games)}") frames, n_nofile, n_span, n_rev, n_near = [], 0, 0, 0, 0 for sheet in games["sheet"]: path = os.path.join(DATA_DIR, f"{sheet}.csv") if not os.path.exists(path): n_nofile += 1 continue d = pd.read_csv(path, parse_dates=["date"])[["date", "positive", "negative"]] d[["positive", "negative"]] = (d[["positive", "negative"]] .apply(pd.to_numeric, errors="coerce").fillna(0).abs()) if d.empty: n_nofile += 1 continue span = (d["date"].max() - d["date"].min()).days + 1 if not (MIN_SPAN_DAYS <= span <= MAX_SPAN_DAYS): n_span += 1 continue if d["positive"].sum() + d["negative"].sum() < MIN_TOTAL_REVIEWS: n_rev += 1 continue full = pd.date_range(d["date"].min(), d["date"].max(), freq="D") d = (d.groupby("date")[["positive", "negative"]].sum() .reindex(full, fill_value=0).rename_axis("date").reset_index()) g = process_game(d, sheet) if g is None: n_near += 1 continue frames.append(g) print(f"dropped: no file/empty {n_nofile}, span {n_span}, reviews {n_rev}, " f"never near a cutoff {n_near}; kept {len(frames)}") if not frames: raise SystemExit("No games left after filtering") df = pd.concat(frames, ignore_index=True) del frames df = df.merge(tags[["sheet", "group", "price"]], on="sheet", how="left") df = df[df["group"].isin(["sp", "mp", "both"])].copy() df["MP"] = (df["group"] == "mp").astype(int) df["BOTH"] = (df["group"] == "both").astype(int) df["no_price"] = df["price"].isna().astype(int) df["ln_price"] = np.log1p(df["price"].fillna(0)) df = df[KEEP] # S_lag stays float64 on purpose: float32 can put a score of exactly 0.70 below the cutoff for c in ["lnR", "N_lag", "ln_N", "ln_age", "ln_price"]: df[c] = df[c].astype("float32") for c in ["sheet", "group", "month", "rel_year"]: df[c] = df[c].astype("category") print("games per group:", df.groupby("group", observed=True)["sheet"].nunique().to_dict()) print(f"panel: {len(df):,} rows, {df.memory_usage(deep=True).sum() / 1e9:.2f} GB") return df def get_panel(rebuild=False): if os.path.exists(PANEL_FILE) and not rebuild: df = pd.read_pickle(PANEL_FILE) print(f"loaded cached panel {PANEL_FILE}: {len(df):,} rows, " f"{df['sheet'].nunique()} games") return df df = build_panel(load_tags()) df.to_pickle(PANEL_FILE) return df def subsample_sp(df, n): sp = df.loc[df["group"] == "sp", "sheet"].astype(str).unique() keep = set(np.random.default_rng(SEED).choice(sp, min(n, len(sp)), replace=False)) out = df[(df["group"] != "sp") | df["sheet"].astype(str).isin(keep)] print(f"single-player subsample: {min(n, len(sp))} of {len(sp)} games") return out # ----------------------------------------------------------------- helpers def stack(df, cutoffs, spec, w): """One row per game-day per cutoff, inside the window. spec="crossers": keep only games seen on both sides of that cutoff in the window.""" parts = [] for c in cutoffs: s = df[(df["S_lag"] - c).abs() <= w].copy() s["cut"] = f"{c:.3f}" s["dist"] = s["S_lag"] - c s["D"] = (s["dist"] >= 0).astype(int) if spec == "crossers": crosses = s.groupby("sheet", observed=True)["D"].nunique() >= 2 s = s[s["sheet"].isin(crosses[crosses].index)] parts.append(s) s = pd.concat(parts, ignore_index=True) if s.empty: return s for c in ("sheet", "month", "rel_year"): s[c] = s[c].astype(str) s["dist_x_D"] = s["dist"] * s["D"] s["gid"] = pd.factorize(s["sheet"])[0] s["gc"] = pd.factorize(s["sheet"] + "_" + s["cut"])[0] # game x cutoff FE return s def boot_p(model, param, reps): """Wild cluster bootstrap p-value. reps=0 skips it.""" if not reps: return np.nan try: r = model.wildboottest(param=param, reps=reps, seed=SEED) return float(r["Pr(>|t|)"]) except Exception as e: print(f" bootstrap failed for {param}: {e}") return np.nan def fit_model(s, regs, ctrl, fes): import pyfixest as pf return pf.feols(f"lnR ~ {' + '.join(regs + ctrl)} | {' + '.join(fes)}", data=s, vcov={"CRV1": "gid"}) def tidy_rows(m, labels, reps, **extra): t = m.tidy() rows = [] for par, label in labels.items(): if par not in t.index: continue est, se = float(t.loc[par, "Estimate"]), float(t.loc[par, "Std. Error"]) rows.append(dict(effect=label, est=est, se=se, ci_low=est - 1.96 * se, ci_high=est + 1.96 * se, p_cluster=float(t.loc[par, "Pr(>|t|)"]), p_boot=boot_p(m, par, reps), pct=100 * (np.exp(est) - 1), obs=int(m._N), **extra)) return pd.DataFrame(rows) # ----------------------------------------------------------------- tests def fit_did(df, group, spec, w, reps=0): """Difference-in-discontinuities: real-cutoff jump minus placebo-cutoff jump.""" sub = df if group == "all" else df[df["group"] == group] s = stack(sub, CUTOFFS + PLACEBOS, spec, w) if s.empty: print(f"[{spec}] {group}: no rows, skipped") return None s["real"] = s["cut"].isin([f"{c:.3f}" for c in CUTOFFS]).astype(int) side = s.groupby(["real", "D"])["sheet"].nunique() print(f"[{spec}] {group}: games per (real, D): {side.to_dict()}") if side.min() < MIN_GAMES or len(side) < 4: print(f"[{spec}] {group}: too few games per side, skipped") return None s["D_x_real"] = s["D"] * s["real"] s["dist_x_real"] = s["dist"] * s["real"] s["dist_x_D_x_real"] = s["dist_x_D"] * s["real"] regs = ["D", "D_x_real", "dist", "dist_x_D", "dist_x_real", "dist_x_D_x_real"] if group == "all": for g in ("MP", "BOTH"): s[f"dist_x_{g}"] = s["dist"] * s[g] s[f"dist_x_D_x_{g}"] = s["dist_x_D"] * s[g] regs += [f"dist_x_{g}", f"dist_x_D_x_{g}"] if spec == "rd": ctrl = [c for c in ["ln_age", "ln_N", "ln_price", "no_price"] if s[c].nunique() > 1] if group == "all": ctrl += [c for c in ["MP", "BOTH"] if s[c].nunique() > 1] fes = [TIME_FE, "rel_year", "cut"] else: ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1] fes = ["gc", TIME_FE] m = fit_model(s, regs, ctrl, fes) out = tidy_rows(m, {"D": "placebo jump (D)", "D_x_real": "real minus placebo (D_x_real)"}, reps, spec=spec, group=group) del s, m gc.collect() return out def fit_did_mp(df, spec, w, reps=0): """Triple difference: (mp real-minus-placebo) minus (sp real-minus-placebo).""" sub = df[df["group"].isin(["sp", "mp"])] s = stack(sub, CUTOFFS + PLACEBOS, spec, w) if s.empty: print(f"[{spec}] triple: no rows, skipped") return None s["real"] = s["cut"].isin([f"{c:.3f}" for c in CUTOFFS]).astype(int) cells = s.groupby(["MP", "real", "D"])["sheet"].nunique() print(f"[{spec}] games per cell (MP, real, D):\n{cells.to_string()}") if len(cells) < 8 or cells.min() < MIN_GAMES: print(f"[{spec}] some cell has fewer than {MIN_GAMES} games, skipped") return None s["D_x_real"] = s["D"] * s["real"] s["D_x_MP"] = s["D"] * s["MP"] s["D_x_real_x_MP"] = s["D"] * s["real"] * s["MP"] regs = ["D", "D_x_real", "D_x_MP", "D_x_real_x_MP"] for v in ("dist", "dist_x_D"): s[f"{v}_x_real"] = s[v] * s["real"] s[f"{v}_x_MP"] = s[v] * s["MP"] s[f"{v}_x_real_x_MP"] = s[v] * s["real"] * s["MP"] regs += [v, f"{v}_x_real", f"{v}_x_MP", f"{v}_x_real_x_MP"] if spec == "rd": s["real_x_MP"] = s["real"] * s["MP"] ctrl = [c for c in ["ln_age", "ln_N", "ln_price", "no_price", "MP", "real_x_MP"] if s[c].nunique() > 1] fes = [TIME_FE, "rel_year", "cut"] else: ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1] fes = ["gc", TIME_FE] m = fit_model(s, regs, ctrl, fes) labels = {"D": "placebo jump, sp", "D_x_real": "real minus placebo, sp", "D_x_MP": "placebo jump, mp minus sp", "D_x_real_x_MP": "TRIPLE: (mp real-placebo) minus (sp real-placebo)"} out = tidy_rows(m, labels, reps, spec=spec) del s, m gc.collect() return out def save(row, path, w, n_sp): row = row.assign(w=w, n_sp=n_sp if n_sp else "all") row.to_csv(path, mode="a", header=not os.path.exists(path), index=False) # ----------------------------------------------------------------- run if __name__ == "__main__": warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest") warnings.filterwarnings("ignore", category=RuntimeWarning) pd.set_option("display.float_format", lambda x: f"{x:.4f}") pd.set_option("display.width", 220) ap = argparse.ArgumentParser() ap.add_argument("test", choices=["did", "triple"]) ap.add_argument("--spec", nargs="+", default=["rd", "crossers"], choices=["rd", "crossers"]) ap.add_argument("--group", nargs="+", default=["mp", "both", "sp"], choices=["sp", "mp", "both", "all"]) ap.add_argument("--w", type=float, default=0.02, help=f"window half-width, max {PANEL_W}") ap.add_argument("--reps", type=int, default=0, help="bootstrap reps (0 = off)") ap.add_argument("--n-sp", type=int, default=None, help="subsample single-player games") ap.add_argument("--rebuild", action="store_true") a = ap.parse_args() if a.w > PANEL_W: raise SystemExit(f"--w must be <= {PANEL_W}; raise PANEL_W and use --rebuild") df = get_panel(a.rebuild) if a.n_sp: df = subsample_sp(df, a.n_sp) print(f"W = {a.w}, bootstrap reps = {a.reps}") for spec in a.spec: if a.test == "did": for g in a.group: print(f"\nrunning did {spec} / {g} ...", flush=True) r = fit_did(df, g, spec, a.w, a.reps) if r is not None: print(r.to_string(index=False), flush=True) save(r, OUT_DID, a.w, a.n_sp) else: print(f"\nrunning triple {spec} ...", flush=True) r = fit_did_mp(df, spec, a.w, a.reps) if r is not None: print(r.to_string(index=False), flush=True) save(r, OUT_TRIPLE, a.w, a.n_sp)