""" Label-cutoff RD: difference-in-discontinuities ("did") and triple difference ("triple"). Memory-lean: 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. Noise reduction options (all chosen on the command line, none on by default): --fe {month,week,day} time fixed effect. "day" removes anything that hits all games on the same date (seasonal sales, weekends, holidays). --spike K drop game-days where R > K * (rolling 29-day median of R + 5), i.e. a game-specific burst such as its own discount. 0 = off. --vol7 MODE recent review volume, SENSITIVITY CHECK ONLY (bad-control risk: after a label change the lagged volume already contains the effect, which biases the estimate toward zero). off baseline, no control, all rows sample drop rows without 14 days of history, no control control sample + control ln(1 + mean reviews, days t-7..t-1) control_lagged sample + control ln(1 + mean reviews, days t-14..t-8) Compare "control" and "control_lagged" with "sample", not with "off": "sample" uses exactly the same rows, so the difference is the control. 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 sp --w 0.02 --fe day --spike 3 python game_test.py did --spec crossers --group mp both sp --w 0.02 --vol7 sample python game_test.py did --spec crossers --group mp both sp --w 0.02 --vol7 control python game_test.py triple --spec crossers --w 0.02 --vol7 control_lagged 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 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 VOL_COLS = ["ln_vol7", "ln_vol7_old"] KEEP = ["sheet", "group", "MP", "BOTH", "lnR", "S_lag", "N_lag", "ln_N", "ln_age", "ln_price", "no_price", "month", "rel_year", "date", "spike_ratio"] + VOL_COLS # ----------------------------------------------------------------- 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) # burst ratio: today's reviews relative to the game's own recent median (stored, filtered later) med = R.rolling(29, center=True, min_periods=7).median().fillna(0) # recent volume, computed on the full daily series before any trimming: # vol7 mean reviews over days t-7 ... t-1 # vol7_old mean reviews over days t-14 ... t-8 (predates most of a post-crossing effect) vol7 = R.shift(1).rolling(7, min_periods=7).mean() vol7_old = R.shift(8).rolling(7, min_periods=7).mean() 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) out["date"] = d["date"] out["spike_ratio"] = (R / (med + 5)).astype("float32") out["ln_vol7"] = np.log1p(vol7).astype("float32") out["ln_vol7_old"] = np.log1p(vol7_old).astype("float32") 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) if {"date", "spike_ratio"} | set(VOL_COLS) <= set(df.columns): print(f"loaded cached panel {PANEL_FILE}: {len(df):,} rows, " f"{df['sheet'].nunique()} games") return df print("cached panel is from an older version (missing columns), rebuilding") df = build_panel(load_tags()) df.to_pickle(PANEL_FILE) return df def drop_spikes(df, k): if not k: return df before = len(df) df = df[df["spike_ratio"] <= k] print(f"spike filter (ratio <= {k}): dropped {before - len(df):,} of {before:,} game-days") return df def match_volume_sample(df, mode): """sample / control / control_lagged all use the same rows: those with both volume measures.""" if mode == "off": return df before = len(df) df = df.dropna(subset=VOL_COLS) print(f"vol7 sample: dropped {before - len(df):,} of {before:,} game-days without 14 days of history") 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 def add_time_fe(df, fe, keep_cols=()): """Create the time fixed-effect column "tfe" (month, week or day) and drop unused columns.""" df = df.copy() if fe == "month": df["tfe"] = df["month"].astype(str) elif fe == "week": df["tfe"] = df["date"].dt.to_period("W").astype(str) else: df["tfe"] = df["date"].dt.strftime("%Y%m%d") df["tfe"] = df["tfe"].astype("category") print(f"time fixed effect: {fe} ({df['tfe'].nunique()} levels)") drop = ["date", "month", "spike_ratio"] + [c for c in VOL_COLS if c not in keep_cols] return df.drop(columns=drop) # ----------------------------------------------------------------- helpers def pick(s, cols): """Keep only columns that exist and vary.""" return [c for c in cols if c in s.columns and s[c].nunique() > 1] 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", "tfe", "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, vctrl=()): """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 = pick(s, ["ln_age", "ln_N", "ln_price", "no_price"] + list(vctrl)) if group == "all": ctrl += pick(s, ["MP", "BOTH"]) fes = ["tfe", "rel_year", "cut"] else: ctrl = pick(s, ["ln_age", "ln_N"] + list(vctrl)) fes = ["gc", "tfe"] 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, vctrl=()): """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 = pick(s, ["ln_age", "ln_N", "ln_price", "no_price", "MP", "real_x_MP"] + list(vctrl)) fes = ["tfe", "rel_year", "cut"] else: ctrl = pick(s, ["ln_age", "ln_N"] + list(vctrl)) fes = ["gc", "tfe"] 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, **settings): """Append rows with the settings used, so results from different runs stay distinguishable.""" row = row.assign(**settings) 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("--fe", choices=["month", "week", "day"], default="month", help="time fixed effect (default month, as in earlier runs)") ap.add_argument("--spike", type=float, default=0, help="drop game-days with burst ratio above this (0 = off, try 3)") ap.add_argument("--vol7", choices=["off", "sample", "control", "control_lagged"], default="off", help="recent-volume sensitivity check (see top of file)") 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") vctrl = {"control": ["ln_vol7"], "control_lagged": ["ln_vol7_old"]}.get(a.vol7, []) df = get_panel(a.rebuild) df = drop_spikes(df, a.spike) df = match_volume_sample(df, a.vol7) if a.n_sp: df = subsample_sp(df, a.n_sp) df = add_time_fe(df, a.fe, keep_cols=vctrl) print(f"W = {a.w}, fe = {a.fe}, spike = {a.spike or 'off'}, vol7 = {a.vol7}, " f"bootstrap reps = {a.reps}") settings = dict(w=a.w, fe=a.fe, spike=a.spike or "off", vol7=a.vol7, n_sp=a.n_sp or "all") 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, vctrl) if r is not None: print(r.to_string(index=False), flush=True) save(r, OUT_DID, **settings) else: print(f"\nrunning triple {spec} ...", flush=True) r = fit_did_mp(df, spec, a.w, a.reps, vctrl) if r is not None: print(r.to_string(index=False), flush=True) save(r, OUT_TRIPLE, **settings)