new data and test options
This commit is contained in:
+112
-28
@@ -1,16 +1,33 @@
|
||||
"""
|
||||
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,
|
||||
Memory-lean: 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.
|
||||
|
||||
Noise reduction options (all chosen on the command line, none on by default):
|
||||
--fe {month,week,day} time fixed effect. "day" removes anything that hits all games on the
|
||||
same date (seasonal sales, weekends, holidays).
|
||||
--spike K drop game-days where R > K * (rolling 29-day median of R + 5),
|
||||
i.e. a game-specific burst such as its own discount. 0 = off.
|
||||
--vol7 MODE recent review volume, SENSITIVITY CHECK ONLY (bad-control risk:
|
||||
after a label change the lagged volume already contains the effect,
|
||||
which biases the estimate toward zero).
|
||||
off baseline, no control, all rows
|
||||
sample drop rows without 14 days of history, no control
|
||||
control sample + control ln(1 + mean reviews, days t-7..t-1)
|
||||
control_lagged sample + control ln(1 + mean reviews, days t-14..t-8)
|
||||
Compare "control" and "control_lagged" with "sample", not with "off":
|
||||
"sample" uses exactly the same rows, so the difference is the control.
|
||||
|
||||
Inputs:
|
||||
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 crossers --group mp both sp --w 0.02 --fe day --spike 3
|
||||
python game_test.py did --spec crossers --group mp both sp --w 0.02 --vol7 sample
|
||||
python game_test.py did --spec crossers --group mp both sp --w 0.02 --vol7 control
|
||||
python game_test.py triple --spec crossers --w 0.02 --vol7 control_lagged
|
||||
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
|
||||
@@ -43,15 +60,15 @@ MIN_TOTAL_REVIEWS = 2000
|
||||
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 cell
|
||||
TIME_FE = "month"
|
||||
CUTOFFS = [0.70, 0.80, 0.95]
|
||||
PLACEBOS = [0.60, 0.75, 0.85, 0.90]
|
||||
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
|
||||
VOL_COLS = ["ln_vol7", "ln_vol7_old"]
|
||||
KEEP = ["sheet", "group", "MP", "BOTH", "lnR", "S_lag", "N_lag", "ln_N",
|
||||
"ln_age", "ln_price", "no_price", "month", "rel_year"]
|
||||
"ln_age", "ln_price", "no_price", "month", "rel_year", "date", "spike_ratio"] + VOL_COLS
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- panel
|
||||
@@ -73,6 +90,15 @@ def process_game(d, sheet):
|
||||
cum_tot = R.cumsum()
|
||||
score = d["positive"].cumsum() / cum_tot.replace(0, np.nan)
|
||||
|
||||
# burst ratio: today's reviews relative to the game's own recent median (stored, filtered later)
|
||||
med = R.rolling(29, center=True, min_periods=7).median().fillna(0)
|
||||
|
||||
# recent volume, computed on the full daily series before any trimming:
|
||||
# vol7 mean reviews over days t-7 ... t-1
|
||||
# vol7_old mean reviews over days t-14 ... t-8 (predates most of a post-crossing effect)
|
||||
vol7 = R.shift(1).rolling(7, min_periods=7).mean()
|
||||
vol7_old = R.shift(8).rolling(7, min_periods=7).mean()
|
||||
|
||||
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)
|
||||
@@ -80,6 +106,10 @@ def process_game(d, sheet):
|
||||
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)
|
||||
out["date"] = d["date"]
|
||||
out["spike_ratio"] = (R / (med + 5)).astype("float32")
|
||||
out["ln_vol7"] = np.log1p(vol7).astype("float32")
|
||||
out["ln_vol7_old"] = np.log1p(vol7_old).astype("float32")
|
||||
|
||||
if TRIM_Q is not None:
|
||||
out = out[out["R"] <= R.quantile(TRIM_Q)]
|
||||
@@ -159,14 +189,35 @@ def build_panel(tags):
|
||||
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
|
||||
if {"date", "spike_ratio"} | set(VOL_COLS) <= set(df.columns):
|
||||
print(f"loaded cached panel {PANEL_FILE}: {len(df):,} rows, "
|
||||
f"{df['sheet'].nunique()} games")
|
||||
return df
|
||||
print("cached panel is from an older version (missing columns), rebuilding")
|
||||
df = build_panel(load_tags())
|
||||
df.to_pickle(PANEL_FILE)
|
||||
return df
|
||||
|
||||
|
||||
def drop_spikes(df, k):
|
||||
if not k:
|
||||
return df
|
||||
before = len(df)
|
||||
df = df[df["spike_ratio"] <= k]
|
||||
print(f"spike filter (ratio <= {k}): dropped {before - len(df):,} of {before:,} game-days")
|
||||
return df
|
||||
|
||||
|
||||
def match_volume_sample(df, mode):
|
||||
"""sample / control / control_lagged all use the same rows: those with both volume measures."""
|
||||
if mode == "off":
|
||||
return df
|
||||
before = len(df)
|
||||
df = df.dropna(subset=VOL_COLS)
|
||||
print(f"vol7 sample: dropped {before - len(df):,} of {before:,} game-days without 14 days of history")
|
||||
return df
|
||||
|
||||
|
||||
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))
|
||||
@@ -175,7 +226,27 @@ def subsample_sp(df, n):
|
||||
return out
|
||||
|
||||
|
||||
def add_time_fe(df, fe, keep_cols=()):
|
||||
"""Create the time fixed-effect column "tfe" (month, week or day) and drop unused columns."""
|
||||
df = df.copy()
|
||||
if fe == "month":
|
||||
df["tfe"] = df["month"].astype(str)
|
||||
elif fe == "week":
|
||||
df["tfe"] = df["date"].dt.to_period("W").astype(str)
|
||||
else:
|
||||
df["tfe"] = df["date"].dt.strftime("%Y%m%d")
|
||||
df["tfe"] = df["tfe"].astype("category")
|
||||
print(f"time fixed effect: {fe} ({df['tfe'].nunique()} levels)")
|
||||
drop = ["date", "month", "spike_ratio"] + [c for c in VOL_COLS if c not in keep_cols]
|
||||
return df.drop(columns=drop)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- helpers
|
||||
def pick(s, cols):
|
||||
"""Keep only columns that exist and vary."""
|
||||
return [c for c in cols if c in s.columns and s[c].nunique() > 1]
|
||||
|
||||
|
||||
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."""
|
||||
@@ -192,7 +263,7 @@ def stack(df, cutoffs, spec, w):
|
||||
s = pd.concat(parts, ignore_index=True)
|
||||
if s.empty:
|
||||
return s
|
||||
for c in ("sheet", "month", "rel_year"):
|
||||
for c in ("sheet", "tfe", "rel_year"):
|
||||
s[c] = s[c].astype(str)
|
||||
s["dist_x_D"] = s["dist"] * s["D"]
|
||||
s["gid"] = pd.factorize(s["sheet"])[0]
|
||||
@@ -234,7 +305,7 @@ def tidy_rows(m, labels, reps, **extra):
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- tests
|
||||
def fit_did(df, group, spec, w, reps=0):
|
||||
def fit_did(df, group, spec, w, reps=0, vctrl=()):
|
||||
"""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, w)
|
||||
@@ -260,13 +331,13 @@ def fit_did(df, group, spec, w, reps=0):
|
||||
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]
|
||||
ctrl = pick(s, ["ln_age", "ln_N", "ln_price", "no_price"] + list(vctrl))
|
||||
if group == "all":
|
||||
ctrl += [c for c in ["MP", "BOTH"] if s[c].nunique() > 1]
|
||||
fes = [TIME_FE, "rel_year", "cut"]
|
||||
ctrl += pick(s, ["MP", "BOTH"])
|
||||
fes = ["tfe", "rel_year", "cut"]
|
||||
else:
|
||||
ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1]
|
||||
fes = ["gc", TIME_FE]
|
||||
ctrl = pick(s, ["ln_age", "ln_N"] + list(vctrl))
|
||||
fes = ["gc", "tfe"]
|
||||
|
||||
m = fit_model(s, regs, ctrl, fes)
|
||||
out = tidy_rows(m, {"D": "placebo jump (D)", "D_x_real": "real minus placebo (D_x_real)"},
|
||||
@@ -276,7 +347,7 @@ def fit_did(df, group, spec, w, reps=0):
|
||||
return out
|
||||
|
||||
|
||||
def fit_did_mp(df, spec, w, reps=0):
|
||||
def fit_did_mp(df, spec, w, reps=0, vctrl=()):
|
||||
"""Triple difference: (mp real-minus-placebo) minus (sp real-minus-placebo)."""
|
||||
sub = df[df["group"].isin(["sp", "mp"])]
|
||||
s = stack(sub, CUTOFFS + PLACEBOS, spec, w)
|
||||
@@ -303,12 +374,11 @@ def fit_did_mp(df, spec, w, reps=0):
|
||||
|
||||
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"]
|
||||
ctrl = pick(s, ["ln_age", "ln_N", "ln_price", "no_price", "MP", "real_x_MP"] + list(vctrl))
|
||||
fes = ["tfe", "rel_year", "cut"]
|
||||
else:
|
||||
ctrl = [c for c in ["ln_age", "ln_N"] if s[c].nunique() > 1]
|
||||
fes = ["gc", TIME_FE]
|
||||
ctrl = pick(s, ["ln_age", "ln_N"] + list(vctrl))
|
||||
fes = ["gc", "tfe"]
|
||||
|
||||
m = fit_model(s, regs, ctrl, fes)
|
||||
labels = {"D": "placebo jump, sp",
|
||||
@@ -321,8 +391,9 @@ def fit_did_mp(df, spec, w, reps=0):
|
||||
return out
|
||||
|
||||
|
||||
def save(row, path, w, n_sp):
|
||||
row = row.assign(w=w, n_sp=n_sp if n_sp else "all")
|
||||
def save(row, path, **settings):
|
||||
"""Append rows with the settings used, so results from different runs stay distinguishable."""
|
||||
row = row.assign(**settings)
|
||||
row.to_csv(path, mode="a", header=not os.path.exists(path), index=False)
|
||||
|
||||
|
||||
@@ -339,6 +410,12 @@ if __name__ == "__main__":
|
||||
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("--fe", choices=["month", "week", "day"], default="month",
|
||||
help="time fixed effect (default month, as in earlier runs)")
|
||||
ap.add_argument("--spike", type=float, default=0,
|
||||
help="drop game-days with burst ratio above this (0 = off, try 3)")
|
||||
ap.add_argument("--vol7", choices=["off", "sample", "control", "control_lagged"],
|
||||
default="off", help="recent-volume sensitivity check (see top of file)")
|
||||
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")
|
||||
@@ -346,22 +423,29 @@ if __name__ == "__main__":
|
||||
if a.w > PANEL_W:
|
||||
raise SystemExit(f"--w must be <= {PANEL_W}; raise PANEL_W and use --rebuild")
|
||||
|
||||
vctrl = {"control": ["ln_vol7"], "control_lagged": ["ln_vol7_old"]}.get(a.vol7, [])
|
||||
|
||||
df = get_panel(a.rebuild)
|
||||
df = drop_spikes(df, a.spike)
|
||||
df = match_volume_sample(df, a.vol7)
|
||||
if a.n_sp:
|
||||
df = subsample_sp(df, a.n_sp)
|
||||
print(f"W = {a.w}, bootstrap reps = {a.reps}")
|
||||
df = add_time_fe(df, a.fe, keep_cols=vctrl)
|
||||
print(f"W = {a.w}, fe = {a.fe}, spike = {a.spike or 'off'}, vol7 = {a.vol7}, "
|
||||
f"bootstrap reps = {a.reps}")
|
||||
|
||||
settings = dict(w=a.w, fe=a.fe, spike=a.spike or "off", vol7=a.vol7, n_sp=a.n_sp or "all")
|
||||
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)
|
||||
r = fit_did(df, g, spec, a.w, a.reps, vctrl)
|
||||
if r is not None:
|
||||
print(r.to_string(index=False), flush=True)
|
||||
save(r, OUT_DID, a.w, a.n_sp)
|
||||
save(r, OUT_DID, **settings)
|
||||
else:
|
||||
print(f"\nrunning triple {spec} ...", flush=True)
|
||||
r = fit_did_mp(df, spec, a.w, a.reps)
|
||||
r = fit_did_mp(df, spec, a.w, a.reps, vctrl)
|
||||
if r is not None:
|
||||
print(r.to_string(index=False), flush=True)
|
||||
save(r, OUT_TRIPLE, a.w, a.n_sp)
|
||||
save(r, OUT_TRIPLE, **settings)
|
||||
Reference in New Issue
Block a user