remove bloat
This commit is contained in:
+299
-338
@@ -1,60 +1,145 @@
|
||||
"""
|
||||
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.
|
||||
Label-cutoff RD, run separately for single-player (sp), multiplayer-only (mp),
|
||||
both, and all games pooled. Self-contained.
|
||||
|
||||
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)
|
||||
game_tags.csv columns: sheet, genres, group ("sp"/"mp"/"both"), price
|
||||
data/<sheet>.csv columns: date, positive, negative
|
||||
|
||||
Install: pip install pandas numpy statsmodels pyfixest
|
||||
Install: pip install pandas numpy pyfixest
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
# ----------------------------------------------------------------- settings
|
||||
DATA_GLOB = "data/*.csv"
|
||||
DATA_DIR = "data"
|
||||
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
|
||||
|
||||
# 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"
|
||||
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
|
||||
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 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:
|
||||
@@ -70,21 +155,13 @@ def stack(df, cutoffs, spec="rd"):
|
||||
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
|
||||
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 (clusters = games, from vcov CRV1)."""
|
||||
"""Wild cluster bootstrap p-value for one coefficient."""
|
||||
try:
|
||||
r = model.wildboottest(param=param, reps=reps, seed=SEED)
|
||||
return float(r["Pr(>|t|)"])
|
||||
@@ -93,336 +170,220 @@ def boot_p(model, param, reps):
|
||||
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]
|
||||
|
||||
def stacked_fit(df, cutoffs, reps, spec="rd"):
|
||||
s = stack(df, cutoffs, spec)
|
||||
s = stack(sub, cutoffs, spec)
|
||||
if s.empty:
|
||||
print(f"[{spec}] {cutoffs}: no rows in window, skipped")
|
||||
print(f"[{spec}] {group} {cutoffs}: no rows, 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")
|
||||
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]
|
||||
fes = " + ".join([TIME_FE, "rel_year", "cut"])
|
||||
else: # price, release year and MP level are absorbed by the game x cutoff effect
|
||||
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 = " + ".join(["gc", TIME_FE])
|
||||
cl = {"CRV1": "gid"}
|
||||
fes = ["gc", TIME_FE]
|
||||
|
||||
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()
|
||||
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
|
||||
|
||||
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)
|
||||
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 stacked_fit3(df, cutoffs, reps, spec="crossers"):
|
||||
s = stack(df, cutoffs, spec)
|
||||
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
|
||||
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
|
||||
real_cuts = [f"{c:.3f}" for c in CUTOFFS]
|
||||
s["real"] = s["cut"].isin(real_cuts).astype(int)
|
||||
|
||||
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"]
|
||||
# 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]
|
||||
fes = " + ".join([TIME_FE, "rel_year", "cut"])
|
||||
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 = " + ".join(["gc", TIME_FE])
|
||||
fes = ["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"}
|
||||
m = pf.feols(f"lnR ~ {' + '.join(regs + ctrl)} | {' + '.join(fes)}",
|
||||
data=s, vcov={"CRV1": "gid"})
|
||||
t = m.tidy()
|
||||
|
||||
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")]:
|
||||
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"])
|
||||
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"]),
|
||||
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),
|
||||
games=s[grp[gname[label]]]["sheet"].nunique() if label in gname else np.nan))
|
||||
obs=int(m._N)))
|
||||
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 = []
|
||||
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")
|
||||
|
||||
# ---- two groups (sp vs mp-only), "both" excluded
|
||||
|
||||
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()} 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()} 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()} 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(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))
|
||||
results.append(plc.assign(kind="placebo", groups="2"))
|
||||
res.append(plc.assign(kind="placebo"))
|
||||
|
||||
# ---- 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")
|
||||
if res:
|
||||
pd.concat(res).to_csv("ell_by_group.csv", index=False)
|
||||
print("Saved ell_by_group.csv")
|
||||
'''
|
||||
Reference in New Issue
Block a user