"""Did the AI-exposure forecasts come true? Every number in the paper and on the site comes from here. Run: .venv/bin/python research/analysis.py (after build_dataset.py) Writes results/results.json and results/*.txt tables. Method in one paragraph: each occupation's employment growth after ChatGPT (May 2022 -> May 2025) is regressed on its AI exposure. Regressions are weighted by 2022 employment (so a job held by 3 million people counts more than one held by 3,000) and use heteroskedasticity-robust (HC1) standard errors. Exposure is standardized, so a coefficient reads "one standard deviation more exposed means this many log points of growth". The checks that matter: comparing jobs only within the same major group (fixed effects), controlling for the COVID drop, and a placebo that asks whether exposure "predicted" growth before ChatGPT existed. """ import json from pathlib import Path import numpy as np import pandas as pd import statsmodels.formula.api as smf ROOT = Path(__file__).resolve().parent.parent RES = ROOT / "results" MEASURES = {"beta_gpt4": "Predicted (GPT-4 rated, 2023)", "beta_human": "Predicted (human rated, 2023)", "observed": "Observed AI use (Anthropic, 2026)"} MAJOR = {"11": "Management", "13": "Business & finance", "15": "Computer & math", "17": "Engineering", "19": "Science", "21": "Social services", "23": "Legal", "25": "Education", "27": "Arts & media", "29": "Healthcare practitioners", "31": "Healthcare support", "33": "Protective service", "35": "Food service", "37": "Cleaning & grounds", "39": "Personal care", "41": "Sales", "43": "Office & admin", "45": "Farming", "47": "Construction", "49": "Repair", "51": "Production", "53": "Transportation"} def load(): df = pd.read_csv(ROOT / "data" / "processed" / "occupations.csv", dtype={"soc": str, "major": str}) df = df.set_index("soc") df["w"] = df.emp_2022 for m in MEASURES: # employment-weighted z-score s = df[[m, "w"]].dropna() mu = np.average(s[m], weights=s.w) sd = np.sqrt(np.average((s[m] - mu) ** 2, weights=s.w)) df[f"z_{m}"] = (df[m] - mu) / sd df["trend_break"] = df.g_post - df.g_pre return df def fit(df, formula, key, weighted=True): cols = [c for c in df.columns if c in formula.replace("C(", " ").replace(")", " ").replace("~", " ").replace("+", " ").split()] d = df.dropna(subset=cols) model = smf.wls(formula, data=d, weights=d.w if weighted else np.ones(len(d))).fit(cov_type="HC1") b, se, p = model.params[key], model.bse[key], model.pvalues[key] return {"b": round(b, 4), "se": round(se, 4), "p": round(p, 4), "lo": round(b - 1.96 * se, 4), "hi": round(b + 1.96 * se, 4), "n": int(model.nobs), "r2": round(model.rsquared, 3)} def main_table(df): """Rows: exposure measure x specification. The heart of the paper.""" specs = { "raw": "{y} ~ {x}", "major_fe": "{y} ~ {x} + C(major)", "covid_ctrl": "{y} ~ {x} + g_covid + g_pre", "both": "{y} ~ {x} + C(major) + g_covid + g_pre", } out = {} for y in ["g_post", "g_pre", "trend_break", "w_post", "w_pre"]: for m in MEASURES: for name, f in specs.items(): if y in ("g_pre", "w_pre", "trend_break") and name in ("covid_ctrl", "both"): continue # controlling for the outcome itself would be meaningless out[f"{y}|{m}|{name}"] = fit(df, f.format(y=y, x=f"z_{m}"), f"z_{m}") # Same-sample raw vs controlled, so the drop isn't just a change in which jobs are included. s = df.dropna(subset=["g_pre", "g_covid"]) for m in MEASURES: out[f"g_post|{m}|raw_same_sample"] = fit(s, f"g_post ~ z_{m}", f"z_{m}") out[f"g_post|{m}|unweighted_fe"] = fit(df, f"g_post ~ z_{m} + C(major)", f"z_{m}", weighted=False) nocomp = df[df.major != "15"] out[f"g_post|{m}|no_computer_fe"] = fit(nocomp, f"g_post ~ z_{m} + C(major)", f"z_{m}") return out def horse_race(df): """Put the prediction and the observed usage in one regression: which one carries the signal?""" out = {} for name, extra in [("raw", ""), ("major_fe", " + C(major)")]: d = df.dropna(subset=["g_post", "z_beta_gpt4", "z_observed"]) mdl = smf.wls(f"g_post ~ z_beta_gpt4 + z_observed{extra}", data=d, weights=d.w).fit(cov_type="HC1") out[name] = {k: {"b": round(mdl.params[k], 4), "se": round(mdl.bse[k], 4), "p": round(mdl.pvalues[k], 4)} for k in ["z_beta_gpt4", "z_observed"]} out[name]["n"] = int(mdl.nobs) return out def event_study(df, measure): """For each year: log employment relative to 2022, regressed on exposure within major groups. If AI drove the change, the line sits near zero before 2022 and falls after it.""" rows = [] for y in [2019, 2020, 2021, 2023, 2024, 2025]: d = df.assign(rel=np.log(df[f"emp_{y}"] / df.emp_2022)) r = fit(d, f"rel ~ z_{measure} + C(major)", f"z_{measure}") rows.append({"year": y, **r}) rows.insert(2 + 1, {"year": 2022, "b": 0.0, "se": 0.0, "lo": 0.0, "hi": 0.0, "p": 1.0}) return sorted(rows, key=lambda r: r["year"]) def quintiles(df, measure): """Plain-English view: sort jobs into five equal-count groups by exposure, add up workers.""" d = df.dropna(subset=[measure, "emp_2019", "emp_2022", "emp_2025"]).copy() d["q"] = pd.qcut(d[measure].rank(method="first"), 5, labels=False) rows = [] for q, s in d.groupby("q"): rows.append({ "quintile": int(q) + 1, "exposure_min": round(s[measure].min(), 3), "exposure_max": round(s[measure].max(), 3), "jobs": len(s), "workers_2022": int(s.emp_2022.sum()), "growth_pre": round(s.emp_2022.sum() / s.emp_2019.sum() - 1, 4), "growth_post": round(s.emp_2025.sum() / s.emp_2022.sum() - 1, 4), "examples": s.sort_values("emp_2022", ascending=False).title.head(3).tolist(), }) return rows def use_groups(df): """Observed use has a big spike at zero (no Claude use seen), so quintiles would split tied zeros arbitrarily. Instead: the zero group, then thirds of the jobs where some use was seen.""" # Same 754-job sample as the regressions. Pre-ChatGPT growth uses the jobs in each group that also have 2019 data. d = df.dropna(subset=["observed", "emp_2022", "emp_2025"]).copy() pos = d[d.observed > 0] cuts = pos.observed.quantile([1 / 3, 2 / 3]).tolist() d["grp"] = np.select([d.observed == 0, d.observed <= cuts[0], d.observed <= cuts[1]], ["none", "low", "medium"], "high") rows = [] for g in ["none", "low", "medium", "high"]: s = d[d.grp == g] p = s.dropna(subset=["emp_2019"]) rows.append({"group": g, "jobs": len(s), "workers_2022": int(s.emp_2022.sum()), "exposure_max": round(s.observed.max(), 3), "jobs_pre": len(p), "growth_pre": round(p.emp_2022.sum() / p.emp_2019.sum() - 1, 4), "growth_post": round(s.emp_2025.sum() / s.emp_2022.sum() - 1, 4), "examples": s.sort_values("emp_2022", ascending=False).title.head(4).tolist()}) return rows def tercile_index(df, measure): """The event study without regression: split each field's jobs into thirds by exposure, add up workers in each third across all fields, and index every year to May 2022 = 100.""" years = [2019, 2020, 2021, 2022, 2023, 2024, 2025] # The 754-job study sample, limited to jobs with employment in all seven years (so the lines and the # prints drawn on them on the site are the same jobs). d = df.dropna(subset=[f"emp_{y}" for y in years] + [measure, "observed"]).copy() d["r"] = d.groupby("major")[measure].rank(pct=True) groups = {"top": d[d.r > 2 / 3], "middle": d[(d.r > 1 / 3) & (d.r <= 2 / 3)], "bottom": d[d.r <= 1 / 3]} return {"years": years, "n": int(len(d)), **{k: [round(s[f"emp_{y}"].sum() / s.emp_2022.sum() * 100, 2) for y in years] for k, s in groups.items()}} def by_major(df): rows = [] for mj, s in df.dropna(subset=["emp_2019", "emp_2022", "emp_2025"]).groupby("major"): o = s.dropna(subset=["observed"]) rows.append({"major": mj, "name": MAJOR.get(mj, mj), "workers_2022": int(s.emp_2022.sum()), "observed": round(np.average(o.observed, weights=o.emp_2022), 4) if len(o) else None, "growth_pre": round(s.emp_2022.sum() / s.emp_2019.sum() - 1, 4), "growth_post": round(s.emp_2025.sum() / s.emp_2022.sum() - 1, 4)}) return rows def poster_children(df): """The most AI-exposed large jobs: what happened to them, and what was already happening.""" d = df[(df.emp_2022 >= 20000)].dropna(subset=["observed", "g_post"]) top = d.sort_values("observed", ascending=False).head(15) return [{"soc": i, "title": r.title, "observed": round(r.observed, 3), "beta_gpt4": None if pd.isna(r.beta_gpt4) else round(r.beta_gpt4, 3), "growth_pre": None if pd.isna(r.emp_2019) else round(r.emp_2022 / r.emp_2019 - 1, 4), "growth_post": round(r.emp_2025 / r.emp_2022 - 1, 4)} for i, r in top.iterrows()] def wsd(df, m): s = df[[m, "w"]].dropna() mu = np.average(s[m], weights=s.w) return float(np.sqrt(np.average((s[m] - mu) ** 2, weights=s.w))) def summary(df): main = df.dropna(subset=["g_post", "observed"]) return {"occupations": int(len(df)), "occupations_analyzed": int(len(main)), "workers_2025_all": int(df.emp_2025.sum()), "workers_2025": int(main.emp_2025.sum()), # the 754-job sample "occupations_pre": int(main.g_pre.notna().sum()), "occupations_without_data": int(len(df) - len(main)), "corr_predicted_observed": round(df[["beta_gpt4", "observed"]].corr().iloc[0, 1], 3), "sd_observed": round(wsd(df, "observed"), 3), "sd_beta_gpt4": round(wsd(df, "beta_gpt4"), 3), "share_workers_zero_observed": round(main.loc[main.observed == 0, "emp_2025"].sum() / main.emp_2025.sum(), 3)} def main(): RES.mkdir(exist_ok=True) df = load() results = { "summary": summary(df), "regressions": main_table(df), "horse_race": horse_race(df), "event_study": {m: event_study(df, m) for m in MEASURES}, "quintiles": {m: quintiles(df, m) for m in ["observed", "beta_gpt4"]}, "use_groups": use_groups(df), "tercile_index": {m: tercile_index(df, m) for m in ["beta_gpt4", "observed"]}, "by_major": by_major(df), "poster_children": poster_children(df), "measures": MEASURES, } (RES / "results.json").write_text(json.dumps(results, indent=1)) # A readable version for checking by eye. lines = [] for k, r in results["regressions"].items(): star = "***" if r["p"] < .01 else "**" if r["p"] < .05 else "*" if r["p"] < .1 else "" lines.append(f"{k:45s} b={r['b']:+.4f} ({r['se']:.4f}) p={r['p']:.3f}{star:3s} n={r['n']}") lines.append("\nHorse race: " + json.dumps(results["horse_race"], indent=1)) for m, es in results["event_study"].items(): lines.append(f"\nEvent study, {m}: " + " ".join(f"{e['year']}:{e['b']:+.3f}[{e['lo']:+.3f},{e['hi']:+.3f}]" for e in es)) (RES / "tables.txt").write_text("\n".join(lines)) print("\n".join(lines)) print(json.dumps(results["summary"], indent=1)) if __name__ == "__main__": main()