new scripts and game data
This commit is contained in:
+273
-76
@@ -2,22 +2,29 @@
|
||||
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.
|
||||
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 (sheet = CSV file name without .csv;
|
||||
group = "sp", "mp" or "both"; "both" games are excluded)
|
||||
game_tags.csv columns: sheet, group ("sp", "mp" or "both"; "both" is excluded)
|
||||
|
||||
Install: pip install pandas numpy statsmodels pyfixest
|
||||
(pyfixest is optional; without it a slower statsmodels fallback is used)
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
@@ -28,13 +35,168 @@ 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
|
||||
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
|
||||
@@ -57,21 +219,29 @@ def load(pattern):
|
||||
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, dtype={"sheet": str})[["sheet", "group"]].drop_duplicates("sheet")
|
||||
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"])].copy()
|
||||
df = df[df["group"].isin(["sp", "mp", "both"])].copy()
|
||||
df["MP"] = (df["group"] == "mp").astype(int)
|
||||
return df
|
||||
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"]
|
||||
@@ -88,9 +258,12 @@ def build(df):
|
||||
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
|
||||
df["age"] = (df["date"] - g["date"].transform("min")).dt.days
|
||||
df["ln_age"] = np.log1p(df["age"]) # day 0 -> 0
|
||||
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)
|
||||
|
||||
@@ -104,9 +277,8 @@ def build(df):
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- 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."""
|
||||
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:
|
||||
@@ -115,7 +287,7 @@ def fit(sample, regs):
|
||||
rhs = " + ".join(regs)
|
||||
if pf is not None:
|
||||
try:
|
||||
m = pf.feols(f"lnR ~ {rhs} | sheet + {TIME_FE}",
|
||||
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"]),
|
||||
@@ -126,8 +298,9 @@ def fit(sample, regs):
|
||||
|
||||
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} + C(sheet) + C({TIME_FE})", data=sample).fit(
|
||||
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
|
||||
@@ -135,7 +308,9 @@ def fit(sample, regs):
|
||||
return out, int(m.nobs)
|
||||
|
||||
|
||||
def solve(df, cutoffs):
|
||||
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:
|
||||
@@ -144,88 +319,110 @@ def solve(df, cutoffs):
|
||||
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 spec == "crossers":
|
||||
crosses = s.groupby("sheet")["D"].nunique() >= 2
|
||||
s = s[s["sheet"].isin(crosses[crosses].index)].copy()
|
||||
|
||||
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")
|
||||
# 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
|
||||
|
||||
# interaction parametrisation: D = ell (single-player), D_x_MP = lambda
|
||||
# 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"]
|
||||
a = fit(s, ["D", "D_x_MP", "dist", "dist_x_MP", "ln_age"])
|
||||
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"]
|
||||
b = fit(s, ["Dsp", "Dmp", "dsp", "dmp", "ln_age"])
|
||||
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}: model could not be estimated (collinear or too few rows), skipped")
|
||||
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,
|
||||
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=n_sp, games_mp=n_mp, obs=a[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. Assumes independent estimates, which is
|
||||
only approximately true: the same game can contribute to several cutoffs."""
|
||||
"""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")
|
||||
|
||||
# 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))
|
||||
pd.set_option("display.width", 220)
|
||||
|
||||
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})")
|
||||
results = []
|
||||
|
||||
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")
|
||||
# ---- 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")
|
||||
Reference in New Issue
Block a user