Files
Valve_research/game_test.py
T
2026-11-23 16:39:35 +01:00

223 lines
9.7 KiB
Python

"""
Estimate the label-cutoff effect on daily new reviews, separately for single-player and
multiplayer games, at each Steam review-label cutoff.
Model, per cutoff c, on game-days with |S_{t-1} - c| <= W:
ln(1 + R_it) = a_i + d_t + gamma*(S - c) + gamma_M*(S - c)*MP_i
+ ell*D + lambda*(D*MP_i) + beta*ln(1 + Age_it) + e_it
D = 1 if S_{t-1} >= c. Game and time fixed effects, SE clustered by game.
ell = label effect for single-player games
ell + lambda = label effect for multiplayer games
lambda = difference (H2: lambda < 0)
Inputs:
data/*.csv one CSV per game with columns: date, positive, negative
game_tags.csv columns: sheet, group (sheet = CSV file name without .csv;
group = "sp", "mp" or "both"; "both" games are excluded)
Install: pip install pandas numpy statsmodels pyfixest
(pyfixest is optional; without it a slower statsmodels fallback is used)
"""
import glob
import os
import numpy as np
import pandas as pd
# ----------------------------------------------------------------- settings
DATA_GLOB = "data/*.csv"
TAGS_FILE = "game_tags.csv"
CUTOFFS = [0.20, 0.40, 0.70, 0.80, 0.95]
W = 0.02 # window half-width in score (0.02 = 2 pp, as in the paper)
MIN_REVIEWS = 500 # only the 500+ row of Table 1
TRIM_Q = 0.99 # drop bursts: daily R above this per-game quantile (None = off)
MIN_CROSSING_GAMES = 10 # required PER GROUP; cutoffs below this are skipped
PLACEBOS = [0.75, 0.85, 0.90] # fake cutoffs: no label changes here
TIME_FE = "month" # "month" or "week"; "date" is too sparse inside narrow windows
# ----------------------------------------------------------------- data
def load(pattern):
frames = []
for path in glob.glob(pattern):
d = pd.read_csv(path, parse_dates=["date"])[["date", "positive", "negative"]].copy()
d["sheet"] = os.path.splitext(os.path.basename(path))[0]
frames.append(d)
if not frames:
raise SystemExit(f"No files found for {pattern}")
df = pd.concat(frames, ignore_index=True)
print(len(frames), "files loaded,", df["sheet"].nunique(), "games")
return df
def add_groups(df):
"""Attach MP_i from the tag file; drop games tagged both or missing from the file."""
tags = pd.read_csv(TAGS_FILE)[["sheet", "group"]].drop_duplicates("sheet")
tags["group"] = tags["group"].astype(str).str.strip().str.lower()
df = df.merge(tags, on="sheet", how="left")
print("Games per group:", df.groupby("group")["sheet"].nunique().to_dict())
missing = df.loc[df["group"].isna(), "sheet"].nunique()
if missing:
print(f"WARNING: {missing} games have no entry in {TAGS_FILE} and are dropped")
df = df[df["group"].isin(["sp", "mp"])].copy()
df["MP"] = (df["group"] == "mp").astype(int)
return df
def build(df):
cols = ["positive", "negative"]
df[cols] = df[cols].apply(pd.to_numeric, errors="coerce").fillna(0).abs().astype(int)
df = df.sort_values(["sheet", "date"]).reset_index(drop=True)
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"])
# NOTE: age is measured from the first row in each CSV, so the CSV must start at release
df["age"] = (df["date"] - g["date"].transform("min")).dt.days
df["ln_age"] = np.log1p(df["age"]) # day 0 -> 0
df["month"] = df["date"].dt.to_period("M").astype(str)
df["week"] = df["date"].dt.to_period("W").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"])
# ----------------------------------------------------------------- estimation
def fit(sample, regs):
"""Return ({reg: (est, se, p)}, nobs) for the given regressors, or None on failure.
Regressors dropped as collinear are missing from the dict."""
try:
import pyfixest as pf
except ImportError:
pf = None
rhs = " + ".join(regs)
if pf is not None:
try:
m = pf.feols(f"lnR ~ {rhs} | sheet + {TIME_FE}",
data=sample, vcov={"CRV1": "sheet"})
t = m.tidy()
out = {r: (float(t.loc[r, "Estimate"]), float(t.loc[r, "Std. Error"]),
float(t.loc[r, "Pr(>|t|)"])) for r in regs if r in t.index}
return out, int(m._N)
except (ZeroDivisionError, ValueError, np.linalg.LinAlgError):
return None
import statsmodels.formula.api as smf
groups = pd.factorize(sample["sheet"])[0]
try:
m = smf.ols(f"lnR ~ {rhs} + C(sheet) + C({TIME_FE})", data=sample).fit(
cov_type="cluster", cov_kwds={"groups": groups})
except (ValueError, np.linalg.LinAlgError):
return None
out = {r: (float(m.params[r]), float(m.bse[r]), float(m.pvalues[r])) for r in regs}
return out, int(m.nobs)
def solve(df, cutoffs):
base = df[df["N_lag"] >= MIN_REVIEWS]
rows = []
for c in cutoffs:
s = base.copy()
s["dist"] = s["S_lag"] - c
s["D"] = (s["dist"] >= 0).astype(int)
s = s[s["dist"].abs() <= W].copy()
# keep only games observed on both sides of the cutoff inside the window
crosses = s.groupby("sheet")["D"].nunique() >= 2
s = s[s["sheet"].isin(crosses[crosses].index)].copy()
per_game = s.groupby("sheet")["MP"].first()
n_mp, n_sp = int(per_game.sum()), int((1 - per_game).sum())
if min(n_sp, n_mp) < MIN_CROSSING_GAMES:
print(f"c={c:.3f}: crossing games sp={n_sp}, mp={n_mp} (need {MIN_CROSSING_GAMES} each), skipped")
continue
# interaction parametrisation: D = ell (single-player), D_x_MP = lambda
s["D_x_MP"] = s["D"] * s["MP"]
s["dist_x_MP"] = s["dist"] * s["MP"]
a = fit(s, ["D", "D_x_MP", "dist", "dist_x_MP", "ln_age"])
# split parametrisation: separate effect per group (gives SE of ell + lambda)
s["Dsp"], s["Dmp"] = s["D"] * (1 - s["MP"]), s["D"] * s["MP"]
s["dsp"], s["dmp"] = s["dist"] * (1 - s["MP"]), s["dist"] * s["MP"]
b = fit(s, ["Dsp", "Dmp", "dsp", "dmp", "ln_age"])
if a is None or b is None or not {"D", "D_x_MP"} <= a[0].keys() or not {"Dsp", "Dmp"} <= b[0].keys():
print(f"c={c:.3f}: model could not be estimated (collinear or too few rows), skipped")
continue
(ell, se_e, p_e), (lam, se_l, p_l) = a[0]["D"], a[0]["D_x_MP"]
(ell_m, se_m, p_m) = b[0]["Dmp"]
rows.append(dict(cutoff=c,
ell=ell, se_ell=se_e, p_ell=p_e,
lam=lam, se_lam=se_l, p_lam=p_l,
ell_mp=ell_m, se_mp=se_m, p_mp=p_m,
pct_sp=100 * (np.exp(ell) - 1), pct_mp=100 * (np.exp(ell_m) - 1),
games_sp=n_sp, games_mp=n_mp, obs=a[1]))
return pd.DataFrame(rows)
def pool(res, est, se):
"""Inverse-variance pooling across cutoffs. Assumes independent estimates, which is
only approximately true: the same game can contribute to several cutoffs."""
w = 1 / res[se] ** 2
return (w * res[est]).sum() / w.sum(), np.sqrt(1 / w.sum())
# ----------------------------------------------------------------- run
if __name__ == "__main__":
df = build(add_groups(load(DATA_GLOB)))
print(df["sheet"].nunique(), "games with lagged score,",
df[df["N_lag"] >= MIN_REVIEWS]["sheet"].nunique(), f"with {MIN_REVIEWS}+ reviews")
# placebo windows must not overlap a real window, or they are not placebos
for pc in PLACEBOS:
if min(abs(pc - c) for c in CUTOFFS) <= 2 * W:
print(f"WARNING: placebo {pc:.3f} is within 2*W of a real cutoff")
res = solve(df, CUTOFFS)
if res.empty:
raise SystemExit("No cutoff had enough crossing games in both groups. "
"Widen W, add games, or lower MIN_CROSSING_GAMES.")
plc = solve(df, PLACEBOS)
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
pd.set_option("display.width", 200)
print("\nREAL cutoffs (log points; pct_* = % change in daily reviews):")
print(res.to_string(index=False))
print("\nPooled across real cutoffs (inverse-variance):")
for label, e, s_ in [("ell (single-player)", "ell", "se_ell"),
("lambda (MP - SP)", "lam", "se_lam"),
("ell + lambda (multiplayer)", "ell_mp", "se_mp")]:
est, se = pool(res, e, s_)
print(f" {label:28s} {est:8.4f} (SE {se:.4f}, z = {est / se:.2f})")
if plc.empty:
print("\nNo placebo cutoff had enough crossing games.")
res.assign(kind="real").to_csv("ell_results.csv", index=False)
else:
print("\nPLACEBO cutoffs (no label changes here):")
print(plc.to_string(index=False))
for label, e, p in [("ell", "ell", "p_ell"), ("lambda", "lam", "p_lam")]:
print(f"Placebo {label}: mean {plc[e].mean():.4f}, mean |.| {plc[e].abs().mean():.4f}, "
f"{int((plc[p] < 0.05).sum())} of {len(plc)} significant at 5%; "
f"real cutoffs with |.| above largest placebo |.|: "
f"{int((res[e].abs() > plc[e].abs().max()).sum())} of {len(res)}")
pd.concat([res.assign(kind="real"), plc.assign(kind="placebo")]).to_csv(
"ell_results.csv", index=False)
print("Saved ell_results.csv")