SPB Git

Repository Public Research preview

r3k_19_figures_v2.py 38.2 KB 183 lines python

1"""r3k_19_figures_v2.py — FIRC-0002 v2.1: every figure of the manuscript from the v2 results (results/r3k_v2/*, data/processed_r3k_v2/*),2rebuilt at Stage E (Agent 9, exhibits director, 2026-11-05) to the Part X.2 standard: one design system (Okabe–Ito palette, viridis for3the sequential heatmap, line styles + markers + hatches so every distinction survives grayscale), Times (the manuscript font), 8–9 pt4text at final size, width = \\textwidth (6.5 in) so LaTeX never rescales, vector PDF with embedded TrueType (fonttype 42), 95 %5intervals from the stated procedure, no truncated axes, no 3-D. Writes figures/r3k_v2/<name>.pdf + .png (inspection copy), copies the6PDF to paper/figures_r3k/ and writes the float wrapper paper/figures_r3k/<name>.tex (\\ExhibitFigure{label}{caption}{\\includegraphics}),7so a bare \\input{figures_r3k/<name>} places the figure with its scientific caption. Every number in a caption is read from a result8file. Run from the worktree root: .venv-review/bin/python -I scripts/r3k_19_figures_v2.py9"""10import json, os, shutil, numpy as np, pandas as pd, matplotlib11matplotlib.use("Agg"); import matplotlib.pyplot as plt; from matplotlib.patches import Patch; from matplotlib.lines import Line2D; from scipy import stats12V = "data/processed_r3k_v2"; T = "results/r3k_v2"; F = "figures/r3k_v2"; PF = "paper/figures_r3k"; SCRIPT = "scripts/r3k_19_figures_v2.py"; os.makedirs(F, exist_ok=True); os.makedirs(PF, exist_ok=True)13R = json.load(open(f"{T}/results.json")); R2 = json.load(open(f"{T}/results2.json")); RE = json.load(open(f"{T}/results_event.json")); RS = json.load(open(f"{T}/results_surv.json"))14df = pd.read_parquet(f"{V}/analysis_panel_v2.parquet")15# ---- design system: Okabe–Ito, Times, 9 pt, textwidth = 6.5 in ----16OI = {"blue": "#0072B2", "orange": "#E69F00", "green": "#009E73", "verm": "#D55E00", "sky": "#56B4E9", "purple": "#CC79A7", "yellow": "#F0E442", "black": "#000000", "grey": "#7F7F7F"}17plt.rcParams.update({"font.family": "serif", "font.serif": ["Times New Roman", "Times", "STIXGeneral", "DejaVu Serif"], "mathtext.fontset": "stix", "font.size": 9, "axes.labelsize": 9, "axes.titlesize": 9, "legend.fontsize": 8, "xtick.labelsize": 8, "ytick.labelsize": 8,18                     "pdf.fonttype": 42, "ps.fonttype": 42, "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.6, "lines.linewidth": 1.4, "legend.frameon": False, "axes.grid": False, "xtick.direction": "out", "ytick.direction": "out", "figure.dpi": 100})19W = 6.5; LAUNCH = pd.Timestamp("2022-11-30"); EXH = []20def fig_new(h, ncols=1, **kw): return plt.subplots(1, ncols, figsize=(W, h), **kw)21def save(fig, name, label, title, caption, width="\\textwidth"):22    (fig.tight_layout(pad=0.4) if fig.get_layout_engine() is None else None); fig.savefig(f"{F}/{name}.pdf"); fig.savefig(f"{F}/{name}.png", dpi=150); plt.close(fig); shutil.copy(f"{F}/{name}.pdf", f"{PF}/{name}.pdf")23    open(f"{PF}/{name}.tex", "w").write(f"% Generated by {SCRIPT} -- do not edit by hand (FIRC-0002 v2.1, Stage E exhibits). Figure file: figures/r3k_v2/{name}.pdf (copy in paper/figures_r3k/).\n% \\input{{figures_r3k/{name}}} on its own places the float with its caption; inside an existing figure wrapper only the graphic is printed.\n\\ExhibitFigure{{{label}}}{{\\textbf{{{title}}} {caption}}}{{\\includegraphics[width={width}]{{{name}.pdf}}}}\n")24    EXH.append({"kind": "figure", "file": f"figures/r3k_v2/{name}.pdf", "wrapper": f"paper/figures_r3k/{name}.tex", "label": label, "title": title, "script": SCRIPT}); print("fig", name)25def tci(x, axis=0):26    """mean and half-width of the 95 % t-interval over cohorts (rows)."""27    x = np.asarray(x, float); m = np.nanmean(x, axis=axis); nn = np.sum(~np.isnan(x), axis=axis); sd = np.nanstd(x, axis=axis, ddof=1); return m, stats.t.ppf(0.975, np.maximum(nn - 1, 1)) * sd / np.sqrt(nn)28def launch_line(ax, x=2021.5, label="ChatGPT launch (30 Nov 2022)"): ax.axvline(x, color=OI["black"], ls=":", lw=0.9, label=label)29def pp1(x): return f"{x * 100:+.1f}"30NW = R["sorts"]["AI_COMPOS_EW_w"]["n_years"]31# ================================================================ 1 quintile means pre/post with 95 % CI over cohorts (appendix) ====32fig, axes = plt.subplots(1, 2, figsize=(W, 3.2), sharey=True, layout="constrained")33for ax, oc, ttl in [(axes[0], "fwd_ret", "Raw forward return"), (axes[1], "fwd_w", "Winsorized within formation year")]:34    d = df.dropna(subset=["z_AI_COMPOS", oc]).copy(); d["q"] = d.groupby("fiscal_year")["z_AI_COMPOS"].transform(lambda s: pd.qcut(s.rank(method="first"), 5, labels=False) + 1)35    m = d.groupby(["fiscal_year", "q"])[oc].mean().unstack() * 100; x = np.arange(1, 6); w = 0.3836    for i, (per, sel, col, hatch) in enumerate([("Pre-launch cohorts 2010–2021 (n = 12)", m.index <= 2021, OI["blue"], ""), ("Post-launch cohorts 2022–2024 (n = 3)", m.index >= 2022, OI["orange"], "//")]):37        mu, hw = tci(m[sel].values); ax.bar(x + (i - .5) * w, mu, w, color=col, hatch=hatch, edgecolor="white", linewidth=0.5, label=per, yerr=hw, capsize=2, error_kw={"lw": 0.7, "ecolor": OI["black"]})38    ax.set_xticks(x); ax.set_xticklabels([f"Q{i}" for i in x]); ax.set_title(ttl); ax.set_xlabel("Quintile of the AI composite (within cohort)"); ax.axhline(0, color=OI["black"], lw=0.5)39axes[0].set_ylabel("Mean forward 12-month return (% per year)"); h_, l_ = axes[0].get_legend_handles_labels(); fig.legend(h_, l_, loc="outside upper center", ncol=2)40save(fig, "fig1_quintiles", "fig:quintiles", "Mean forward return by AI-composite quintile before and after the ChatGPT launch.",41     f"Equal-weighted mean forward twelve-month return of the within-cohort quintiles of the AI composite, averaged over the pre-launch cohorts (2010--2021) and the post-launch cohorts (2022--2024), for the raw return (left) and the return winsorized at 1/99 within the formation year (right). Error bars are 95\\% $t$-intervals over cohorts; the post-launch intervals rest on three cohorts. Russell~3000 universe, $N$ = {R['n_obs']:,} firm-years. The winsorized full-sample Q5$-$Q1 spread is {pp1(R['sorts']['AI_COMPOS_EW_w']['Q5_minus_Q1'])} pp (Table~\\ref{{tab:sortsboth}}).")42# ================================================================ 2 cumulative long-short: all, large, small (appendix) ====43fig, ax = fig_new(3.0)44for fn, col, ls, mk, l in [("", OI["blue"], "-", None, "All firms (Q5$-$Q1, equal-weighted)"), ("_large_top1000", OI["orange"], "--", "s", "Largest 1,000 (corrected capitalization)"), ("_small_rest", OI["green"], "-.", "^", "Remaining firms")]:45    ts = pd.read_parquet(f"{V}/ls_ts_v2_AI_COMPOS{fn}.parquet"); ts["date"] = pd.to_datetime(ts["date"]); ax.plot(ts.date, ((1 + ts.ls).cumprod() - 1) * 100, color=col, ls=ls, marker=mk, markevery=12, ms=3.5, label=l)46ax.axvline(LAUNCH, color=OI["black"], ls=":", lw=0.9, label="ChatGPT launch"); ax.axhline(0, color=OI["black"], lw=0.5); ax.set_ylabel("Cumulative long–short return (%)"); ax.set_xlabel("Month"); ax.legend(loc="upper left")47save(fig, "fig2_cumulative_ls", "fig:cumls", "Cumulative return of the AI-composite long--short portfolio by size group.",48     f"Cumulative return of the equal-weighted Q5$-$Q1 portfolio on the AI composite, selected every June from the cohort quintiles and held July--June, for all firms and within the two size groups (largest 1,000 firms by corrected capitalization versus the rest; quintiles formed within group). Monthly returns, splice months set to missing; {R['ls_alpha']['AI_COMPOS']['full']['n_months']} months. No uncertainty band is drawn on a cumulative path; the monthly mean, HAC $t$ and alphas are in Table~\\ref{{tab:alphaboth}}. The lines use distinct dashes and markers so that they remain distinguishable in grayscale.")49# ================================================================ 3 cohort spreads raw / wins / median (main) ====50cs = R2["cohorts"]["cohort_spreads_pct"]; cw = R2["cohorts_w"]["cohort_spreads_pct"]; cm = R2["cohorts_med"]["cohort_spreads_pct"]; yrs = np.array([int(k) for k in cs])51fig, ax = fig_new(3.1); wb = 0.2752ax.bar(yrs - wb, list(cs.values()), wb, color=OI["blue"], label="Raw return"); ax.bar(yrs, list(cw.values()), wb, color=OI["orange"], hatch="//", edgecolor="white", linewidth=0.4, label="Winsorized within year"); ax.bar(yrs + wb, list(cm.values()), wb, color=OI["green"], hatch="..", edgecolor="white", linewidth=0.4, label="Median difference")53lo, hi = R2["cohorts_w"]["pre_ci95_pct"]; ax.axhspan(lo, hi, xmin=0, xmax=(2021.5 - (yrs.min() - .6)) / (yrs.max() + .6 - (yrs.min() - .6)), color=OI["orange"], alpha=0.12, lw=0, label="95% CI of the pre-launch mean (wins.)")54ax.axhline(R2["cohorts_w"]["pre_mean_pct"], color=OI["orange"], lw=0.8, ls="--"); ax.axhline(0, color=OI["black"], lw=0.5); launch_line(ax, label="Launch (between the 2021 and 2022 cohorts)")55ax.set_xticks(yrs); ax.set_xticklabels(yrs, rotation=45); ax.set_xlim(yrs.min() - .6, yrs.max() + .6); ax.set_xlabel("Formation cohort (filing year; held July Y+1 – June Y+2)"); ax.set_ylabel("Q5$-$Q1 forward return (pp per year)"); ax.legend(loc="upper left", ncol=2)56save(fig, "fig3_cohort_spreads", "fig:cohorts", "Annual AI-composite spreads by formation cohort, Russell~3000.",57     f"Equal-weighted Q5$-$Q1 forward-return spread of the AI composite for each formation cohort, on the raw return, the return winsorized at 1/99 within the formation year, and as the median difference. The dashed line and the shaded band are the mean and the 95\\% $t$-interval of the twelve pre-launch winsorized spreads ({R2['cohorts_w']['pre_mean_pct']:+.1f} pp, [{lo:+.1f}, {hi:+.1f}]); the dotted vertical line separates the cohorts held before and after the ChatGPT launch. The post-launch cohorts are {', '.join(f'{y}: {v:+.1f}' for y, v in cw.items() if int(y) >= 2022)} pp (wins.); tests of a 2022 break are in Table~\\ref{{tab:cohorts}}.")58# ================================================================ 4 trend of AI language (main) ====59tr = df.groupby("fiscal_year")["ai_adoption_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(); tri = df.groupby("fiscal_year")["ai_infrastructure_wmean"].mean()60fig, ax = fig_new(2.9)61ax.plot(tr.index, tr.values, color=OI["blue"], marker="o", ms=4, label="AI adoption, all firms"); ax.plot(trl.index, trl.values, color=OI["orange"], ls="--", marker="s", ms=3.5, label="AI adoption, largest 1,000"); ax.plot(trs.index, trs.values, color=OI["green"], ls="-.", marker="^", ms=3.5, label="AI adoption, remaining firms"); ax.plot(tri.index, tri.values, color=OI["purple"], ls=":", marker="D", ms=3, label="AI infrastructure, all firms")62launch_line(ax, x=2022, label="Filing year of the launch (2022)"); ax.set_xlabel("Filing year"); ax.set_ylabel("Mean section-weighted cosine similarity"); ax.set_xticks(tr.index); ax.set_xticklabels(tr.index, rotation=45); ax.legend(loc="upper left", ncol=2)63save(fig, "fig4_trend", "fig:trend", "The secular rise of AI language in SEC filings.",64     f"Cross-sectional mean of the section-weighted cosine similarity of the firm-year's filing chunks to the AI-adoption anchor, for all firms in the estimation sample, the largest 1,000 firms by corrected capitalization and the remaining firms, and of the AI-infrastructure score for all firms, by filing year ({R['yrs'].replace('-', '--')}; $N$ = {R['n_obs']:,} firm-years). The series are unstandardized levels (the regressions use within-year $z$-scores), so the rise is the secular drift that the within-year standardization removes. No confidence band is drawn: with more than a thousand firms per year the standard error of the mean is smaller than the marker.")65# ================================================================ 5 Fama–MacBeth slope by cohort (main) ====66fm = pd.DataFrame(R2["fm_byyear"]); fig, ax = fig_new(2.9)67ax.errorbar(fm.year - .13, fm.coef * 100, yerr=1.96 * fm.se * 100, fmt="o", color=OI["blue"], ms=4, capsize=2, lw=0.9, label="Raw return"); ax.errorbar(fm.year + .13, fm.coef_w * 100, yerr=1.96 * fm.se_w * 100, fmt="s", color=OI["orange"], ms=4, capsize=2, lw=0.9, ls="none", label="Winsorized within year")68ax.axhline(0, color=OI["black"], lw=0.5); ax.axhline(R["fama_macbeth"]["compos_w"]["z_AI_COMPOS"]["mean_coef"] * 100, color=OI["orange"], lw=0.8, ls="--", label=f"Mean winsorized slope ({R['fama_macbeth']['compos_w']['z_AI_COMPOS']['mean_coef'] * 100:+.2f} pp/SD)"); launch_line(ax)69ax.set_xticks(fm.year); ax.set_xticklabels(fm.year, rotation=45); ax.set_xlabel("Formation cohort (filing year)"); ax.set_ylabel("Slope on the AI composite (pp per SD)"); ax.legend(loc="upper left", ncol=2)70save(fig, "fig5_fm_byyear", "fig:fmyear", "Year-by-year Fama--MacBeth slopes on the AI composite, Russell~3000.",71     f"Slope of the forward twelve-month return on the within-year standardized AI composite in each annual cross-sectional regression with size, momentum and volatility controls, for the raw and the within-year winsorized return, with 95\\% confidence intervals from heteroskedasticity-robust standard errors within the year. The dashed line is the time-series mean of the winsorized slopes ({R['fama_macbeth']['compos_w']['z_AI_COMPOS']['mean_coef'] * 100:+.2f} pp per SD, NW $t$ {R['fama_macbeth']['compos_w']['z_AI_COMPOS']['t']:.2f}; Table~\\ref{{tab:fmboth}}). Within-year intervals do not account for the cross-cohort dependence that the Newey--West and fixed-$b$ inference of the tables addresses.")72# ================================================================ 6 placebo factors (appendix, with tab_placebo) ====73pl = R2["placebo"]; names = list(pl); x = np.arange(len(names)); fig, ax = fig_new(3.3)74for i, (per, col, hatch, l) in enumerate([("pre_w", OI["blue"], "", "Pre-launch cohorts 2010–2021 (n = 12)"), ("post_w", OI["orange"], "//", "Post-launch cohorts 2022–2024 (n = 3)")]):75    mu = [pl[k][per]["mean"] * 100 for k in names]; lo_ = [pl[k][per]["mean"] * 100 - pl[k][per]["ci95"][0] * 100 for k in names]; hi_ = [pl[k][per]["ci95"][1] * 100 - pl[k][per]["mean"] * 100 for k in names]76    ax.bar(x + (i - .5) * .38, mu, .38, color=col, hatch=hatch, edgecolor="white", linewidth=0.4, label=l, yerr=[lo_, hi_], capsize=2, error_kw={"lw": 0.7, "ecolor": OI["black"]})77ax.set_xticks(x); ax.set_xticklabels([k + ("\n(AI anchor)" if pl[k]["is_ai"] else "") for k in names], rotation=30, ha="right"); ax.axhline(0, color=OI["black"], lw=0.5); ax.set_ylabel("Q5$-$Q1 spread, wins. (pp per year)"); ax.legend(loc="upper right")78save(fig, "fig6_placebo", "fig:placebo", "Placebo across eight semantic factors scored with the same pipeline.",79     "Equal-weighted Q5$-$Q1 spreads of the forward return (winsorized at 1/99 within the formation year) for the three AI anchors and five non-AI anchors scored identically, averaged over the pre- and post-launch cohorts, with 95\\% $t$-intervals over cohorts. The post-launch intervals rest on three cohorts and are correspondingly wide; the pooled interaction tests with cohort-level inference and the multiple-testing adjustment over the eight factors are in Table~\\ref{tab:placebo}.")80# ================================================================ 7 event-study CAR paths with CDA band (main) ====81p = pd.read_parquet(f"{V}/event_car_paths_v2.parquet"); p0 = p[p.pos >= -20].copy(); base = RE["by_benchmark"]["mm_2022"]["full"]["horizons"]82E1 = base["car_1y"]; sig_day = E1["HL_CAR_pct"] / (E1["t_cda"] * np.sqrt(E1["days"]))   # estimation-window daily SD of the H-L portfolio implied by the CDA t83fig, ax = fig_new(3.3)84for c_, col, ls, mk in [("High", OI["blue"], "-", "o"), ("Mid", OI["grey"], "-.", "s"), ("Low", OI["orange"], "--", "^")]: ax.plot(p0.pos, (p0[c_] - p0[c_].iloc[0]) * 100, color=col, ls=ls, marker=mk, markevery=40, ms=3.5, lw=1.2, label=f"{c_} pre-launch AI tercile")85hl = (p0["High_minus_Low"] - p0["High_minus_Low"].iloc[0]) * 100; ax.plot(p0.pos, hl, color=OI["verm"], lw=1.8, label="High minus Low")86k = np.clip(p0.pos.values, 0, None).astype(float); hl0 = hl[p0.pos == 0].iloc[0] if (p0.pos == 0).any() else 0; band = 1.96 * sig_day * np.sqrt(np.maximum(k, 0)); ax.fill_between(p0.pos, hl0 - band, hl0 + band, color=OI["verm"], alpha=0.12, lw=0, label="95% CDA band around the day-0 level")87ax.axvspan(-20, -1, color=OI["grey"], alpha=.15, lw=0, label="Pre-launch block (1–29 Nov 2022)"); ax.axvline(0, color=OI["black"], ls=":", lw=0.9); ax.axhline(0, color=OI["black"], lw=0.5)88ax.set_xlabel("Trading days relative to 1 December 2022"); ax.set_ylabel("Cumulative abnormal return (%)"); ax.legend(loc="lower left", ncol=2)89save(fig, "fig7_event_car", "fig:event", "Cumulative abnormal returns around the ChatGPT launch by pre-launch AI tercile.",90     f"Equal-weighted cumulative market-model abnormal returns of the three terciles of 2021-cohort AI exposure ({RE['n_firms']:,} firms; IWV market model estimated {RE['window']['estimation']}) and of the High$-$Low portfolio, from twenty trading days before the launch to {RE['window']['n_event_days']} days after. The shaded band is $\\pm 1.96\\,\\hat\\sigma\\sqrt{{k}}$ around the High$-$Low level on day 0, where $\\hat\\sigma$ is the estimation-window daily standard deviation of the High$-$Low portfolio implied by the CDA statistic (crude dependence adjustment; the band widens with the horizon $k$). All terciles drift negative because the model was estimated in the 2022 bear market; only differences between terciles are interpretable, and the one-year High$-$Low difference of {E1['HL_CAR_pct']:+.1f} pp (CDA $t$ {E1['t_cda']:.2f}) depends on the benchmark (Table~\\ref{{tab:eventcda}}).")91# ================================================================ 8 double-sort heatmaps pre / post (appendix) ====92fig, axes = plt.subplots(1, 2, figsize=(W, 2.9), layout="constrained")93mats = {k: pd.DataFrame(R2[k]) for k in ("double_sort_pre_w", "double_sort_post_w")}; vmin = min(m.loc[["Small", "Mid", "Large"], ["Lo", "Mid", "Hi"]].values.min() for m in mats.values()); vmax = max(m.loc[["Small", "Mid", "Large"], ["Lo", "Mid", "Hi"]].values.max() for m in mats.values())94for ax, key, ttl in zip(axes, ["double_sort_pre_w", "double_sort_post_w"], ["Pre-launch cohorts 2010–2021", "Post-launch cohorts 2022–2024"]):95    ds = mats[key]; Mx = ds.loc[["Small", "Mid", "Large"], ["Lo", "Mid", "Hi"]].values.astype(float); im = ax.imshow(Mx, cmap="viridis", vmin=vmin, vmax=vmax, aspect="auto")96    ax.set_xticks(range(3)); ax.set_xticklabels(["Low AI", "Mid", "High AI"]); ax.set_yticks(range(3)); ax.set_yticklabels(["Small", "Mid", "Large"]); ax.set_xlabel("AI-composite tercile within size tercile")97    ax.set_title(ttl + "\nHigh–Low: " + ", ".join(f"{sz.lower()} {ds.loc[sz, 'Hi-Lo']:+.1f}" for sz in ["Small", "Mid", "Large"]), fontsize=8)98    for i in range(3):99        for j in range(3): ax.text(j, i, f"{Mx[i, j]:.1f}", ha="center", va="center", fontsize=8, color="white" if Mx[i, j] < (vmin + vmax) / 2 else "black")100    for s_ in ("top", "right"): ax.spines[s_].set_visible(True)101axes[0].set_ylabel("Size tercile (corrected capitalization)"); cb = fig.colorbar(im, ax=axes, shrink=0.85, pad=0.02); cb.set_label("Mean forward return, wins. (% per year)")102save(fig, "fig8_double_sort", "fig:double", "AI language $\\times$ size double sort before and after the launch, Russell~3000.",103     "Mean forward twelve-month return (winsorized at 1/99 within the formation year, percent per year) by tercile of the AI composite within tercile of the corrected market capitalization, both formed within cohort on ranks, averaged over the pre-launch and the post-launch cohorts (viridis scale, common across panels; cell values printed; High$-$Low differences in the panel titles). The differences are descriptive; the formal large-versus-small test with clustered inference and its minimum detectable effect are in Table~\\ref{tab:contrasts}, and the post-launch cells average three cohorts.")104# ================================================================ 9 event-time profile with reference year at zero (main) ====105ev = pd.DataFrame(R2["did_eventtime"]["rows"]); et = pd.DataFrame(R2["did_eventtime_trailing"]["rows"]); ref = R2["did_eventtime"]["ref"]; fig, ax = fig_new(3.2)106ax.errorbar(ev.year - .1, ev.diff_from_ref * 100, yerr=1.96 * ev.diff_se * 100, fmt="o-", color=OI["blue"], ms=4, capsize=2, lw=1.1, label=f"Exposure = mean composite 2019–21 (committed design), difference from {ref}")107ax.errorbar(et.year + .1, et.diff_from_ref * 100, yerr=1.96 * et.diff_se * 100, fmt="s--", color=OI["orange"], ms=4, capsize=2, lw=1.1, label=f"Exposure = trailing three-year mean ending Y$-$1, difference from {ref}")108ax.axhline(0, color=OI["black"], lw=0.5); launch_line(ax, label="Launch (between the 2021 and 2022 cohorts)"); ax.axvspan(2013.5, 2018.5, color=OI["grey"], alpha=.12, lw=0, label="Look-back cohorts: outcomes precede the 2019–21 exposure")109ax.set_xticks(ev.year); ax.set_xlabel(f"Outcome cohort (reference {ref} = 0 by construction)"); ax.set_ylabel(f"Slope difference from {ref} (pp per SD)"); ax.legend(loc="upper left", fontsize=7)110save(fig, "fig9_eventtime", "fig:eventtime", "Event-time profile of the premium on pre-determined AI exposure, Russell~3000.",111     f"Coefficient on pre-determined AI exposure $\\times$ outcome-cohort dummies in a regression of the forward return (winsorized within the formation year) with the main effect of exposure included, so that each point is the difference from the {ref} reference cohort (zero by construction; the {ref} slope itself is {R2['did_eventtime']['base_slope_ref_year'] * 100:+.1f} pp per SD, $t$ {R2['did_eventtime']['base_t']:.2f}). Bars are 95\\% intervals from firm-clustered standard errors ($N$ = {R2['did_eventtime']['n']:,}). The committed v2.0 figure plotted absolute slopes from a model without the main effect, which is why it appeared flat. Shaded cohorts interact outcomes with language written afterwards (look-back selection, not a pre-trend test); the trailing-exposure variant avoids this. The pre-launch differences are not zero, so parallel trends do not hold (Table~\\ref{{tab:eventtime}}).")112# ================================================================ 10 form-specific composites (appendix) ====113Nf = R2["filing_type"]; tags = [("10k", "10-K only"), ("10q", "10-Q only"), ("8k", "8-K only"), ("formw", "Equal-form")]; x = np.arange(len(tags)); fig, ax = fig_new(2.9)114for i, (per, col, hatch, l) in enumerate([("pre_w", OI["blue"], "", "Pre-launch cohorts 2010–2021 (n = 12)"), ("post_w", OI["orange"], "//", "Post-launch cohorts 2022–2024 (n = 3)")]):115    mu = [Nf[t][per]["mean"] * 100 for t, _ in tags]; lo_ = [Nf[t][per]["mean"] * 100 - Nf[t][per]["ci95"][0] * 100 for t, _ in tags]; hi_ = [Nf[t][per]["ci95"][1] * 100 - Nf[t][per]["mean"] * 100 for t, _ in tags]116    ax.bar(x + (i - .5) * .38, mu, .38, color=col, hatch=hatch, edgecolor="white", linewidth=0.4, label=l, yerr=[lo_, hi_], capsize=2, error_kw={"lw": 0.7, "ecolor": OI["black"]})117ax.set_xticks(x); ax.set_xticklabels([l for _, l in tags]); ax.axhline(0, color=OI["black"], lw=0.5); ax.set_xlabel("Composite built from"); ax.set_ylabel("Q5$-$Q1 spread, wins. (pp per year)"); ax.legend(loc="upper left")118save(fig, "fig10_filing_type", "fig:filingtype", "Pre- and post-launch spreads of the form-specific AI composites.",119     f"Equal-weighted Q5$-$Q1 spreads (forward return winsorized within the formation year) of the composite rebuilt from one filing form at a time and of the equal-form composite, averaged over the pre- and post-launch cohorts with 95\\% $t$-intervals over cohorts. The HAC Wald test of equal Fama--MacBeth slopes across the three forms has $p$ = {Nf['fm_forms_w']['wald_equality']['p']:.3f} on winsorized and {Nf['fm_forms_raw']['wald_equality']['p']:.3f} on raw returns (Table~\\ref{{tab:filingtype}}), so the ranking of the forms is not statistically established.")120# ================================================================ 11 placebo break dates + contiguous blocks (main) ====121PBw = R2["placebo_breaks"]["winsorized"]; pb = PBw["diff_post_minus_pre_pct_by_break_year"]; cb_ = PBw["permutation"]["contiguous_blocks"]; fig, axes = fig_new(2.9, 2)122yb = [int(k_) for k_ in pb]; axes[0].bar(yb, list(pb.values()), color=[OI["verm"] if y == 2022 else OI["grey"] for y in yb], hatch=["//" if y == 2022 else "" for y in yb], edgecolor="white", linewidth=0.4); axes[0].axhline(0, color=OI["black"], lw=0.5)123axes[0].set_xlabel("Candidate break year (first post cohort)"); axes[0].set_ylabel("Post minus pre mean spread, wins. (pp)"); axes[0].set_xticks(yb); axes[0].set_xticklabels(yb, rotation=45); axes[0].set_title(f"Break candidates: 2022 ranks {PBw['rank_of_2022']} of {PBw['n_candidates']}")124yc = [int(k_) for k_ in cb_]; axes[1].bar(yc, [v * 100 for v in cb_.values()], color=[OI["verm"] if y == 2022 else OI["grey"] for y in yc], hatch=["//" if y == 2022 else "" for y in yc], edgecolor="white", linewidth=0.4); axes[1].axhline(0, color=OI["black"], lw=0.5)125axes[1].set_xlabel("Contiguous three-cohort block (first cohort)"); axes[1].set_ylabel("Block mean minus the other cohorts, wins. (pp)"); axes[1].set_xticks(yc); axes[1].set_xticklabels(yc, rotation=45); axes[1].set_title(f"Three-cohort blocks: permutation p = {PBw['permutation']['p_one_sided']:.2f}")126axes[0].legend(handles=[Patch(color=OI["verm"], hatch="//", label="2022 (actual launch)"), Patch(color=OI["grey"], label="Other candidates")], loc="upper right")127save(fig, "fig11_placebo_breaks", "fig:placebobreaks", "Placebo break dates and contiguous-block comparison, AI composite, Russell~3000.",128     f"Left: difference between the mean winsorized Q5$-$Q1 spread of the cohorts from the candidate break year onward and the mean of the earlier cohorts, for every candidate between {min(yb)} and {max(yb)}; candidates with few post cohorts have larger sampling variance, so the ranking is descriptive (bootstrap and Romano--Wolf $p$-values in Table~\\ref{{tab:mhtfullb}}). Right: mean spread of each contiguous three-cohort block minus the mean of the remaining cohorts; the 2022--24 block is exceeded by {PBw['permutation']['rank_among_contiguous'] - 1} of the 12 blocks and by a share {PBw['permutation']['p_one_sided']:.2f} of all {PBw['permutation']['n_subsets']} three-cohort subsets (exact permutation; Table~\\ref{{tab:cohorts}}).")129# ================================================================ 12 size groups pre / post with CIs (main) ====130G = R["groups"]; names = ["large_top1000", "small_rest", "sp500", "non_sp500"]; labs = ["Largest 1,000", "Remaining firms", "S&P 500 members", "Non-members"]; fig, ax = fig_new(3.1); x = np.arange(4)131for i, (per, sfx, col, hatch, l) in enumerate([("pre", "", OI["blue"], "", "Pre, raw"), ("pre", "_w", OI["sky"], "//", "Pre, wins."), ("post", "", OI["orange"], "", "Post, raw"), ("post", "_w", OI["yellow"], "//", "Post, wins.")]):132    vals = [G[n_][per + sfx]["mean"] * 100 for n_ in names]; err = [[G[n_][per + sfx]["mean"] * 100 - G[n_][per + sfx]["ci95"][0] * 100 for n_ in names], [G[n_][per + sfx]["ci95"][1] * 100 - G[n_][per + sfx]["mean"] * 100 for n_ in names]]133    ax.bar(x + (i - 1.5) * .2, vals, .2, color=col, hatch=hatch, edgecolor="white", linewidth=0.4, label=l, yerr=err, capsize=2, error_kw={"lw": .7, "ecolor": OI["black"]})134ax.set_xticks(x); ax.set_xticklabels(labs); ax.axhline(0, color=OI["black"], lw=0.5); ax.set_ylabel("Q5$-$Q1 spread (pp per year), 95% CI over cohorts"); ax.legend(loc="upper left", ncol=4)135cl = R["contrasts"]["large_vs_small_w"]["hi_x_post_x_group"]136save(fig, "fig12_size_groups", "fig:sizegroups", "Pre- and post-launch AI-composite spreads by size group and index membership.",137     f"Equal-weighted Q5$-$Q1 spreads with quintiles formed within each sub-sample and cohort, averaged over the pre-launch (2010--21, twelve cohorts) and post-launch (2022--24, three cohorts) formation cohorts, on the raw and the within-year winsorized return, with 95\\% $t$-intervals over cohorts. The post-launch intervals are wide because they rest on three cohorts; the point estimates rise for the largest 1,000 firms and the S\\&P~500 members only, but the formal large-versus-small contrast ({cl['coef_pct']:+.1f} pp, firm $t$ {cl['t_firm']:.2f}, two-way $t$ {cl['t_twoway']:.2f}, wild $p$ {cl['p_wild_webb']:.2f}, MDE {cl['mde_pct_firm']:.1f} pp; Table~\\ref{{tab:contrasts}}) is not significant and the large-cap post mean without the 2024 cohort equals its pre mean (Table~\\ref{{tab:groups}}).")138# ================================================================ 13 cohorts both universes (main) ====139SM = R["samples"]; ya = np.array([int(k_) for k_ in SM["r3k"]["cohorts_w_pct"]]); va = list(SM["r3k"]["cohorts_w_pct"].values()); yb_ = np.array([int(k_) for k_ in SM["sp500"]["cohorts_w_pct"]]); vb = list(SM["sp500"]["cohorts_w_pct"].values())140fig, ax = fig_new(3.0); ax.bar(ya - .2, va, .4, color=OI["blue"], label="Russell 3000 universe"); ax.bar(yb_ + .2, vb, .4, color=OI["orange"], hatch="//", edgecolor="white", linewidth=0.4, label="S&P 500 members only"); ax.axhline(0, color=OI["black"], lw=0.5); launch_line(ax, label="Launch (between the 2021 and 2022 cohorts)")141ax.set_xticks(ya); ax.set_xticklabels(ya, rotation=45); ax.set_xlabel("Formation cohort (filing year)"); ax.set_ylabel("Q5$-$Q1 forward return, wins. (pp)"); ax.legend(loc="upper left")142save(fig, "fig13_cohorts_both", "fig:cohortsboth", "Annual AI-composite spreads by cohort, Russell~3000 universe versus S\\&P~500 members.",143     f"Equal-weighted Q5$-$Q1 spread of the AI composite (forward return winsorized within the formation year) for each formation cohort, with quintiles formed within each universe and cohort. In both universes the 2022 cohort is negative and the post-launch average is driven by the 2024 cohort (Russell~3000 post cohorts: {', '.join(f'{y}: {v:+.1f}' for y, v in SM['r3k']['cohorts_w_pct'].items() if int(y) >= 2022)} pp; S\\&P~500: {', '.join(f'{y}: {v:+.1f}' for y, v in SM['sp500']['cohorts_w_pct'].items() if int(y) >= 2022)} pp). Cohort-level confidence intervals and the pooled member-versus-non-member test are in Tables~\\ref{{tab:prepostboth}} and \\ref{{tab:contrasts}}.")144# ================================================================ 14 cumulative LS both universes (main) ====145fig, ax = fig_new(2.9)146for sname, col, ls, mk, l in [("r3k", OI["blue"], "-", None, "Russell 3000 universe"), ("sp500", OI["orange"], "--", "s", "S&P 500 members only")]:147    t2 = pd.read_parquet(f"{V}/ls_ts_v2_AI_COMPOS_{sname}.parquet"); t2["date"] = pd.to_datetime(t2["date"]); ax.plot(t2.date, ((1 + t2.ls).cumprod() - 1) * 100, color=col, ls=ls, marker=mk, markevery=12, ms=3.5, label=l)148ax.axvline(LAUNCH, color=OI["black"], ls=":", lw=0.9, label="ChatGPT launch"); ax.axhline(0, color=OI["black"], lw=0.5); ax.set_ylabel("Cumulative long–short return (%)"); ax.set_xlabel("Month"); ax.legend(loc="upper left")149save(fig, "fig14_cumulative_both", "fig:cumboth", "Cumulative long--short return on the AI composite in the two universes.",150     f"Cumulative return of the equal-weighted, annually selected (June) Q5$-$Q1 portfolio on the AI composite, held July--June with monthly rebalancing within the year, in the Russell~3000 universe and among S\\&P~500 members ({R['samples']['r3k']['ls']['AI_COMPOS']['full']['n_months']} months). Mean returns, Sharpe ratios and factor alphas with HAC inference are in Table~\\ref{{tab:alphaboth}}; a cumulative path carries no interval.")151# ================================================================ 15 specification curve (main / fallback appendix) ====152sc = pd.read_csv(f"{T}/spec_curve.csv").sort_values("spread_pct").reset_index(drop=True); SCv = R2["spec_curve"]153se = np.where(sc.t_nw.abs() > 1e-9, (sc.spread_pct / sc.t_nw).abs(), np.nan); sig = sc.t_nw.abs() > 1.96; col = np.where(sig & (sc.spread_pct > 0), OI["blue"], np.where(sig & (sc.spread_pct < 0), OI["verm"], OI["grey"]))154fig, axes = plt.subplots(2, 1, figsize=(W, 5.0), gridspec_kw={"height_ratios": [3, 2.2]}, sharex=True)155axes[0].errorbar(sc.index, sc.spread_pct, yerr=1.96 * se, fmt="none", ecolor="#BBBBBB", elinewidth=0.3, zorder=1); axes[0].scatter(sc.index, sc.spread_pct, s=5, c=col, zorder=2, linewidths=0)156axes[0].axhline(0, color=OI["black"], lw=0.5); axes[0].axhline(SCv["median_spread_pct"], color=OI["black"], lw=0.7, ls="--"); axes[0].set_ylabel("Q5$-$Q1 spread (pp per year)")157axes[0].legend(handles=[Line2D([], [], marker="o", ls="none", color=OI["blue"], label=f"Positive and |NW t| > 1.96 ({SCv['share_positive_sig_nw'] * 100:.0f}%)"), Line2D([], [], marker="o", ls="none", color=OI["verm"], label=f"Negative and |NW t| > 1.96 ({SCv['share_negative_sig_nw'] * 100:.1f}%)"), Line2D([], [], marker="o", ls="none", color=OI["grey"], label="Not significant"), Line2D([], [], color=OI["black"], ls="--", lw=0.7, label=f"Median {SCv['median_spread_pct']:+.1f} pp")], loc="upper left", fontsize=7)158dims = [("size_filter", "Universe", ["all", "ex_top500", "large", "small"]), ("winsor", "Return treatment", ["raw", "w199", "w595", "median"]), ("weight", "Weighting", ["EW", "VW"]), ("horizon", "Horizon (months)", [6, 12, 24]), ("form", "Filing form", ["all", "10-K", "10-Q", "8-K"]), ("aggregation", "Chunk aggregation", ["wmean", "mean", "top5"])]159yl = []; yt = []; k_ = 0160for dname, dlab, levels in dims:161    for lv in levels:162        m_ = sc[dname].astype(str) == str(lv); axes[1].scatter(sc.index[m_], np.full(m_.sum(), k_), s=1.5, c=OI["grey"], linewidths=0); yl.append(f"{dlab}: {lv}"); yt.append(k_); k_ += 1163    axes[1].axhline(k_ - .5, color="#DDDDDD", lw=0.4)164axes[1].set_yticks(yt); axes[1].set_yticklabels(yl, fontsize=6); axes[1].set_xlabel(f"Specifications ranked by spread ({SCv['n_specs']:,} = 4 × 4 × 2 × 3 × 4 × 3 choices)"); axes[1].invert_yaxis()165save(fig, "fig15_spec_curve", "fig:speccurve", "Specification curve of the AI-composite spread, Russell~3000.",166     f"Top: the equal- or value-weighted Q5$-$Q1 spread of the AI composite in each of the {SCv['n_specs']:,} specifications obtained by crossing the universe (all firms, excluding the 500 largest, largest 1,000, remaining), the return treatment (raw, 1/99 or 5/95 winsorized within year, median), the weighting, the horizon, the filing form and the chunk aggregation, ranked by size; thin bars are $\\pm 1.96$ Newey--West standard errors over cohorts; {SCv['share_positive'] * 100:.0f}\\% of specifications are positive, {SCv['share_positive_sig_nw'] * 100:.0f}\\% positive with $|$NW $t| > 1.96$ ({SCv['share_positive_sig_plain'] * 100:.0f}\\% with the plain $t$), median {SCv['median_spread_pct']:+.1f} pp, interquartile range [{SCv['iqr_spread_pct'][0]:+.1f}, {SCv['iqr_spread_pct'][1]:+.1f}]. Bottom: the specification choices of each ranked estimate. Specifications are not independent (they share cohorts and firms), so the share significant is descriptive, not a test.")167# ================================================================ 16 placebo launch dates (main / fallback appendix) ====168PS = RE["placebo_summary"]; yrs_ = sorted(PS["HL_1y_by_launch_pct"]); x = np.arange(len(yrs_)); fig, axes = fig_new(2.9, 2)169axes[0].bar(x - .2, [PS["HL_1y_by_launch_pct"][y] for y in yrs_], .4, color=[OI["verm"] if y == "2022" else OI["blue"] for y in yrs_], label="Full sample"); axes[0].bar(x + .2, [PS["large_HL_1y_by_launch_pct"][y] for y in yrs_], .4, color=[OI["verm"] if y == "2022" else OI["sky"] for y in yrs_], hatch="//", edgecolor="white", linewidth=0.4, label="Largest 1,000")170axes[0].axhline(0, color=OI["black"], lw=0.5); axes[0].set_xticks(x); axes[0].set_xticklabels(yrs_, rotation=45); axes[0].set_ylabel("One-year High$-$Low CAR (pp)"); axes[0].set_xlabel("Fictitious launch on 30 November of"); axes[0].legend(handles=[Patch(color=OI["blue"], label="Full sample"), Patch(color=OI["sky"], hatch="//", label="Largest 1,000"), Patch(color=OI["verm"], label="2022 (actual launch)")], loc="upper left", fontsize=7)171axes[1].bar(x, [PS["t_cda_by_launch"][y] for y in yrs_], .5, color=[OI["verm"] if y == "2022" else OI["blue"] for y in yrs_]); axes[1].axhline(0, color=OI["black"], lw=0.5); axes[1].axhline(1.96, color=OI["black"], ls="--", lw=0.7); axes[1].axhline(-1.96, color=OI["black"], ls="--", lw=0.7); axes[1].text(-0.45, 2.04, "±1.96", fontsize=7, ha="left", va="bottom")172axes[1].set_xticks(x); axes[1].set_xticklabels(yrs_, rotation=45); axes[1].set_ylabel("CDA $t$, full sample"); axes[1].set_xlabel("Fictitious launch on 30 November of")173save(fig, "fig16_placebo_launches", "fig:placebolaunches", "Placebo launch dates: the event-study design applied to 30 November of 2015--2021.",174     f"The ChatGPT event study (IWV market model, terciles of the prior cohort's AI composite, one-year horizon) re-run with a fictitious launch on 30 November of each year 2015--2021, beside the actual 2022 launch. Left: one-year High$-$Low cumulative abnormal return for the full sample and the largest 1,000 firms; right: the dependence-robust CDA $t$ of the full-sample High$-$Low portfolio with the $\\pm 1.96$ reference lines. The 2022 launch ranks {PS['rank_2022_by_HL']} of {PS['n_launches']} by High$-$Low and {PS['rank_2022_by_t']} by $t$; the placebo $t$-statistics range over {min(PS['t_cda_by_launch'][y] for y in yrs_ if y != '2022'):.2f} to {max(PS['t_cda_by_launch'][y] for y in yrs_ if y != '2022'):.2f} (Table~\\ref{{tab:eventcda}}).")175# ================================================================ 17 attrition by tercile and snapshot (appendix) ====176AP = RS["attrition_pivot_absent_share"]; dates = sorted(AP); xs = [pd.Timestamp(d) for d in dates]; fig, ax = fig_new(2.9)177for tc, col, ls, mk, l in [("small", OI["verm"], "-", "o", "Small tercile"), ("mid", OI["orange"], "--", "s", "Mid tercile"), ("large", OI["blue"], "-.", "^", "Large tercile")]: ax.plot(xs, [AP[d][tc] * 100 for d in dates], color=col, ls=ls, marker=mk, ms=3.5, label=l)178ax.set_ylabel("Then-constituents absent in Aug. 2025 (%)"); ax.set_xlabel("Date of the IWV holdings capture (Internet Archive)"); ax.set_ylim(0, None); ax.legend(loc="upper right")179ax.annotate("no capture between 2007 and May 2019", xy=(pd.Timestamp("2013-01-01"), 6), fontsize=7, ha="center", color=OI["grey"])180save(fig, "fig17_attrition", "fig:attrition", "Attrition of IWV constituents by market-value tercile, from dated holdings captures.",181     f"Share of the constituents of each dated iShares Russell~3000 ETF holdings file ({len(dates)} Internet Archive captures, 2006 and May 2019--August 2025) that are no longer held on 28 August 2025, by market-value tercile within the capture. The small tercile's annualised exit rate is two to four times the large tercile's (Table~\\ref{{tab:attrition}}). No capture exists between 2007 and May 2019, and delisted firms have no AI scores, so attrition by AI quintile cannot be computed; the figure documents the size gradient of the survivorship that conditions the whole panel.")182json.dump(EXH, open(f"{F}/FIGURE_MAP.json", "w"), indent=1); print("figures done:", len(EXH))183
Files main
Menu

Theme