This commit is contained in:
2026-11-19 10:29:09 +01:00
parent 5a55a5ca14
commit 646c634f54
152 changed files with 264874 additions and 0 deletions
+176
View File
@@ -0,0 +1,176 @@
"""
Estimate ell (label-cutoff effect on daily new reviews) for 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_{i,t-1} - c) + ell*D_{i,t-1} + beta*ln(Age_it) + e_it
D = 1 if S_{t-1} >= c. Game and day fixed effects, SE clustered by game.
Install: pip install pandas numpy statsmodels pyfixest
(pyfixest is optional; without it a statsmodels fallback with month dummies is used)
"""
import glob
import os
import numpy as np
import pandas as pd
# ----------------------------------------------------------------- settings
DATA_GLOB = "data/*.csv" # one CSV per game: date, positive, negative
CUTOFFS = [0.20, 0.40, 0.70, 0.80, 0.95]
W = 0.02 # window half-width in score (0.02 = 2 pp)
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 # skip cutoffs with fewer crossing games
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 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["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):
"""Return (ell, se, p, nobs), or None if the model cannot be estimated."""
try:
import pyfixest as pf
except ImportError:
pf = None
if pf is not None:
try:
m = pf.feols(f"lnR ~ D + dist + ln_age | sheet + {TIME_FE}",
data=sample, vcov={"CRV1": "sheet"})
t = m.tidy()
if "D" not in t.index: # D was dropped as collinear
return None
r = t.loc["D"]
return float(r["Estimate"]), float(r["Std. Error"]), float(r["Pr(>|t|)"]), int(m._N)
except (ZeroDivisionError, ValueError, np.linalg.LinAlgError):
return None
import statsmodels.formula.api as smf
groups = pd.factorize(sample["sheet"])[0]
m = smf.ols(f"lnR ~ D + dist + ln_age + C(sheet) + C({TIME_FE})", data=sample).fit(
cov_type="cluster", cov_kwds={"groups": groups})
return float(m.params["D"]), float(m.bse["D"]), float(m.pvalues["D"]), 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]
# 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)]
n_games = s["sheet"].nunique()
if n_games < MIN_CROSSING_GAMES:
print(f"c={c:.2f}: only {n_games} crossing games, skipped")
continue
out = fit(s)
if out is None:
print(f"c={c:.2f}: model could not be estimated (collinear or too few rows), skipped")
continue
ell, se, p, n = out
rows.append(dict(cutoff=c, ell=ell, se=se, p=p,
pct_effect=100 * (np.exp(ell) - 1),
games=n_games, obs=n))
return pd.DataFrame(rows)
def pool(res):
w = 1 / res["se"] ** 2
ell = (w * res["ell"]).sum() / w.sum()
se = np.sqrt(1 / w.sum())
return ell, se
# ----------------------------------------------------------------- run
if __name__ == "__main__":
df = build(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 touch a real cutoff, 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:.2f} is within 2*W of a real cutoff")
res = solve(df, CUTOFFS)
if res.empty:
raise SystemExit("No cutoff had enough crossing games. Widen W or add games.")
plc = solve(df, PLACEBOS)
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
print("\nEll per REAL cutoff (log points; pct_effect = % change in daily reviews):")
print(res.to_string(index=False))
ell, se = pool(res)
print(f"\nPooled ell (inverse-variance): {ell:.4f} (SE {se:.4f}, "
f"~{100 * (np.exp(ell) - 1):.1f}% change in daily reviews)")
if plc.empty:
print("\nNo placebo cutoff had enough crossing games.")
else:
print("\nEll per PLACEBO cutoff (no label changes here):")
print(plc.to_string(index=False))
n_sig = int((plc["p"] < 0.05).sum())
print(f"\nPlacebo summary: {len(plc)} cutoffs, mean ell {plc['ell'].mean():.4f}, "
f"mean |ell| {plc['ell'].abs().mean():.4f}, {n_sig} significant at 5%")
print("Real cutoffs with |ell| larger than the largest placebo |ell|:",
(res["ell"].abs() > plc["ell"].abs().max()).sum(), "of", len(res))
res.assign(kind="real").pipe(
lambda r: pd.concat([r, plc.assign(kind="placebo")])
).to_csv("ell_results.csv", index=False)
print("Saved ell_results.csv (real + placebo)")
raise SystemExit(0)
res.to_csv("ell_results.csv", index=False)
print("Saved ell_results.csv")