Files
Valve_research/game_test.py
T
2026-11-28 11:22:27 +01:00

389 lines
15 KiB
Python

"""
Label-cutoff RD, run separately for single-player (sp), multiplayer-only (mp),
both, and all games pooled. Self-contained.
Inputs:
game_tags.csv columns: sheet, genres, group ("sp"/"mp"/"both"), price
data/<sheet>.csv columns: date, positive, negative
Install: pip install pandas numpy pyfixest
"""
import os
import numpy as np
import pandas as pd
# ----------------------------------------------------------------- settings
DATA_DIR = "data"
TAGS_FILE = "game_tags.csv"
# game selection
GAME_GENRES = {
'Action', 'Indie', 'Simulation', 'Strategy', 'RPG', 'Early Access',
'Casual', 'Adventure', 'Free To Play', 'Massively Multiplayer',
'Racing', 'Sports', 'Episodic',
}
MIN_SPAN_DAYS = 365 # first to last date
MAX_SPAN_DAYS = 10 * 365
MIN_TOTAL_REVIEWS = 2000 # all reviews in the file
# RD settings
W = 0.01 # window half-width in score; also try 0.01 and 0.03
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 group AND per side of the cutoff
TIME_FE = "month"
CUTOFFS = [0.70, 0.80, 0.95]
PLACEBOS = [0.60, 0.75, 0.85, 0.90]
BOOT_REPS = 999
PLACEBO_REPS = 499
SEED = 42
# ----------------------------------------------------------------- step 1: choose games, load 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") # "NA"/blank -> NaN
return tags
def select_and_load(tags):
"""Genre filter, then read each game file once, apply span/review filters,
fill missing days with zero reviews. Returns the daily panel for kept games."""
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 = [], 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())
d["sheet"] = sheet
frames.append(d)
print(f"dropped: no file/empty {n_nofile}, span {n_span}, reviews {n_rev}; kept {len(frames)}")
if not frames:
raise SystemExit("No games left after filtering")
return pd.concat(frames, ignore_index=True)
def add_groups(df, tags):
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))
print("games per group:", df.groupby("group")["sheet"].nunique().to_dict())
return df
def build(df):
df = df.sort_values(["sheet", "date"]).reset_index(drop=True)
df[["positive", "negative"]] = df[["positive", "negative"]].astype(int)
df["R"] = df["positive"] + df["negative"]
g = df.groupby("sheet")
df["cum_pos"] = g["positive"].cumsum()
df["cum_tot"] = g["R"].cumsum()
df["score"] = df["cum_pos"] / df["cum_tot"].replace(0, np.nan)
g = df.groupby("sheet")
df["S_lag"] = g["score"].shift(1)
df["N_lag"] = g["cum_tot"].shift(1)
df["lnR"] = np.log1p(df["R"])
df["ln_N"] = np.log(df["N_lag"].clip(lower=1))
first = g["date"].transform("min") # CSV must start at release
df["age"] = (df["date"] - first).dt.days
df["ln_age"] = np.log1p(df["age"])
df["rel_year"] = first.dt.year.astype(str)
df["month"] = df["date"].dt.to_period("M").astype(str)
if TRIM_Q is not None:
q = df.groupby("sheet")["R"].transform(lambda x: x.quantile(TRIM_Q))
before = len(df)
df = df[df["R"] <= q]
print(f"burst filter dropped {before - len(df)} game-days")
return df.dropna(subset=["S_lag", "N_lag"])
# ----------------------------------------------------------------- RD helpers
def stack(df, cutoffs, spec="rd"):
"""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."""
base = df[df["N_lag"] >= MIN_REVIEWS]
parts = []
for c in cutoffs:
s = base[(base["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")["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
s["dist_x_D"] = s["dist"] * s["D"]
s["gid"] = pd.factorize(s["sheet"])[0] # cluster id
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 for one coefficient."""
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_group(df, cutoffs, reps, group, spec="rd"):
"""Label effect (jump D) for one subset: 'sp', 'mp', 'both' or 'all'."""
sub = df if group == "all" else df[df["group"] == group]
s = stack(sub, cutoffs, spec)
if s.empty:
print(f"[{spec}] {group} {cutoffs}: no rows, skipped")
return None
side = s.groupby("D")["sheet"].nunique()
n0, n1 = int(side.get(0, 0)), int(side.get(1, 0))
if min(n0, n1) < MIN_GAMES:
print(f"[{spec}] {group} {cutoffs}: games below/above = {n0}/{n1} "
f"(need {MIN_GAMES}), skipped")
return None
regs = ["D", "dist", "dist_x_D"]
if group == "all":
# separate slopes per group so the pooled jump is not driven by slope differences
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"] if s["cut"].nunique() > 1 else [])
else: # crossers: game x cutoff FE absorbs price, release year, group level
ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1]
fes = ["gc", TIME_FE]
import pyfixest as pf
m = pf.feols(f"lnR ~ {' + '.join(regs + ctrl)} | {' + '.join(fes)}",
data=s, vcov={"CRV1": "gid"})
t = m.tidy()
if "D" not in t.index:
print(f"[{spec}] {group}: D dropped as collinear, skipped")
return None
est = float(t.loc["D", "Estimate"])
return pd.DataFrame([dict(
spec=spec, group=group, cutoffs=",".join(f"{c:.2f}" for c in cutoffs),
est=est, se=float(t.loc["D", "Std. Error"]),
p_cluster=float(t.loc["D", "Pr(>|t|)"]),
p_boot=boot_p(m, "D", reps),
pct=100 * (np.exp(est) - 1),
games_below=n0, games_above=n1, obs=int(m._N))])
def test_all_groups(df, cutoffs, reps, spec="rd", per_cutoff=False):
sets = [cutoffs] + ([[c] for c in cutoffs] if per_cutoff else [])
out = [fit_group(df, cs, reps, g, spec)
for cs in sets for g in ("sp", "mp", "both", "all")]
out = [o for o in out if o is not None]
return pd.concat(out, ignore_index=True) if out else None
def fit_did(df, group, spec="rd", reps=BOOT_REPS):
"""Difference-in-discontinuities: real-cutoff jump minus average placebo jump."""
sub = df if group == "all" else df[df["group"] == group]
s = stack(sub, CUTOFFS + PLACEBOS, spec) # real and placebo cutoffs together
if s.empty:
return None
real_cuts = [f"{c:.3f}" for c in CUTOFFS]
s["real"] = s["cut"].isin(real_cuts).astype(int)
# check there are enough games on each side for both kinds of cutoff
side = s.groupby(["real", "D"])["sheet"].nunique()
if side.min() < MIN_GAMES or len(side) < 4:
print(f"[{spec}] {group}: too few games per side {side.to_dict()}, 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": # group-specific slopes, as before
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"] # "cut" absorbs the real dummy
else:
ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1]
fes = ["gc", TIME_FE]
import pyfixest as pf
m = pf.feols(f"lnR ~ {' + '.join(regs + ctrl)} | {' + '.join(fes)}",
data=s, vcov={"CRV1": "gid"})
t = m.tidy()
rows = []
for label, par in [("placebo jump (D)", "D"),
("real minus placebo (D_x_real)", "D_x_real")]:
est = float(t.loc[par, "Estimate"])
rows.append(dict(spec=spec, group=group, effect=label, est=est,
se=float(t.loc[par, "Std. Error"]),
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)))
return pd.DataFrame(rows)
def fit_did_mp(df, spec="rd", reps=BOOT_REPS):
"""Triple difference: (mp real-minus-placebo) minus (sp real-minus-placebo)."""
sub = df[df["group"].isin(["sp", "mp"])] # "both" excluded
s = stack(sub, CUTOFFS + PLACEBOS, spec)
if s.empty:
return None
real_cuts = [f"{c:.3f}" for c in CUTOFFS]
s["real"] = s["cut"].isin(real_cuts).astype(int)
# games per cell: MP x real x side of cutoff
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
# jump terms
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"]
# slopes: fully interacted so slope differences don't leak into the jump
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"] # "cut" absorbs the real dummy
else: # gc absorbs MP and real x MP
ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1]
fes = ["gc", TIME_FE]
import pyfixest as pf
m = pf.feols(f"lnR ~ {' + '.join(regs + ctrl)} | {' + '.join(fes)}",
data=s, vcov={"CRV1": "gid"})
t = m.tidy()
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)"}
rows = []
for par, label in labels.items():
if par not in t.index:
continue
est = float(t.loc[par, "Estimate"])
se = float(t.loc[par, "Std. Error"])
rows.append(dict(spec=spec, 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),
obs=int(m._N)))
return pd.DataFrame(rows)
# ----------------------------------------------------------------- run
if __name__ == "__main__":
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest")
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
pd.set_option("display.width", 220)
tags = load_tags()
df = build(add_groups(select_and_load(tags), tags))
print(df["sheet"].nunique(), "games with lagged score,",
df[df["N_lag"] >= MIN_REVIEWS]["sheet"].nunique(), f"with {MIN_REVIEWS}+ reviews")
tri = [fit_did_mp(df, spec) for spec in ["rd", "crossers"]]
tri = pd.concat([x for x in tri if x is not None], ignore_index=True)
print(tri.to_string(index=False))
tri.to_csv("ell_triple.csv", index=False)
'''
did = [fit_did(df, g, spec) for spec in ["rd", "crossers"]
for g in ("sp", "mp", "both", "all")]
did = pd.concat([d for d in did if d is not None], ignore_index=True)
print(did.to_string(index=False))
did.to_csv("ell_did.csv", index=False)
res = []
for spec in ["rd", "crossers"]:
print(f"\n=== {spec.upper()} by group: real cutoffs (stacked, plus each cutoff) ===")
real = test_all_groups(df, CUTOFFS, BOOT_REPS, spec, per_cutoff=True)
if real is not None:
print(real.to_string(index=False))
res.append(real.assign(kind="real"))
print(f"\n=== {spec.upper()} by group: placebos ===")
plc = test_all_groups(df, PLACEBOS, PLACEBO_REPS, spec, per_cutoff=True)
if plc is not None:
print(plc.to_string(index=False))
res.append(plc.assign(kind="placebo"))
if res:
pd.concat(res).to_csv("ell_by_group.csv", index=False)
print("Saved ell_by_group.csv")
'''