import glob import os import numpy as np import pandas as pd import pyfixest as pf THRESH = 0.95 CLIP_Q = 0.995 # winsorize, don't drop DATA_GLOB = "data/*.csv" TAGS_FILE = "game_tags.csv" W = 0.02 # window half-width in score; also try 0.01 and 0.03 MIN_REVIEWS = 500 def load(pattern): frames = [] for path in glob.glob(pattern): d = pd.read_csv(path, parse_dates=["date"])[["date", "positive", "negative"]].copy() if d.empty: print(f"skipping {path}: no rows") continue 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"] = 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 add_groups(df): 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") 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) # lagged label state (what the store page showed at the start of the day) g = df.groupby("sheet") df["S_lag"] = g["score"].shift(1) df["N_lag"] = g["cum_tot"].shift(1) # winsorize bursts per game cap = df.groupby("sheet")["R"].transform(lambda x: x.quantile(CLIP_Q)) df["R_w"] = df["R"].clip(upper=cap) # baseline: mean reviews/day over days -120..-30 (ends well before today) df["base"] = (df.groupby("sheet")["R_w"] .transform(lambda x: x.shift(30).rolling(90, min_periods=60).mean())) df["y"] = df["R_w"] / df["base"].where(df["base"] > 0.2) # min baseline df["ly"] = np.log1p(df["y"]) return df.dropna(subset=["S_lag", "N_lag", "ly"]) def rd(df, thresh=THRESH, w=W): d = df[(df["N_lag"] >= MIN_REVIEWS) & ((df["S_lag"] - thresh).abs() <= w)].copy() d["x"] = d["S_lag"] - thresh d["above"] = (d["x"] >= 0).astype(int) d["xa"] = d["x"] * d["above"] # date FE = your cross-sectional normalization; cluster by game m = pf.feols("ly ~ above + x + xa | date", data=d, vcov={"CRV1": "sheet"}) return m TIERS = [0.20, 0.40, 0.70, 0.80, 0.95] # label cutoffs (500+ review regime) def add_label(df): df = df.sort_values(["sheet", "date"]).copy() pct = (df["S_lag"] * 100).round() / 100 # Steam shows rounded % df["L"] = np.searchsorted(TIERS, pct.values, side="right") df.loc[df["N_lag"] < MIN_REVIEWS, "L"] = np.nan # ignore low-count regime g = df.groupby("sheet")["L"] df["dL"] = g.diff() return df def stack(df, pre=56, post=56, gap=70, ncontrol=60, seed=0): rng = np.random.default_rng(seed) flips = df[df["dL"].fillna(0) != 0][["sheet", "date", "dL"]] flip_by_game = {s: d["date"].values for s, d in flips.groupby("sheet")} games = {s: d.set_index("date")["R_w"] for s, d in df.groupby("sheet")} out = [] for k, (_, e) in enumerate(flips.iterrows()): t0 = e["date"] # clean event: no other flip for this game within +-gap days fl = flip_by_game[e["sheet"]] if (np.abs((fl - np.datetime64(t0)) / np.timedelta64(1, "D")) <= gap).sum() > 1: continue cand = [] for s, r in games.items(): f = flip_by_game.get(s, np.array([], dtype="datetime64[ns]")) clean = not (np.abs((f - np.datetime64(t0)) / np.timedelta64(1, "D")) <= gap).any() if s == e["sheet"] or clean: cand.append(s) ctrl = [s for s in cand if s != e["sheet"]] ctrl = list(rng.choice(ctrl, min(ncontrol, len(ctrl)), replace=False)) for s in [e["sheet"]] + ctrl: r = games[s] base = r.loc[t0 - pd.Timedelta(days=120): t0 - pd.Timedelta(days=31)] win = r.loc[t0 - pd.Timedelta(days=pre): t0 + pd.Timedelta(days=post - 1)] if len(base) < 60 or len(win) < pre + post or base.mean() < 0.2: continue w = pd.DataFrame({"date": win.index, "ly": np.log1p(win.values / base.mean())}) w["rel"] = (w["date"] - t0).dt.days w["wk"] = w["rel"] // 7 w["treated"] = int(s == e["sheet"]) w["sheet"], w["stack"], w["dir"] = s, k, np.sign(e["dL"]) out.append(w) S = pd.concat(out, ignore_index=True) S["gs"] = S["stack"].astype(str) + "_" + S["sheet"] S["ds"] = S["stack"].astype(str) + "_" + S["date"].dt.strftime("%Y%m%d") return S def event_study(S, direction): d = S[S["dir"] == direction].copy() d["post"] = (d["rel"] >= 0).astype(int) m_avg = pf.feols("ly ~ treated:post | gs + ds", data=d, vcov={"CRV1": "sheet"}) m_es = pf.feols("ly ~ i(wk, treated, ref=-1) | gs + ds", data=d, vcov={"CRV1": "sheet"}) return m_avg, m_es if __name__ == "__main__": import warnings warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest") df = add_label(build(add_groups(load(DATA_GLOB)))) full = add_label(build(add_groups(load(DATA_GLOB)))) # build with no dropna S = stack(full) df = full.dropna(subset=["S_lag", "N_lag", "ly"]) # RD only for direction in (1, -1): m_avg, m_es = event_study(S, direction) print("UP" if direction == 1 else "DOWN", m_avg.coef().iloc[0], m_avg.se().iloc[0]) m_es.iplot() if False else print(m_es.tidy()[["Estimate", "Std. Error"]]) pd.set_option("display.float_format", lambda x: f"{x:.4f}") pd.set_option("display.width", 220) for w in (0.01, 0.02, 0.03): m = rd(df2, THRESH, w) print(w, m.coef()["above"], m.se()["above"], m.pvalue()["above"]) results = []