428 lines
18 KiB
Python
428 lines
18 KiB
Python
"""
|
|
Estimate the label-cutoff effect on daily new reviews, separately for single-player and
|
|
multiplayer games, at each Steam review-label cutoff.
|
|
|
|
Main specification (regression discontinuity), per cutoff c, on game-days with |S_{t-1} - c| <= W:
|
|
ln(1 + R_it) = d_month + d_relyear
|
|
+ gamma*(S-c) + rho*(S-c)*D
|
|
+ gamma_M*(S-c)*MP + rho_M*(S-c)*D*MP
|
|
+ ell*D + lambda*(D*MP)
|
|
+ b1*ln(1 + Age) + b2*ln(N_{t-1}) + e_it
|
|
D = 1 if S_{t-1} >= c. SE clustered by game.
|
|
|
|
Games do NOT need to cross the cutoff: the jump is identified by comparing games just
|
|
below to games just above, so there is no game fixed effect.
|
|
|
|
ell = label effect for single-player games
|
|
ell + lambda = label effect for multiplayer games
|
|
lambda = difference (H2: lambda < 0)
|
|
|
|
Robustness specification ("crossers"): the old design, game fixed effects on games that
|
|
cross the cutoff inside the window, now with separate slopes on each side.
|
|
|
|
Inputs:
|
|
data/*.csv one CSV per game with columns: date, positive, negative
|
|
game_tags.csv columns: sheet, group ("sp", "mp" or "both"; "both" is excluded)
|
|
|
|
Install: pip install pandas numpy statsmodels pyfixest
|
|
"""
|
|
import glob
|
|
import os
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
# ----------------------------------------------------------------- settings
|
|
DATA_GLOB = "data/*.csv"
|
|
TAGS_FILE = "game_tags.csv"
|
|
W = 0.02 # window half-width in score; also try 0.01 and 0.03
|
|
MIN_REVIEWS = 500
|
|
TRIM_Q = 0.99
|
|
MIN_GAMES = 10 # raised: tiny cells break the bootstrap
|
|
PLACEBOS = [0.60, 0.75, 0.85, 0.90] # 0.65 dropped: too few games
|
|
# CHANGED: required per group AND per side of the cutoff
|
|
TIME_FE = "month"
|
|
RD_FE = [TIME_FE, "rel_year"] # NEW: fixed effects for the main (no-game-FE) spec
|
|
CROSSER_FE = ["sheet", TIME_FE] # NEW: fixed effects for the robustness spec
|
|
|
|
CUTOFFS = [0.70, 0.80, 0.95] # 0.20 / 0.40 dropped: no usable games
|
|
BOOT_REPS = 999 # wild bootstrap draws, real cutoffs
|
|
PLACEBO_REPS = 499 # fewer for placebos to save time
|
|
SEED = 123
|
|
STACK_FE = [TIME_FE, "rel_year", "cut"] # "cut" = one fixed effect per cutoff
|
|
|
|
|
|
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 inside 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["D_x_MP"] = s["D"] * s["MP"]
|
|
s["dist_x_MP"] = s["dist"] * s["MP"]
|
|
s["dist_x_D_x_MP"] = s["dist_x_D"] * s["MP"]
|
|
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"]
|
|
s["dsp_D"], s["dmp_D"] = s["dsp"] * s["D"], s["dmp"] * s["D"]
|
|
s["gid"] = pd.factorize(s["sheet"])[0] # cluster id (integer for numba)
|
|
s["gc"] = pd.factorize(s["sheet"] + "_" + s["cut"])[0] # game x cutoff fixed effect
|
|
return s
|
|
|
|
|
|
|
|
|
|
def boot_p(model, param, reps):
|
|
"""Wild cluster bootstrap p-value for one coefficient (clusters = games, from vcov CRV1)."""
|
|
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 stacked_fit(df, cutoffs, reps, spec="rd"):
|
|
s = stack(df, cutoffs, spec)
|
|
if s.empty:
|
|
print(f"[{spec}] {cutoffs}: no rows in window, skipped")
|
|
return None
|
|
|
|
side = s.groupby(["MP", "D"])["sheet"].nunique()
|
|
n = {(mp, d): int(side.get((mp, d), 0)) for mp in (0, 1) for d in (0, 1)}
|
|
if min(n.values()) < MIN_GAMES:
|
|
print(f"[{spec}] {cutoffs}: games per side sp={n[0,0]}/{n[0,1]}, mp={n[1,0]}/{n[1,1]} "
|
|
f"(need {MIN_GAMES} each), skipped")
|
|
return None
|
|
|
|
if spec == "rd":
|
|
ctrl = [c for c in ["ln_age", "ln_N", "ln_price", "no_price"] if s[c].nunique() > 1]
|
|
fes = " + ".join([TIME_FE, "rel_year", "cut"])
|
|
else: # price, release year and MP level are absorbed by the game x cutoff effect
|
|
ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1]
|
|
fes = " + ".join(["gc", TIME_FE])
|
|
cl = {"CRV1": "gid"}
|
|
|
|
import pyfixest as pf
|
|
a_regs = ["D", "D_x_MP", "dist", "dist_x_D", "dist_x_MP", "dist_x_D_x_MP"] + ctrl
|
|
b_regs = ["Dsp", "Dmp", "dsp", "dsp_D", "dmp", "dmp_D"] + ctrl
|
|
ma = pf.feols(f"lnR ~ {' + '.join(a_regs)} | {fes}", data=s, vcov=cl)
|
|
mb = pf.feols(f"lnR ~ {' + '.join(b_regs)} | {fes}", data=s, vcov=cl)
|
|
ta, tb = ma.tidy(), mb.tidy()
|
|
|
|
out = []
|
|
for label, t, m, par in [("ell (single-player)", ta, ma, "D"),
|
|
("lambda (MP - SP)", ta, ma, "D_x_MP"),
|
|
("ell + lambda (multiplayer)", tb, mb, "Dmp")]:
|
|
if par not in t.index:
|
|
print(f"[{spec}] {par} dropped as collinear, skipped")
|
|
continue
|
|
est = float(t.loc[par, "Estimate"])
|
|
out.append(dict(spec=spec, cutoffs=",".join(f"{c:.2f}" for c in cutoffs), 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),
|
|
games_sp=s.loc[s["MP"] == 0, "sheet"].nunique(),
|
|
games_mp=s.loc[s["MP"] == 1, "sheet"].nunique(),
|
|
obs=int(ma._N)))
|
|
return pd.DataFrame(out)
|
|
|
|
|
|
def stacked_fit3(df, cutoffs, reps, spec="crossers"):
|
|
s = stack(df, cutoffs, spec)
|
|
if s.empty:
|
|
return None
|
|
grp = {"sp": (s["MP"] == 0) & (s["BOTH"] == 0), "mp": s["MP"] == 1, "both": s["BOTH"] == 1}
|
|
|
|
side = {g: s[m].groupby("D")["sheet"].nunique() for g, m in grp.items()}
|
|
for g, x in side.items():
|
|
if min(x.get(0, 0), x.get(1, 0)) < MIN_GAMES:
|
|
print(f"[{spec}] group {g}: games below/above = {x.get(0,0)}/{x.get(1,0)} (need {MIN_GAMES}), skipped")
|
|
return None
|
|
|
|
for g, m in grp.items(): # one set of terms per group
|
|
s[f"D_{g}"] = s["D"] * m
|
|
s[f"d_{g}"] = s["dist"] * m
|
|
s[f"dD_{g}"] = s["dist"] * s["D"] * m
|
|
s["D_x_BOTH"] = s["D"] * s["BOTH"]
|
|
s["dist_x_BOTH"] = s["dist"] * s["BOTH"]
|
|
s["dist_x_D_x_BOTH"] = s["dist_x_D"] * s["BOTH"]
|
|
|
|
if spec == "rd":
|
|
ctrl = [c for c in ["ln_age", "ln_N", "ln_price", "no_price"] if s[c].nunique() > 1]
|
|
fes = " + ".join([TIME_FE, "rel_year", "cut"])
|
|
else:
|
|
ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1]
|
|
fes = " + ".join(["gc", TIME_FE])
|
|
|
|
import pyfixest as pf
|
|
cl = {"CRV1": "gid"}
|
|
# levels: separate jump and slopes per group
|
|
b_regs = [f"{p}_{g}" for g in grp for p in ("D", "d", "dD")] + ctrl
|
|
# differences relative to single-player
|
|
a_regs = ["D", "D_x_MP", "D_x_BOTH", "dist", "dist_x_D", "dist_x_MP", "dist_x_D_x_MP",
|
|
"dist_x_BOTH", "dist_x_D_x_BOTH"] + ctrl
|
|
mb = pf.feols(f"lnR ~ {' + '.join(b_regs)} | {fes}", data=s, vcov=cl)
|
|
ma = pf.feols(f"lnR ~ {' + '.join(a_regs)} | {fes}", data=s, vcov=cl)
|
|
tb, ta = mb.tidy(), ma.tidy()
|
|
|
|
|
|
gname = {"ell single-player": "sp", "ell multiplayer-only": "mp", "ell both": "both"}
|
|
|
|
rows = []
|
|
for label, t, m, par in [("ell single-player", tb, mb, "D_sp"),
|
|
("ell multiplayer-only", tb, mb, "D_mp"),
|
|
("ell both", tb, mb, "D_both"),
|
|
("mp-only minus sp", ta, ma, "D_x_MP"),
|
|
("both minus sp", ta, ma, "D_x_BOTH")]:
|
|
if par not in t.index:
|
|
continue
|
|
est = float(t.loc[par, "Estimate"])
|
|
rows.append(dict(spec=spec, cutoffs=",".join(f"{c:.2f}" for c in cutoffs), 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),
|
|
games=s[grp[gname[label]]]["sheet"].nunique() if label in gname else np.nan))
|
|
return pd.DataFrame(rows)
|
|
|
|
|
|
# ----------------------------------------------------------------- data
|
|
def load(pattern):
|
|
frames = []
|
|
for path in glob.glob(pattern):
|
|
d = pd.read_csv(path, parse_dates=["date"])[["date", "positive", "negative"]].copy()
|
|
if d.empty:
|
|
print(f"skipping {path}: no rows")
|
|
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"] = 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):
|
|
tags = pd.read_csv(TAGS_FILE, dtype={"sheet": str})[["sheet", "group", "price"]].drop_duplicates("sheet")
|
|
tags["sheet"] = tags["sheet"].str.strip()
|
|
tags["group"] = tags["group"].astype(str).str.strip().str.lower()
|
|
tags["price"] = pd.to_numeric(tags["price"], errors="coerce") # "NA" / blank -> NaN
|
|
df["sheet"] = df["sheet"].astype(str)
|
|
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", "both"])].copy()
|
|
df["MP"] = (df["group"] == "mp").astype(int)
|
|
df["BOTH"] = (df["group"] == "both").astype(int)
|
|
|
|
# price control: log(1 + price), with a dummy for games that have no listed price
|
|
df["no_price"] = df["price"].isna().astype(int)
|
|
df["ln_price"] = np.log1p(df["price"].fillna(0))
|
|
n_np = df.loc[df["no_price"] == 1, "sheet"].nunique()
|
|
if n_np:
|
|
print(f"NOTE: {n_np} games have no price (kept, with no_price dummy)")
|
|
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"])
|
|
df["ln_N"] = np.log(df["N_lag"].clip(lower=1)) # NEW: game-size control
|
|
# NOTE: age is measured from the first row in each CSV, so the CSV must start at release
|
|
first = g["date"].transform("min")
|
|
df["age"] = (df["date"] - first).dt.days
|
|
df["ln_age"] = np.log1p(df["age"])
|
|
df["rel_year"] = first.dt.year.astype(str) # NEW: release-year fixed effect
|
|
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, fes):
|
|
"""Return ({reg: (est, se, p)}, nobs) or None. `fes` is a list of fixed-effect columns."""
|
|
try:
|
|
import pyfixest as pf
|
|
except ImportError:
|
|
pf = None
|
|
|
|
rhs = " + ".join(regs)
|
|
if pf is not None:
|
|
try:
|
|
m = pf.feols(f"lnR ~ {rhs} | {' + '.join(fes)}",
|
|
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]
|
|
fe_terms = " + ".join(f"C({f})" for f in fes)
|
|
try:
|
|
m = smf.ols(f"lnR ~ {rhs} + {fe_terms}", 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, spec="rd"):
|
|
"""spec = "rd": all games in the window, no game FE (main)
|
|
spec = "crossers": only games on both sides in the window, game FE (robustness)"""
|
|
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()
|
|
|
|
if spec == "crossers":
|
|
crosses = s.groupby("sheet")["D"].nunique() >= 2
|
|
s = s[s["sheet"].isin(crosses[crosses].index)].copy()
|
|
|
|
# CHANGED: count games per group on EACH side of the cutoff inside the window
|
|
side = s.groupby(["MP", "D"])["sheet"].nunique()
|
|
n = {(mp, d): int(side.get((mp, d), 0)) for mp in (0, 1) for d in (0, 1)}
|
|
n_sp, n_mp = min(n[0, 0], n[0, 1]), min(n[1, 0], n[1, 1])
|
|
if min(n_sp, n_mp) < MIN_GAMES:
|
|
print(f"c={c:.3f} [{spec}]: games below/above sp={n[0,0]}/{n[0,1]}, "
|
|
f"mp={n[1,0]}/{n[1,1]} (need {MIN_GAMES} each), skipped")
|
|
continue
|
|
|
|
# NEW: slope allowed to differ on each side of the cutoff
|
|
s["dist_x_D"] = s["dist"] * s["D"]
|
|
s["D_x_MP"] = s["D"] * s["MP"]
|
|
s["dist_x_MP"] = s["dist"] * s["MP"]
|
|
s["dist_x_D_x_MP"] = s["dist_x_D"] * s["MP"]
|
|
ctrl = ["ln_age", "ln_N"]
|
|
if spec == "rd":
|
|
ctrl += ["ln_price", "no_price"]
|
|
fes = RD_FE if spec == "rd" else CROSSER_FE
|
|
|
|
|
|
# interaction parametrisation: D = ell (single-player), D_x_MP = lambda
|
|
a = fit(s, ["D", "D_x_MP", "dist", "dist_x_D", "dist_x_MP", "dist_x_D_x_MP"] + ctrl, fes)
|
|
|
|
# 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"]
|
|
s["dsp_D"], s["dmp_D"] = s["dsp"] * s["D"], s["dmp"] * s["D"]
|
|
b = fit(s, ["Dsp", "Dmp", "dsp", "dsp_D", "dmp", "dmp_D"] + ctrl, fes)
|
|
|
|
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} [{spec}]: model could not be estimated, 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, spec=spec,
|
|
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=s.loc[s["MP"] == 0, "sheet"].nunique(),
|
|
games_mp=s.loc[s["MP"] == 1, "sheet"].nunique(),
|
|
obs=a[1]))
|
|
return pd.DataFrame(rows)
|
|
|
|
|
|
def pool(res, est, se):
|
|
"""Inverse-variance pooling across cutoffs. Approximate: a 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__":
|
|
import warnings
|
|
warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest")
|
|
|
|
df = build(add_groups(load(DATA_GLOB)))
|
|
df2 = df[df["group"] != "both"].copy() # two-group analysis: sp vs mp-only
|
|
print(df["sheet"].nunique(), "games with lagged score,",
|
|
df[df["N_lag"] >= MIN_REVIEWS]["sheet"].nunique(), f"with {MIN_REVIEWS}+ reviews")
|
|
|
|
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
|
|
pd.set_option("display.width", 220)
|
|
|
|
results = []
|
|
|
|
# ---- two groups (sp vs mp-only), "both" excluded
|
|
for spec in ["rd", "crossers"]:
|
|
print(f"\n=== {spec.upper()} 2-group: stacked real cutoffs ===")
|
|
real = stacked_fit(df2, CUTOFFS, BOOT_REPS, spec)
|
|
if real is None:
|
|
continue
|
|
print(real.to_string(index=False))
|
|
results.append(real.assign(kind="real", groups="2"))
|
|
|
|
print(f"\n=== {spec.upper()} 2-group: placebos ===")
|
|
plc = [stacked_fit(df2, PLACEBOS, PLACEBO_REPS, spec)]
|
|
plc += [stacked_fit(df2, [pc], PLACEBO_REPS, spec) for pc in PLACEBOS]
|
|
plc = [p for p in plc if p is not None]
|
|
if plc:
|
|
plc = pd.concat(plc, ignore_index=True)
|
|
print(plc.to_string(index=False))
|
|
results.append(plc.assign(kind="placebo", groups="2"))
|
|
|
|
# ---- three groups (sp, mp-only, both), all games
|
|
for spec in ["crossers", "rd"]:
|
|
print(f"\n=== {spec.upper()} 3-group: stacked real cutoffs ===")
|
|
real3 = stacked_fit3(df, CUTOFFS, BOOT_REPS, spec)
|
|
if real3 is None:
|
|
continue
|
|
print(real3.to_string(index=False))
|
|
results.append(real3.assign(kind="real", groups="3"))
|
|
|
|
print(f"\n=== {spec.upper()} 3-group: placebos (stacked) ===")
|
|
plc3 = stacked_fit3(df, PLACEBOS, PLACEBO_REPS, spec)
|
|
if plc3 is not None:
|
|
print(plc3.to_string(index=False))
|
|
results.append(plc3.assign(kind="placebo", groups="3"))
|
|
|
|
if results:
|
|
pd.concat(results).to_csv("ell_results.csv", index=False)
|
|
print("Saved ell_results.csv") |