new paradigm
This commit is contained in:
+102
-55
@@ -1,12 +1,23 @@
|
||||
"""
|
||||
Estimate ell (label-cutoff effect on daily new reviews) for each Steam review-label cutoff.
|
||||
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_{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.
|
||||
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 statsmodels fallback with month dummies is used)
|
||||
(pyfixest is optional; without it a slower statsmodels fallback is used)
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
@@ -15,12 +26,13 @@ import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
# ----------------------------------------------------------------- settings
|
||||
DATA_GLOB = "data/*.csv" # one CSV per game: date, positive, negative
|
||||
DATA_GLOB = "data/*.csv"
|
||||
TAGS_FILE = "game_tags.csv"
|
||||
CUTOFFS = [0.20, 0.40, 0.70, 0.80, 0.95]
|
||||
W = 0.03 # window half-width in score (0.02 = 2 pp)
|
||||
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 # skip cutoffs with fewer crossing games
|
||||
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
|
||||
|
||||
@@ -39,6 +51,20 @@ def load(pattern):
|
||||
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)
|
||||
@@ -54,6 +80,7 @@ def build(df):
|
||||
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)
|
||||
@@ -69,30 +96,35 @@ def build(df):
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- estimation
|
||||
def fit(sample):
|
||||
"""Return (ell, se, p, nobs), or None if the model cannot be estimated."""
|
||||
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 ~ D + dist + ln_age | sheet + {TIME_FE}",
|
||||
m = pf.feols(f"lnR ~ {rhs} | 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)
|
||||
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]
|
||||
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)
|
||||
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):
|
||||
@@ -102,75 +134,90 @@ def solve(df, cutoffs):
|
||||
s = base.copy()
|
||||
s["dist"] = s["S_lag"] - c
|
||||
s["D"] = (s["dist"] >= 0).astype(int)
|
||||
s = s[s["dist"].abs() <= W]
|
||||
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)]
|
||||
n_games = s["sheet"].nunique()
|
||||
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 n_games < MIN_CROSSING_GAMES:
|
||||
print(f"c={c:.2f}: only {n_games} crossing games, skipped")
|
||||
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
|
||||
|
||||
out = fit(s)
|
||||
if out is None:
|
||||
print(f"c={c:.2f}: model could not be estimated (collinear or too few rows), skipped")
|
||||
# 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, 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))
|
||||
|
||||
(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):
|
||||
w = 1 / res["se"] ** 2
|
||||
ell = (w * res["ell"]).sum() / w.sum()
|
||||
se = np.sqrt(1 / w.sum())
|
||||
return ell, se
|
||||
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(load(DATA_GLOB))
|
||||
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 touch a real cutoff, or they are not placebos
|
||||
# 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:.2f} is within 2*W of a real cutoff")
|
||||
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. Widen W or add games.")
|
||||
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}")
|
||||
print("\nEll per REAL cutoff (log points; pct_effect = % change in daily reviews):")
|
||||
pd.set_option("display.width", 200)
|
||||
print("\nREAL cutoffs (log points; pct_* = % 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)")
|
||||
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("\nEll per PLACEBO cutoff (no label changes here):")
|
||||
print("\nPLACEBO cutoffs (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)
|
||||
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")
|
||||
Reference in New Issue
Block a user