more data

This commit is contained in:
2026-11-27 13:30:59 +01:00
parent a2fe1de359
commit 321342762c
2573 changed files with 1659852 additions and 1104 deletions
+116 -160
View File
@@ -1,177 +1,133 @@
"""
Matched stacked event study.
For each clean crossing (event_study.find_events) build a stack: the crossing game plus up to K_CTRL
look-alike games that, over the same calendar window, never change label bucket.
Controls match on: same group (sp/mp/both), genre overlap, review count, age, pre-crossing inflow,
and score within S_BAND of the cutoff on the event date.
ln(1+R) = unit FE (game within stack) + date FE (within stack) + treat x post | donut dropped
Signed: down-crossings are flipped so one coefficient = "label effect". Cluster: treated game.
Download classification, price and genres for every game in data/.
- Game ids come from the file names in data/ (e.g. data/730.csv -> app id 730).
- A row is complete when it has price AND genres. Incomplete or missing rows are (re)fetched,
so the script can be stopped and re-run, and old files without a genres column are upgraded.
- Writes game_tags.csv: sheet, group, name, categories, price, currency, genres
group = sp / mp / both / unknown (from Steam store "categories")
price = base price before discount, 0 if free, "NA" if no price listed
genres = Steam store genres joined by ";" ("none" if the store lists none)
Install: pip install requests
"""
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pyfixest as pf
import csv
import glob
import os
import time
from game_test import load, add_groups, build, DATA_GLOB, MIN_REVIEWS
from event_study import find_events, EV_WIN, EV_BIN
import requests
ALL_CUTS = [0.20, 0.40, 0.70, 0.80, 0.95] # controls must not cross ANY of these in the window
REAL_CUTS, PLACEBO_CUTS = [0.70, 0.80], [0.75, 0.85]
K_CTRL = 3 # controls per event
S_BAND = 0.03 # control score within 3 pp of the cutoff on the event date
N_TOL = np.log(2) # review count within a factor 2
AGE_TOL = 0.7 # |ln(1+age) difference|
PRE_TOL = 0.5 # |difference in mean ln(1+R), days -30..-7|
MIN_JACC = 0.34 # minimum genre overlap
MIN_COV = 0.8 # control needs lnR on 80% of window days
DONUT = 3 # drop days -3..-1 from the step estimate
REF_BIN = -3 # reference bin = days -9..-7 (not the burst days)
MIN_EVENTS = 20
DATA_GLOB = "data/*.csv"
OUT = "game_tags.csv"
API = "https://store.steampowered.com/api/appdetails"
CC = "us"
DELAY = 1.6
SAVE_EVERY = 10
FIELDS = ["sheet", "group", "name", "categories", "price", "currency", "genres"]
MP_CATS = {"multi-player", "co-op", "online co-op", "pvp", "online pvp", "mmo",
"cross-platform multiplayer"}
SP_CATS = {"single-player"}
def jacc(a, b):
return len(a & b) / len(a | b) if (a | b) else 0.0
def ids_from_files():
ids = []
for path in sorted(glob.glob(DATA_GLOB)):
stem = os.path.splitext(os.path.basename(path))[0]
if stem.isdigit():
ids.append(stem)
else:
print(f"skipping {path}: file name is not a numeric app id")
return ids
def match(ev_all, L, S, N, meta):
stacks, dropped = [], 0
for eid, e in ev_all.groupby("eid"):
e = e.sort_values("k")
s0, c = e["sheet"].iloc[0], e["cutoff"].iloc[0]
t0 = e["date"].iloc[0] - pd.Timedelta(days=int(e["k"].iloc[0]))
dates = pd.date_range(t0 - pd.Timedelta(days=EV_WIN), t0 + pd.Timedelta(days=EV_WIN - 1))
kk = np.arange(-EV_WIN, EV_WIN)
pre = (kk >= -30) & (kk <= -7)
cand = meta.index[(meta["group"] == meta.at[s0, "group"]) & (meta.index != s0)]
Lw = L.reindex(dates)[cand]
keep = Lw.notna().mean() >= MIN_COV
cand = cand[keep.to_numpy()]
Lw, Sw = Lw[cand], S.reindex(dates)[cand]
if len(cand) == 0:
dropped += 1
continue
d = pd.DataFrame(index=cand)
d["near"] = (Sw.loc[t0] - c).abs() <= S_BAND
d["dN"] = (np.log(N.loc[t0, cand].clip(lower=1)) - np.log(max(N.loc[t0, s0], 1))).abs()
d["dAge"] = (np.log1p((t0 - meta.loc[cand, "first"]).dt.days)
- np.log1p((t0 - meta.at[s0, "first"]).days)).abs()
d["dPre"] = (Lw[pre].mean() - L.reindex(dates)[s0][pre].mean()).abs()
d["jac"] = [jacc(meta.at[x, "genres"], meta.at[s0, "genres"]) for x in cand]
d = d[d["near"] & (d["dN"] <= N_TOL) & (d["dAge"] <= AGE_TOL)
& (d["dPre"] <= PRE_TOL) & (d["jac"] >= MIN_JACC) & (N.loc[t0, d.index] >= MIN_REVIEWS)]
# same label bucket for the whole window (no label change for the control)
ok = []
for x in d.index:
b = np.digitize(Sw[x].dropna().to_numpy(), ALL_CUTS)
ok.append(len(b) > 0 and b.min() == b.max())
d = d[ok]
if d.empty:
dropped += 1
continue
d["dist"] = d["dPre"] / PRE_TOL + d["dN"] / N_TOL + d["dAge"] / AGE_TOL + (1 - d["jac"])
ctrl = list(d.sort_values("dist").index[:K_CTRL])
for sheet, treat in [(s0, 1)] + [(x, 0) for x in ctrl]:
f = pd.DataFrame({"date": dates, "k": kk, "lnR": L.reindex(dates)[sheet].to_numpy()})
f["stack"], f["treat"], f["sheet"], f["tsheet"] = eid, treat, sheet, s0
f["unit"] = f"{eid}|{sheet}"
stacks.append(f)
print(f" events without a usable control: {dropped}")
return pd.concat(stacks, ignore_index=True) if stacks else pd.DataFrame()
def load_rows():
"""Existing rows keyed by sheet; columns missing in an old file load as blanks."""
if not os.path.exists(OUT):
return {}
with open(OUT, newline="", encoding="utf-8") as f:
return {row["sheet"]: {k: row.get(k) or "" for k in FIELDS} for row in csv.DictReader(f)}
def prep(st):
st = st.dropna(subset=["lnR"]).copy()
st["gid"] = pd.factorize(st["tsheet"])[0]
st["unit_i"] = pd.factorize(st["unit"])[0]
st["sk"] = pd.factorize(st["stack"] + "_" + st["k"].astype(str))[0]
st["kb"] = np.floor_divide(st["k"], EV_BIN)
return st
def save_rows(rows):
tmp = OUT + ".tmp"
with open(tmp, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS)
writer.writeheader()
writer.writerows(rows.values())
os.replace(tmp, OUT)
def estimate(st):
cl = {"CRV1": "gid"}
names = {}
for b in sorted(st["kb"].unique()):
if b == REF_BIN:
continue
nm = f"t_{'m' if b < 0 else 'p'}{abs(b)}"
st[nm] = ((st["kb"] == b) & (st["treat"] == 1)).astype(int) * st["sgn"]
names[b] = nm
m = pf.feols(f"lnR ~ {' + '.join(names.values())} | unit_i + sk", data=st, vcov=cl)
t = m.tidy()
co = [(b, float(t.loc[nm, "Estimate"]), float(t.loc[nm, "Std. Error"]))
for b, nm in names.items() if nm in t.index] + [(REF_BIN, 0.0, 0.0)]
co = pd.DataFrame(co, columns=["kb", "est", "se"]).sort_values("kb")
d = st[~st["k"].between(-DONUT, -1)].copy()
d["tp"] = ((d["k"] >= 0) & (d["treat"] == 1)).astype(int) * d["sgn"]
ms = pf.feols("lnR ~ tp | unit_i + sk", data=d, vcov=cl)
ts = ms.tidy()
step = dict(est=float(ts.loc["tp", "Estimate"]), se=float(ts.loc["tp", "Std. Error"]),
p=float(ts.loc["tp", "Pr(>|t|)"]))
return co, step
def fetch(appid):
"""Store data dict, {} if Steam has no store entry, None on a temporary failure."""
for attempt in range(5):
try:
r = requests.get(API, params={"appids": appid, "l": "english", "cc": CC}, timeout=20)
if r.status_code == 429:
time.sleep(60 * (attempt + 1))
continue
r.raise_for_status()
entry = r.json()[appid]
return entry["data"] if entry.get("success") else {}
except (requests.RequestException, ValueError, KeyError, TypeError):
time.sleep(5 * (attempt + 1))
return None
def plot(co, title, path):
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.errorbar(co["kb"] * EV_BIN, co["est"], yerr=1.96 * co["se"], fmt="o-", capsize=3)
ax.axhline(0, color="grey", lw=0.8)
ax.axvline(-0.5, color="red", ls="--", lw=0.8)
ax.set_xlabel(f"days since crossing ({EV_BIN}-day bins)")
ax.set_ylabel("treated minus matched controls (signed)")
ax.set_title(title)
fig.tight_layout()
fig.savefig(path, dpi=150)
plt.close(fig)
def classify(categories):
cats = {c.lower() for c in categories}
mp, sp = bool(cats & MP_CATS), bool(cats & SP_CATS)
if mp and sp:
return "both"
if mp:
return "mp"
if sp:
return "sp"
return "unknown"
def get_price(data):
if data.get("is_free"):
return 0, ""
po = data.get("price_overview")
if po:
return round(po["initial"] / 100, 2), po.get("currency", "")
return "NA", ""
def needs_fetch(rows, appid):
r = rows.get(appid)
return r is None or r["price"] == "" or r["genres"] == ""
def main():
ids = ids_from_files()
rows = load_rows()
todo = [i for i in ids if needs_fetch(rows, i)]
print(f"{len(ids)} games in data/, {len(ids) - len(todo)} complete, {len(todo)} to fetch "
f"(about {len(todo) * DELAY / 60:.0f} min)")
try:
for n, appid in enumerate(todo, 1):
data = fetch(appid)
if data is None:
print(f"[{n}/{len(todo)}] {appid}: request failed, will retry on next run")
continue
cats = [c["description"] for c in data.get("categories", [])]
genres = [g["description"] for g in data.get("genres", [])]
price, currency = get_price(data)
rows[appid] = {"sheet": appid, "group": classify(cats), "name": data.get("name", ""),
"categories": ";".join(cats), "price": price, "currency": currency,
"genres": ";".join(genres) or "none"}
print(f"[{n}/{len(todo)}] {appid} {data.get('name', '?')}: {rows[appid]['group']}, "
f"{price} {currency}, {rows[appid]['genres']}")
if n % SAVE_EVERY == 0:
save_rows(rows)
time.sleep(DELAY)
finally:
save_rows(rows)
if __name__ == "__main__":
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="pyfixest")
df = build(add_groups(load(DATA_GLOB)))
L = df.pivot(index="date", columns="sheet", values="lnR")
S = df.pivot(index="date", columns="sheet", values="S_lag")
N = df.pivot(index="date", columns="sheet", values="N_lag")
meta = df.groupby("sheet").agg(group=("group", "first"), first=("date", "min"),
genres=("genres", "first"))
meta["genres"] = meta["genres"].fillna("").map(lambda s: {g for g in s.split(";") if g and g != "none"})
L, S, N = L[meta.index], S[meta.index], N[meta.index]
rows = []
for kind, cuts in [("real", REAL_CUTS), ("placebo", PLACEBO_CUTS)]:
parts = []
for direction, sgn in [("up", 1), ("down", -1)]:
print(f"[{kind} {direction}] matching...")
ev = find_events(df, cuts, direction)
if ev.empty:
continue
st = match(ev, L, S, N, meta)
if st.empty:
continue
st["sgn"] = sgn
parts.append((direction, st))
for label, sts in [(d, [s]) for d, s in parts] + [("pooled", [s for _, s in parts])]:
st = prep(pd.concat(sts, ignore_index=True))
n_ev = st.loc[st["treat"] == 1, "stack"].nunique()
if n_ev < MIN_EVENTS:
print(f"[{kind} {label}] only {n_ev} matched events, skipped")
continue
co, step = estimate(st)
rows.append(dict(kind=kind, sample=label, events=n_ev,
games=st.loc[st["treat"] == 1, "tsheet"].nunique(),
ctrl_per_event=st.loc[st["treat"] == 0, "unit"].nunique() / n_ev,
pct=100 * (np.exp(step["est"]) - 1), **step))
plot(co, f"{kind} {label}: matched stacked event study, {n_ev} events",
f"matched_{kind}_{label}.png")
res = pd.DataFrame(rows)
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
pd.set_option("display.width", 200)
print(res.to_string(index=False))
res.to_csv("matched_results.csv", index=False)
main()