#!/usr/bin/env python3 """Full Google Trends pull for the National Card Playing Day 2026 study. Anchor method: every batch = 4 games + cribbage (anchor), geo=US, state resolution, inc_low_vol=True. Raw CSVs are cached in data/raw/; re-running resumes. Paced (20-30 s between requests) with polite exponential backoff on 429s. """ import json, random, sys, time, datetime from pathlib import Path import pandas as pd from pytrends.request import TrendReq from pytrends.exceptions import TooManyRequestsError, ResponseError ROOT = Path(__file__).resolve().parents[1] RAW = ROOT / "data" / "raw"; RAW.mkdir(parents=True, exist_ok=True) LOG = ROOT / "data" / "pull_log.txt" KW = { "euchre":"/m/0p5ys","cribbage":"/m/03mc6sw","pinochle":"/m/066pw","spades":"/m/01g6fz", "canasta":"/m/0lytf","gin rummy":"/m/0f9yh","contract bridge":"/m/019hy","go fish":"/m/038zv", "crazy eights":"/m/015rk1","oh hell":"/m/05q4d","kings in the corner":"/m/07fq4f", "spite and malice":"/m/02gx4c","solitaire":"/m/06ycb","poker":"/m/05r1j","blackjack":"/m/019d6", "hearts":"hearts card game","sheepshead":"sheepshead card game","hand and foot":"hand and foot card game", "pitch":"pitch card game","golf":"golf card game", } ANCHOR = "cribbage" BATCHES = { "B1": ["spades","euchre","pinochle","canasta"], "B2": ["gin rummy","contract bridge","hearts","hand and foot"], "B3": ["go fish","crazy eights","golf","kings in the corner"], "B4": ["oh hell","spite and malice","sheepshead","pitch"], } WINDOWS = {"12m":"today 12-m","5y":"today 5-y"} def log(msg): line = f"{datetime.datetime.now().isoformat(timespec='seconds')} {msg}" print(line, flush=True); LOG.open("a").write(line+"\n") py = TrendReq(hl="en-US", tz=300, timeout=(10,40)) def call(fn, what): for attempt in range(6): try: r = fn(); time.sleep(random.uniform(20,30)); return r except (TooManyRequestsError, ResponseError) as e: wait = 60*(2**attempt)+random.uniform(0,15) log(f"{what}: {type(e).__name__} {str(e)[:80]} -> sleeping {wait:.0f}s (attempt {attempt+1})") time.sleep(wait) raise RuntimeError(f"gave up on {what}") def run_batch(tag, games, win, related=False): names = games + ([ANCHOR] if ANCHOR not in games else []) kws = [KW[g] for g in names] stem = f"{tag}_{win}" f_reg, f_iot = RAW/f"{stem}_by_state.csv", RAW/f"{stem}_over_time.csv" meta_f = RAW/f"{stem}_meta.json" if f_reg.exists() and f_iot.exists() and (not related or (RAW/f"{stem}_related.json").exists()): log(f"skip {stem} (cached)"); return call(lambda: py.build_payload(kws, cat=0, timeframe=WINDOWS[win], geo="US", gprop=""), f"payload {stem}") reg = call(lambda: py.interest_by_region(resolution="REGION", inc_low_vol=True, inc_geo_code=True), f"region {stem}") reg = reg.rename(columns=dict(zip(kws,names))); reg.to_csv(f_reg) iot = call(lambda: py.interest_over_time(), f"iot {stem}") iot = iot.rename(columns=dict(zip(kws,names))); iot.to_csv(f_iot) meta = {"batch":tag,"window":win,"timeframe":WINDOWS[win],"games":names,"keywords":kws, "collected_at":datetime.datetime.now().astimezone().isoformat(timespec="seconds"), "window_start":str(iot.index.min().date()) if len(iot) else None, "window_end":str(iot.index.max().date()) if len(iot) else None} json.dump(meta, open(meta_f,"w"), indent=1) log(f"done {stem}: {reg.shape}, window {meta['window_start']}..{meta['window_end']}") if related: rq = call(lambda: py.related_queries(), f"related {stem}") out = {} for kw, d in rq.items(): name = names[kws.index(kw)] if kw in kws else kw out[name] = {k:(v.to_dict(orient="records") if v is not None else None) for k,v in (d or {}).items()} json.dump(out, open(RAW/f"{stem}_related.json","w"), indent=1) log(f"related {stem} saved") if __name__ == "__main__": which = sys.argv[1] if len(sys.argv)>1 else "headline" if which == "headline": for win in WINDOWS: for tag, games in BATCHES.items(): run_batch(tag, games, win, related=(win=="12m")) elif which == "custom": # custom TAG WIN game1,game2,... tag, win, games = sys.argv[2], sys.argv[3], sys.argv[4].split(",") run_batch(tag, games, win, related=False) def run_single(game, win="12m"): """One game alone: Trends scales each state's share of all searches, 100 = the state where the game takes the biggest share. Used for 'where is this game searched most' (not for winners).""" stem=f"S_{game.replace(' ','-')}_{win}"; f=RAW/f"{stem}_by_state.csv" if f.exists(): log(f"skip {stem}"); return call(lambda: py.build_payload([KW[game]], cat=0, timeframe=WINDOWS[win], geo="US", gprop=""), f"payload {stem}") reg=call(lambda: py.interest_by_region(resolution="REGION", inc_low_vol=True, inc_geo_code=True), f"region {stem}") reg.rename(columns={KW[game]:game}).to_csv(f) json.dump({"game":game,"keyword":KW[game],"timeframe":WINDOWS[win],"collected_at":datetime.datetime.now().astimezone().isoformat(timespec="seconds")}, open(RAW/f"{stem}_meta.json","w")) log(f"done {stem}") if __name__ == "__main__" and len(sys.argv)>1 and sys.argv[1]=="singles": for g in ["euchre","cribbage","pinochle","spades","hearts","canasta","gin rummy","contract bridge","hand and foot", "oh hell","golf","kings in the corner","spite and malice","sheepshead","pitch","go fish","crazy eights"]: run_single(g)