Repository Public Research preview
1"""r3k_11_t17_refit.py — Stage D (FIRC-0002, package L1, cluster C: DATA-01, ECON-04, EDIT-02, ADVE-04, AI_C-02, LITE-04, THEO-01).2Table 17 (tab_did_spid) refit on the COMMITTED analysis panel (staged read-only copy, vintage 2026-10-28, the3post-r3k_04 overwrite) with an explicit-terms formula, design-matrix rank / condition number, firm-clustered,4two-way (firm x year, Cameron-Gelbach-Miller) and HC1 standard errors, N and R2, plus a cohort(year)-FE variant.5Also re-estimates the two DiD rows of the same table (unchanged specification) so the table has one producing script.6Outputs: results/r3k_v2/t17_refit.json, paper/tables/tab_did_spid.tex (regenerated; BEFORE = git HEAD 3cf7560).7Run: OMP_NUM_THREADS=4 nice -n 10 .venv-review/bin/python -I scripts/r3k_11_t17_refit.py8"""9import json, warnings, numpy as np, pandas as pd, statsmodels.api as sm, statsmodels.formula.api as smf10from linearmodels.panel import PanelOLS11warnings.filterwarnings("ignore")12D = "data/processed_r3k"; T = "results/r3k_v2"; P = "paper/tables"13df = pd.read_parquet(f"{D}/analysis_panel.parquet")14assert "post" in df.columns and df.columns.tolist().count("post") == 1, "duplicated post column"15OUT = {"panel_vintage": "data/processed_r3k/analysis_panel.parquet (author, 2026-10-28, post-r3k_04 overwrite)", "n_panel_rows": int(len(df))}1617def cgm_cov(res, g1, g2):18 """Two-way clustered covariance (Cameron, Gelbach & Miller 2011): V_g1 + V_g2 - V_(g1 x g2), from the fitted OLS."""19 v1 = res.get_robustcov_results(cov_type="cluster", groups=g1).cov_params()20 v2 = res.get_robustcov_results(cov_type="cluster", groups=g2).cov_params()21 gg = pd.factorize(pd.Series(list(zip(g1, g2))))[0]22 v12 = res.get_robustcov_results(cov_type="cluster", groups=gg).cov_params()23 return v1 + v2 - v122425def fit(formula, d, label):26 d = d.copy(); y, X = pd.DataFrame(), None27 r = smf.ols(formula, data=d).fit()28 X = r.model.exog; rank = int(np.linalg.matrix_rank(X)); cond = float(np.linalg.cond(X))29 g_firm = pd.factorize(d["ticker"])[0]; g_year = pd.factorize(d["fiscal_year"])[0]30 se_firm = np.sqrt(np.diag(r.get_robustcov_results(cov_type="cluster", groups=g_firm).cov_params()))31 se_year = np.sqrt(np.diag(r.get_robustcov_results(cov_type="cluster", groups=g_year).cov_params()))32 se_tw = np.sqrt(np.clip(np.diag(cgm_cov(r, g_firm, g_year)), 0, None)); se_hc1 = np.sqrt(np.diag(r.get_robustcov_results(cov_type="HC1").cov_params()))33 names = r.model.exog_names; out = {"formula": formula, "n": int(r.nobs), "r2": round(float(r.rsquared), 4), "rank": rank, "k": int(X.shape[1]), "cond": round(cond, 2), "n_firms": int(d.ticker.nunique()), "n_years": int(d.fiscal_year.nunique()), "coef": {}}34 for i, v in enumerate(names):35 if v.startswith("C(fiscal_year)") or v == "Intercept": continue36 b = float(r.params.iloc[i]); out["coef"][v] = {"coef_pct": round(b * 100, 2), "t_firm": round(b / se_firm[i], 2), "t_year": round(b / se_year[i], 2), "t_twoway": round(b / se_tw[i], 2), "t_hc1": round(b / se_hc1[i], 2), "se_firm_pct": round(se_firm[i] * 100, 2)}37 print(label, "N", out["n"], "R2", out["r2"], "rank", rank, "/", out["k"], "cond", round(cond, 2)); return out3839for k, lab in [("z_SPID_TECH", "spid_tech"), ("spid_ai_any", "spid_ai_any")]:40 d2 = df.dropna(subset=["fwd_w", k, "z_AI_COMPOS", "z_size", "z_mom", "post"]).copy()41 f_base = f"fwd_w ~ {k} + post + {k}:post + z_AI_COMPOS + z_AI_COMPOS:post + z_size + z_mom"42 f_yfe = f"fwd_w ~ {k} + {k}:post + z_AI_COMPOS + z_AI_COMPOS:post + z_size + z_mom + C(fiscal_year)"43 OUT[lab] = {"base": fit(f_base, d2, lab + " base"), "year_fe": fit(f_yfe, d2, lab + " yearFE")}44 for v, c in OUT[lab]["base"]["coef"].items(): print(" ", v, c)4546# DiD rows (same specification as r3k_04 block G, re-estimated here so the table has one producing script)47exp_c = df[df.fiscal_year.isin([2019, 2020, 2021])].groupby("ticker")[["ai_adoption_wmean", "ai_infrastructure_wmean"]].mean().mean(axis=1)48dd = df.copy(); dd["pre_AI_cont"] = dd.ticker.map((exp_c - exp_c.mean()) / exp_c.std()); dd["treated"] = dd.ticker.map((exp_c > exp_c.median()).astype(float))49did = dd.dropna(subset=["fwd_w", "pre_AI_cont", "z_size", "z_mom"]).copy(); did["tp"] = did.treated * did.post; did["cp"] = did.pre_AI_cont * did.post; did = did.set_index(["ticker", "fiscal_year"])50mb = PanelOLS.from_formula("fwd_w ~ tp + z_size + z_mom + EntityEffects + TimeEffects", data=did, drop_absorbed=True).fit(cov_type="clustered", cluster_entity=True, cluster_time=True)51mc = PanelOLS.from_formula("fwd_w ~ cp + z_size + z_mom + EntityEffects + TimeEffects", data=did, drop_absorbed=True).fit(cov_type="clustered", cluster_entity=True, cluster_time=True)52OUT["did"] = {"binary": {"coef_pct": round(float(mb.params["tp"]) * 100, 2), "t_twoway": round(float(mb.tstats["tp"]), 2), "n": int(mb.nobs)}, "continuous": {"coef_pct": round(float(mc.params["cp"]) * 100, 2), "t_twoway": round(float(mc.tstats["cp"]), 2), "n": int(mc.nobs)}}53print("DiD", OUT["did"])54json.dump(OUT, open(f"{T}/t17_refit.json", "w"), indent=2)5556# ---- Table 17 (tab_did_spid.tex), regenerated with the three inference columns, N, R2, rank/cond in the notes ----57def n(x): return f"{int(x):,}".replace(",", "{,}")58body = "\\begin{tabular}{lrrrr}\n\\toprule\nSpecification & Coefficient (pp) & $t$ (firm cl.) & $t$ (firm $\\times$ year cl.) & $t$ (HC1) \\\\\n\\midrule\n"59Dd = OUT["did"]60body += f"DiD: treated (above-median 2019--21 exposure) $\\times$ post (firm + year FE) & {Dd['binary']['coef_pct']:+.2f} & & {Dd['binary']['t_twoway']:.2f} & \\\\\nDiD: continuous exposure $\\times$ post (firm + year FE) & {Dd['continuous']['coef_pct']:+.2f} & & {Dd['continuous']['t_twoway']:.2f} & \\\\\n\\midrule\n"61for lab, l in [("spid_tech", "SPID technology projects ($z$)"), ("spid_ai_any", "Any AI-initiative project (0/1)")]:62 b = OUT[lab]["base"]; k = "z_SPID_TECH" if lab == "spid_tech" else "spid_ai_any"63 for v, vl in [(k, l), (f"{k}:post", l + " $\\times$ post"), ("z_AI_COMPOS", "AI composite ($z$)"), ("z_AI_COMPOS:post", "AI composite $\\times$ post"), ("post", "Post-launch cohort (2022--24)")]:64 c = b["coef"][v]; body += f"{vl} & {c['coef_pct']:+.2f} & {c['t_firm']:.2f} & {c['t_twoway']:.2f} & {c['t_hc1']:.2f} \\\\\n"65 y = OUT[lab]["year_fe"]["coef"][f"{k}:post"]; body += f"\\quad {l.split(' (')[0]} $\\times$ post, cohort FE instead of post dummy & {y['coef_pct']:+.2f} & {y['t_firm']:.2f} & {y['t_twoway']:.2f} & {y['t_hc1']:.2f} \\\\\n"66 body += f"\\quad $N$ = {n(b['n'])} firm-years ({n(b['n_firms'])} firms, {b['n_years']} cohorts); $R^2$ = {b['r2']:.3f}; design rank {b['rank']}/{b['k']}, condition number {b['cond']:.1f} \\\\\n\\addlinespace\n"67body += "\\bottomrule\n\\end{tabular}"68open(f"{P}/tab_did_spid.tex", "w").write(body); print("table tab_did_spid.tex")69