new data
This commit is contained in:
+189
-211
@@ -1,14 +1,26 @@
|
||||
"""
|
||||
Label-cutoff RD, run separately for single-player (sp), multiplayer-only (mp),
|
||||
both, and all games pooled. Self-contained.
|
||||
Label-cutoff RD: difference-in-discontinuities ("did") and triple difference ("triple").
|
||||
Memory-lean version: each game is processed on its own, only rows near a cutoff are kept,
|
||||
the trimmed panel is cached, and models are fitted one at a time.
|
||||
|
||||
Inputs:
|
||||
game_tags.csv columns: sheet, genres, group ("sp"/"mp"/"both"), price
|
||||
game_tags.csv columns: sheet, genres, group ("sp"/"mp"/"both"), price
|
||||
data/<sheet>.csv columns: date, positive, negative
|
||||
|
||||
Usage:
|
||||
python game_test.py did --spec rd --group mp both sp --w 0.02
|
||||
python game_test.py did --spec crossers --group mp both
|
||||
python game_test.py triple --spec rd crossers --w 0.02
|
||||
python game_test.py did --spec rd --group sp --n-sp 300 # subsample single-player
|
||||
python game_test.py did --reps 299 # wild bootstrap (slow)
|
||||
python game_test.py did --rebuild # rebuild cached panel
|
||||
|
||||
Install: pip install pandas numpy pyfixest
|
||||
"""
|
||||
import argparse
|
||||
import gc
|
||||
import os
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
@@ -16,31 +28,33 @@ import pandas as pd
|
||||
# ----------------------------------------------------------------- settings
|
||||
DATA_DIR = "data"
|
||||
TAGS_FILE = "game_tags.csv"
|
||||
OUT_DID = "ell_did.csv"
|
||||
OUT_TRIPLE = "ell_triple.csv"
|
||||
|
||||
# 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
|
||||
MIN_SPAN_DAYS = 365
|
||||
MAX_SPAN_DAYS = 10 * 365
|
||||
MIN_TOTAL_REVIEWS = 2000 # all reviews in the file
|
||||
MIN_TOTAL_REVIEWS = 2000
|
||||
|
||||
# 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
|
||||
MIN_GAMES = 10 # per cell
|
||||
TIME_FE = "month"
|
||||
CUTOFFS = [0.70, 0.80, 0.95]
|
||||
PLACEBOS = [0.60, 0.75, 0.85, 0.90]
|
||||
BOOT_REPS = 999
|
||||
PLACEBO_REPS = 499
|
||||
SEED = 42
|
||||
|
||||
PANEL_W = 0.03 # panel keeps rows within this distance of any cutoff,
|
||||
PANEL_FILE = "panel_w03.pkl" # so any --w up to 0.03 can reuse it
|
||||
KEEP = ["sheet", "group", "MP", "BOTH", "lnR", "S_lag", "N_lag", "ln_N",
|
||||
"ln_age", "ln_price", "no_price", "month", "rel_year"]
|
||||
|
||||
# ----------------------------------------------------------------- step 1: choose games, load panel
|
||||
|
||||
# ----------------------------------------------------------------- panel
|
||||
def load_tags():
|
||||
tags = pd.read_csv(TAGS_FILE, dtype={"sheet": str})
|
||||
tags["sheet"] = tags["sheet"].str.strip()
|
||||
@@ -48,19 +62,46 @@ def load_tags():
|
||||
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
|
||||
tags["price"] = pd.to_numeric(tags["price"], errors="coerce")
|
||||
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."""
|
||||
def process_game(d, sheet):
|
||||
"""Score, lags, controls for one game; keep only rows near a cutoff."""
|
||||
d = d.sort_values("date").reset_index(drop=True)
|
||||
R = d["positive"] + d["negative"]
|
||||
cum_tot = R.cumsum()
|
||||
score = d["positive"].cumsum() / cum_tot.replace(0, np.nan)
|
||||
|
||||
out = pd.DataFrame({"S_lag": score.shift(1), "N_lag": cum_tot.shift(1), "R": R})
|
||||
first = d["date"].iloc[0]
|
||||
out["lnR"] = np.log1p(R)
|
||||
out["ln_N"] = np.log(out["N_lag"].clip(lower=1))
|
||||
out["ln_age"] = np.log1p((d["date"] - first).dt.days)
|
||||
out["month"] = d["date"].dt.to_period("M").astype(str)
|
||||
out["rel_year"] = str(first.year)
|
||||
|
||||
if TRIM_Q is not None:
|
||||
out = out[out["R"] <= R.quantile(TRIM_Q)]
|
||||
out = out.dropna(subset=["S_lag", "N_lag"])
|
||||
out = out[out["N_lag"] >= MIN_REVIEWS]
|
||||
|
||||
cuts = np.array(CUTOFFS + PLACEBOS)
|
||||
near = (np.abs(out["S_lag"].to_numpy()[:, None] - cuts[None, :]) <= PANEL_W).any(axis=1)
|
||||
out = out[near].drop(columns="R")
|
||||
if out.empty:
|
||||
return None
|
||||
out["sheet"] = sheet
|
||||
return out
|
||||
|
||||
|
||||
def build_panel(tags):
|
||||
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
|
||||
frames, n_nofile, n_span, n_rev, n_near = [], 0, 0, 0, 0
|
||||
for sheet in games["sheet"]:
|
||||
path = os.path.join(DATA_DIR, f"{sheet}.csv")
|
||||
if not os.path.exists(path):
|
||||
@@ -72,7 +113,6 @@ def select_and_load(tags):
|
||||
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
|
||||
@@ -83,85 +123,87 @@ def select_and_load(tags):
|
||||
|
||||
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)
|
||||
.reindex(full, fill_value=0).rename_axis("date").reset_index())
|
||||
g = process_game(d, sheet)
|
||||
if g is None:
|
||||
n_near += 1
|
||||
continue
|
||||
frames.append(g)
|
||||
|
||||
print(f"dropped: no file/empty {n_nofile}, span {n_span}, reviews {n_rev}; kept {len(frames)}")
|
||||
print(f"dropped: no file/empty {n_nofile}, span {n_span}, reviews {n_rev}, "
|
||||
f"never near a cutoff {n_near}; 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 = pd.concat(frames, ignore_index=True)
|
||||
del frames
|
||||
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())
|
||||
df = df[KEEP]
|
||||
|
||||
# S_lag stays float64 on purpose: float32 can put a score of exactly 0.70 below the cutoff
|
||||
for c in ["lnR", "N_lag", "ln_N", "ln_age", "ln_price"]:
|
||||
df[c] = df[c].astype("float32")
|
||||
for c in ["sheet", "group", "month", "rel_year"]:
|
||||
df[c] = df[c].astype("category")
|
||||
|
||||
print("games per group:", df.groupby("group", observed=True)["sheet"].nunique().to_dict())
|
||||
print(f"panel: {len(df):,} rows, {df.memory_usage(deep=True).sum() / 1e9:.2f} GB")
|
||||
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"])
|
||||
def get_panel(rebuild=False):
|
||||
if os.path.exists(PANEL_FILE) and not rebuild:
|
||||
df = pd.read_pickle(PANEL_FILE)
|
||||
print(f"loaded cached panel {PANEL_FILE}: {len(df):,} rows, "
|
||||
f"{df['sheet'].nunique()} games")
|
||||
return df
|
||||
df = build_panel(load_tags())
|
||||
df.to_pickle(PANEL_FILE)
|
||||
return df
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- RD helpers
|
||||
def stack(df, cutoffs, spec="rd"):
|
||||
def subsample_sp(df, n):
|
||||
sp = df.loc[df["group"] == "sp", "sheet"].astype(str).unique()
|
||||
keep = set(np.random.default_rng(SEED).choice(sp, min(n, len(sp)), replace=False))
|
||||
out = df[(df["group"] != "sp") | df["sheet"].astype(str).isin(keep)]
|
||||
print(f"single-player subsample: {min(n, len(sp))} of {len(sp)} games")
|
||||
return out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- helpers
|
||||
def stack(df, cutoffs, spec, w):
|
||||
"""One row per game-day per 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:
|
||||
s = base[(base["S_lag"] - c).abs() <= W].copy()
|
||||
s = df[(df["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
|
||||
crosses = s.groupby("sheet", observed=True)["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
|
||||
for c in ("sheet", "month", "rel_year"):
|
||||
s[c] = s[c].astype(str)
|
||||
s["dist_x_D"] = s["dist"] * s["D"]
|
||||
s["gid"] = pd.factorize(s["sheet"])[0] # cluster id
|
||||
s["gid"] = pd.factorize(s["sheet"])[0]
|
||||
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."""
|
||||
"""Wild cluster bootstrap p-value. reps=0 skips it."""
|
||||
if not reps:
|
||||
return np.nan
|
||||
try:
|
||||
r = model.wildboottest(param=param, reps=reps, seed=SEED)
|
||||
return float(r["Pr(>|t|)"])
|
||||
@@ -170,87 +212,48 @@ 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]
|
||||
|
||||
s = stack(sub, cutoffs, spec)
|
||||
if s.empty:
|
||||
print(f"[{spec}] {group} {cutoffs}: no rows, skipped")
|
||||
return None
|
||||
|
||||
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]
|
||||
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 = ["gc", TIME_FE]
|
||||
|
||||
def fit_model(s, regs, ctrl, fes):
|
||||
import pyfixest as pf
|
||||
m = pf.feols(f"lnR ~ {' + '.join(regs + ctrl)} | {' + '.join(fes)}",
|
||||
data=s, vcov={"CRV1": "gid"})
|
||||
return pf.feols(f"lnR ~ {' + '.join(regs + ctrl)} | {' + '.join(fes)}",
|
||||
data=s, vcov={"CRV1": "gid"})
|
||||
|
||||
|
||||
def tidy_rows(m, labels, reps, **extra):
|
||||
t = m.tidy()
|
||||
if "D" not in t.index:
|
||||
print(f"[{spec}] {group}: D dropped as collinear, skipped")
|
||||
return None
|
||||
|
||||
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))])
|
||||
rows = []
|
||||
for par, label in labels.items():
|
||||
if par not in t.index:
|
||||
continue
|
||||
est, se = float(t.loc[par, "Estimate"]), float(t.loc[par, "Std. Error"])
|
||||
rows.append(dict(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),
|
||||
pct=100 * (np.exp(est) - 1), obs=int(m._N), **extra))
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
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."""
|
||||
# ----------------------------------------------------------------- tests
|
||||
def fit_did(df, group, spec, w, reps=0):
|
||||
"""Difference-in-discontinuities: real-cutoff jump minus placebo-cutoff jump."""
|
||||
sub = df if group == "all" else df[df["group"] == group]
|
||||
|
||||
s = stack(sub, CUTOFFS + PLACEBOS, spec) # real and placebo cutoffs together
|
||||
s = stack(sub, CUTOFFS + PLACEBOS, spec, w)
|
||||
if s.empty:
|
||||
print(f"[{spec}] {group}: no rows, skipped")
|
||||
return None
|
||||
|
||||
real_cuts = [f"{c:.3f}" for c in CUTOFFS]
|
||||
s["real"] = s["cut"].isin(real_cuts).astype(int)
|
||||
|
||||
# check there are enough games on each side for both kinds of cutoff
|
||||
s["real"] = s["cut"].isin([f"{c:.3f}" for c in CUTOFFS]).astype(int)
|
||||
side = s.groupby(["real", "D"])["sheet"].nunique()
|
||||
print(f"[{spec}] {group}: games per (real, D): {side.to_dict()}")
|
||||
if side.min() < MIN_GAMES or len(side) < 4:
|
||||
print(f"[{spec}] {group}: too few games per side {side.to_dict()}, skipped")
|
||||
print(f"[{spec}] {group}: too few games per side, 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
|
||||
if group == "all":
|
||||
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]
|
||||
@@ -260,52 +263,38 @@ def fit_did(df, group, spec="rd", reps=BOOT_REPS):
|
||||
ctrl = [c for c in ["ln_age", "ln_N", "ln_price", "no_price"] if s[c].nunique() > 1]
|
||||
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
|
||||
fes = [TIME_FE, "rel_year", "cut"]
|
||||
else:
|
||||
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()
|
||||
m = fit_model(s, regs, ctrl, fes)
|
||||
out = tidy_rows(m, {"D": "placebo jump (D)", "D_x_real": "real minus placebo (D_x_real)"},
|
||||
reps, spec=spec, group=group)
|
||||
del s, m
|
||||
gc.collect()
|
||||
return out
|
||||
|
||||
rows = []
|
||||
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):
|
||||
def fit_did_mp(df, spec, w, reps=0):
|
||||
"""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)
|
||||
sub = df[df["group"].isin(["sp", "mp"])]
|
||||
s = stack(sub, CUTOFFS + PLACEBOS, spec, w)
|
||||
if s.empty:
|
||||
print(f"[{spec}] triple: no rows, skipped")
|
||||
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
|
||||
s["real"] = s["cut"].isin([f"{c:.3f}" for c in CUTOFFS]).astype(int)
|
||||
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"]
|
||||
@@ -314,76 +303,65 @@ def fit_did_mp(df, spec="rd", reps=BOOT_REPS):
|
||||
|
||||
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", "ln_price", "no_price", "MP", "real_x_MP"]
|
||||
if s[c].nunique() > 1]
|
||||
fes = [TIME_FE, "rel_year", "cut"]
|
||||
else:
|
||||
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()
|
||||
|
||||
m = fit_model(s, regs, ctrl, fes)
|
||||
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"])
|
||||
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),
|
||||
obs=int(m._N)))
|
||||
return pd.DataFrame(rows)
|
||||
out = tidy_rows(m, labels, reps, spec=spec)
|
||||
del s, m
|
||||
gc.collect()
|
||||
return out
|
||||
|
||||
|
||||
def save(row, path, w, n_sp):
|
||||
row = row.assign(w=w, n_sp=n_sp if n_sp else "all")
|
||||
row.to_csv(path, mode="a", header=not os.path.exists(path), index=False)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- run
|
||||
if __name__ == "__main__":
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest")
|
||||
warnings.filterwarnings("ignore", category=RuntimeWarning)
|
||||
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
|
||||
pd.set_option("display.width", 220)
|
||||
|
||||
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")
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("test", choices=["did", "triple"])
|
||||
ap.add_argument("--spec", nargs="+", default=["rd", "crossers"], choices=["rd", "crossers"])
|
||||
ap.add_argument("--group", nargs="+", default=["mp", "both", "sp"],
|
||||
choices=["sp", "mp", "both", "all"])
|
||||
ap.add_argument("--w", type=float, default=0.02, help=f"window half-width, max {PANEL_W}")
|
||||
ap.add_argument("--reps", type=int, default=0, help="bootstrap reps (0 = off)")
|
||||
ap.add_argument("--n-sp", type=int, default=None, help="subsample single-player games")
|
||||
ap.add_argument("--rebuild", action="store_true")
|
||||
a = ap.parse_args()
|
||||
if a.w > PANEL_W:
|
||||
raise SystemExit(f"--w must be <= {PANEL_W}; raise PANEL_W and use --rebuild")
|
||||
|
||||
df = get_panel(a.rebuild)
|
||||
if a.n_sp:
|
||||
df = subsample_sp(df, a.n_sp)
|
||||
print(f"W = {a.w}, bootstrap reps = {a.reps}")
|
||||
|
||||
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()} 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()} 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))
|
||||
res.append(plc.assign(kind="placebo"))
|
||||
|
||||
if res:
|
||||
pd.concat(res).to_csv("ell_by_group.csv", index=False)
|
||||
print("Saved ell_by_group.csv")
|
||||
'''
|
||||
for spec in a.spec:
|
||||
if a.test == "did":
|
||||
for g in a.group:
|
||||
print(f"\nrunning did {spec} / {g} ...", flush=True)
|
||||
r = fit_did(df, g, spec, a.w, a.reps)
|
||||
if r is not None:
|
||||
print(r.to_string(index=False), flush=True)
|
||||
save(r, OUT_DID, a.w, a.n_sp)
|
||||
else:
|
||||
print(f"\nrunning triple {spec} ...", flush=True)
|
||||
r = fit_did_mp(df, spec, a.w, a.reps)
|
||||
if r is not None:
|
||||
print(r.to_string(index=False), flush=True)
|
||||
save(r, OUT_TRIPLE, a.w, a.n_sp)
|
||||
Reference in New Issue
Block a user