Repository Public Research preview
1"""r3k_06_figures.py — publication figures (figures/r3k/*.pdf + .png)."""2import json, numpy as np, pandas as pd, matplotlib3matplotlib.use("Agg"); import matplotlib.pyplot as plt4D = "data/processed_r3k"; T = "results/r3k"; F = "figures/r3k"5R = json.load(open(f"{T}/results.json")); R2 = json.load(open(f"{T}/results2.json")); RE = json.load(open(f"{T}/results_event.json"))6df = pd.read_parquet(f"{D}/analysis_panel.parquet")7BLUE, GOLD, GREY, RED = "#16365c", "#c9a227", "#8a8a8a", "#a63d40"8def save(fig, name): fig.tight_layout(); fig.savefig(f"{F}/{name}.pdf"); fig.savefig(f"{F}/{name}.png", dpi=220); plt.close(fig); print("fig", name)910# 1 quintile returns pre/post (EW, composite)11s_pre = R["subperiod_spread"]["AI_COMPOS"]["pre"]; s_post = R["subperiod_spread"]["AI_COMPOS"]["post"]12qs = {}13for per, yrs in [("Pre-ChatGPT cohorts (2010-2021)", range(2010, 2022)), ("Post-ChatGPT cohorts (2022-2024)", range(2022, 2025))]:14 d = df[df.fiscal_year.isin(list(yrs))].dropna(subset=["z_AI_COMPOS", "fwd_ret"]).copy(); d["q"] = d.groupby("fiscal_year")["z_AI_COMPOS"].transform(lambda s: pd.qcut(s, 5, labels=False) + 1)15 qs[per] = d.groupby(["fiscal_year", "q"]).fwd_ret.mean().groupby("q").mean() * 10016fig, ax = plt.subplots(figsize=(7.2, 3.4)); w = 0.38; x = np.arange(1, 6)17for i, (per, s) in enumerate(qs.items()): ax.bar(x + (i - .5) * w, s.values, w, color=[BLUE, GOLD][i], label=per)18ax.set_xticks(x); ax.set_xticklabels([f"Q{i}" for i in x]); ax.set_ylabel("Mean forward 12-month return (%)"); ax.set_xlabel("AI-composite quintile (within year)"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False)19save(fig, "fig1_quintiles")2021# 2 cumulative long-short22ts = pd.read_parquet(f"{D}/ls_ts_AI_COMPOS.parquet"); ts["date"] = pd.to_datetime(ts["date"]); ts = ts.sort_values("date")23fig, ax = plt.subplots(figsize=(7.2, 3.4)); ax.plot(ts.date, (1 + ts.ls).cumprod() - 1, color=BLUE, lw=2, label="All firms (Q5-Q1, EW)")24for g, c in [("large_top1000", GOLD), ("small_rest", GREY)]:25 t2 = pd.read_parquet(f"{D}/ls_ts_AI_COMPOS_{g}.parquet"); t2["date"] = pd.to_datetime(t2["date"]); ax.plot(t2.date, (1 + t2.ls).cumprod() - 1, color=c, lw=1.6, label={"large_top1000": "Largest 1,000 (Russell 1000 proxy)", "small_rest": "Remaining firms (Russell 2000 proxy)"}[g])26ax.axvline(pd.Timestamp("2022-11-30"), color=RED, ls="--", lw=1); ax.text(pd.Timestamp("2022-12-15"), ax.get_ylim()[1] * 0.9, "ChatGPT", color=RED, fontsize=8)27ax.set_ylabel("Cumulative long-short return"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig2_cumulative_ls")2829# 3 cohort spreads30cs = R2["cohorts"]["cohort_spreads_pct"]; yrs = [int(k) for k in cs]; vals = list(cs.values())31fig, ax = plt.subplots(figsize=(7.2, 3.2)); ax.bar(yrs, vals, color=[GOLD if y >= 2022 else BLUE for y in yrs]); ax.axhline(0, color="k", lw=.6)32ax.axhline(R2["cohorts"]["pre_mean_pct"], color=BLUE, ls=":", lw=1); ax.axhline(R2["cohorts"]["post_mean_pct"], color=GOLD, ls=":", lw=1)33ax.set_xlabel("Formation cohort (filing year)"); ax.set_ylabel("Q5-Q1 forward return (pp)"); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig3_cohort_spreads")3435# 4 AI language trend (mean composite raw signal by year, all vs large vs small)36tr = df.groupby("fiscal_year")[["ai_adoption_wmean", "ai_infrastructure_wmean"]].mean(); trl = df[df.size_group == "large"].groupby("fiscal_year")["ai_adoption_wmean"].mean(); trs = df[df.size_group == "small"].groupby("fiscal_year")["ai_adoption_wmean"].mean()37fig, ax = plt.subplots(figsize=(7.2, 3.2)); ax.plot(tr.index, tr.ai_adoption_wmean, color=BLUE, lw=2, marker="o", label="AI adoption (all firms)"); ax.plot(trl.index, trl.values, color=GOLD, lw=1.4, label="largest 1,000"); ax.plot(trs.index, trs.values, color=GREY, lw=1.4, label="remaining firms")38ax.set_xlabel("Filing year"); ax.set_ylabel("Mean section-weighted similarity"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig4_trend")3940# 5 FM by year41fm = pd.DataFrame(R2["fm_byyear"]); fig, ax = plt.subplots(figsize=(7.2, 3.2)); ax.errorbar(fm.year, fm.coef * 100, yerr=1.96 * fm.se * 100, fmt="o", color=BLUE, capsize=2); ax.axhline(0, color="k", lw=.6); ax.axvline(2021.5, color=RED, ls="--", lw=1)42ax.set_xlabel("Formation cohort"); ax.set_ylabel("Slope on AI composite (pp per SD)"); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig5_fm_byyear")4344# 6 placebo45pl = R2["placebo"]; names = list(pl); pre = [pl[n]["pre"]["mean"] * 100 for n in names]; post = [pl[n]["post"]["mean"] * 100 for n in names]46fig, ax = plt.subplots(figsize=(7.2, 3.6)); x = np.arange(len(names)); ax.bar(x - .2, pre, .4, color=BLUE, label="Pre (2010-2021)"); ax.bar(x + .2, post, .4, color=[GOLD if pl[n]["is_ai"] else GREY for n in names], label="Post (2022-2024)")47ax.set_xticks(x); ax.set_xticklabels(names, rotation=30, ha="right", fontsize=8); ax.axhline(0, color="k", lw=.6); ax.set_ylabel("Q5-Q1 spread (pp/yr)"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig6_placebo")4849# 7 event CAR paths50p = pd.read_parquet(f"{D}/event_car_paths.parquet"); fig, ax = plt.subplots(figsize=(7.2, 3.4))51for c, col in [("High", BLUE), ("Mid", GREY), ("Low", GOLD)]: ax.plot(p.index, p[c] * 100, color=col, lw=1.6, label=f"{c} pre-event AI tercile")52ax.plot(p.index, p["High_minus_Low"] * 100, color=RED, lw=2, label="High minus Low"); ax.axvline(pd.Timestamp("2022-11-30"), color="k", ls="--", lw=.8); ax.axhline(0, color="k", lw=.5)53ax.set_ylabel("Cumulative abnormal return (%)"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig7_event_car")5455# 8 double sort heatmap (post)56ds = pd.DataFrame(R2["double_sort_post"]); fig, ax = plt.subplots(figsize=(6, 3)); cols = [c for c in ds.columns if c != "Hi-Lo"]; M = ds[cols].values.astype(float)57im = ax.imshow(M, cmap="RdYlBu_r", aspect="auto"); ax.set_xticks(range(len(cols))); ax.set_xticklabels(cols); ax.set_yticks(range(len(ds.index))); ax.set_yticklabels(ds.index); ax.set_xlabel("AI-composite tercile (within size tercile)"); ax.set_ylabel("Size tercile")58for i in range(M.shape[0]):59 for j in range(M.shape[1]): ax.text(j, i, f"{M[i, j]:.1f}", ha="center", va="center", fontsize=8)60plt.colorbar(im, ax=ax, label="Mean forward return (%)"); save(fig, "fig8_double_sort")6162# 9 event-time DiD63ev = pd.DataFrame(R2["did_eventtime"]); fig, ax = plt.subplots(figsize=(7.2, 3.2)); ax.errorbar(ev.year, ev.coef * 100, yerr=1.96 * ev.se * 100, fmt="o-", color=BLUE, capsize=2); ax.axhline(0, color="k", lw=.6); ax.axvline(2021.5, color=RED, ls="--", lw=1)64ax.set_xlabel("Formation cohort (reference 2021)"); ax.set_ylabel("Premium on 2019-21 exposure (pp per SD)"); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig9_eventtime")6566# 10 filing-type signals: pre/post spreads67N = R2["filing_type"]; tags = [("10k", "10-K"), ("10q", "10-Q"), ("8k", "8-K")]; fig, ax = plt.subplots(figsize=(6.4, 3.2)); x = np.arange(3)68ax.bar(x - .2, [N[t]["pre"]["mean"] * 100 for t, _ in tags], .4, color=BLUE, label="Pre"); ax.bar(x + .2, [N[t]["post"]["mean"] * 100 for t, _ in tags], .4, color=GOLD, label="Post")69ax.set_xticks(x); ax.set_xticklabels([l for _, l in tags]); ax.axhline(0, color="k", lw=.6); ax.set_ylabel("Q5-Q1 spread (pp/yr)"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig10_filing_type")7071# 11 placebo break dates72pb = R2["placebo_breaks"]["diff_post_minus_pre_pct_by_break_year"]; fig, ax = plt.subplots(figsize=(6.4, 3)); yrs = [int(k) for k in pb]73ax.bar(yrs, list(pb.values()), color=[RED if y == 2022 else GREY for y in yrs]); ax.axhline(0, color="k", lw=.6); ax.set_xlabel("Candidate break year (first post cohort)"); ax.set_ylabel("Post minus pre mean spread (pp)"); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig11_placebo_breaks")7475# 12 size groups: pre/post spreads + sharpe76G = R["groups"]; names = ["large_top1000", "small_rest", "sp500", "non_sp500"]; labs = ["Largest 1,000", "Remaining", "S&P 500", "Non-S&P 500"]77fig, ax = plt.subplots(figsize=(6.8, 3.2)); x = np.arange(4); ax.bar(x - .2, [G[n]["pre"]["mean"] * 100 for n in names], .4, color=BLUE, label="Pre"); ax.bar(x + .2, [G[n]["post"]["mean"] * 100 for n in names], .4, color=GOLD, label="Post")78ax.set_xticks(x); ax.set_xticklabels(labs); ax.axhline(0, color="k", lw=.6); ax.set_ylabel("Q5-Q1 spread (pp/yr)"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig12_size_groups")79# 13 cohort spreads: Russell 3000 vs S&P 50080SM = R["samples"]; ya = [int(k) for k in SM["r3k"]["cohorts_pct"]]; va = list(SM["r3k"]["cohorts_pct"].values()); yb = [int(k) for k in SM["sp500"]["cohorts_pct"]]; vb = list(SM["sp500"]["cohorts_pct"].values())81fig, ax = plt.subplots(figsize=(7.2, 3.4)); ax.bar(np.array(ya) - .2, va, .4, color=BLUE, label="Russell 3000 universe"); ax.bar(np.array(yb) + .2, vb, .4, color=GOLD, label="S&P 500 members only")82ax.axhline(0, color="k", lw=.6); ax.axvline(2021.5, color=RED, ls="--", lw=1); ax.set_xlabel("Formation cohort"); ax.set_ylabel("Q5-Q1 forward return (pp)"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig13_cohorts_both")83# 14 cumulative LS: Russell 3000 vs S&P 50084fig, ax = plt.subplots(figsize=(7.2, 3.4))85for sname, c, l in [("r3k", BLUE, "Russell 3000 universe"), ("sp500", GOLD, "S&P 500 members only")]:86 t2 = pd.read_parquet(f"{D}/ls_ts_AI_COMPOS_{sname}.parquet"); t2["date"] = pd.to_datetime(t2["date"]); ax.plot(t2.date, (1 + t2.ls).cumprod() - 1, color=c, lw=2, label=l)87ax.axvline(pd.Timestamp("2022-11-30"), color=RED, ls="--", lw=1); ax.axhline(0, color="k", lw=.5); ax.set_ylabel("Cumulative long-short return"); ax.legend(frameon=False, fontsize=8); ax.spines[["top", "right"]].set_visible(False); save(fig, "fig14_cumulative_both")88print("figures done")89