SPB Git

Repository Public Research preview

r3k_18_survivorship.py 12.8 KB 100 lines python

1"""r3k_18_survivorship.py — Stage D (FIRC-0002, package L6, cluster D: ADVE-01, EDIT-04, AI_C-05, DATA-03, ECON-07, THEO-07, THEO-06, AI_C-12).2Executable survivorship diagnostics on the current-membership universe (no new scoring of delisted firms = X1, author-side):3 (i)  point-in-time IWV constituents from the 17 dated iShares holdings captures archived by the Wayback Machine (manifest4      results/r3k_v2/iwv_holdings_manifest.json; June 2010-2018 have no capture -> unresolved_issues.md);5 (ii) attrition: share of then-constituents (by ISIN / CUSIP / ticker) absent from the 2025-08-28 holdings and from the 20266      universe.json, by size tercile (market value within the snapshot) and snapshot date; AR trigger (c') evaluated on this table;7 (iii) then-members-present cohort spreads: cohorts whose formation month has a capture within 7 months, restricted to panel firms8      that were IWV members at (or near) formation (removes later entrants);9 (iv) EW panel forward return by cohort and size group vs IWV / IWM total return over the same windows (Yahoo adjusted close =10      total return, benchmarks_monthly_v2);11 (v)  spreads on returns demeaned by size group x cohort; among below-median forward-volatility firm-years; below the cohort's12      99th return percentile;13 (vi) bounding exercise (Brown-Goetzmann-Ross logic): the Q5-Q1 difference in exit rates that would be needed to generate the14      observed spread for exit returns of -30 / -50 / -70 %, against the measured attrition rates and forward-volatility gradient.15Writes results/r3k_v2/results_surv.json, attrition_by_tercile_year.csv. Run: OMP_NUM_THREADS=4 nice -n 10 .venv-review/bin/python -I scripts/r3k_18_survivorship.py16"""17import os, sys, json, glob, time, warnings, numpy as np, pandas as pd18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); import r3k_inference as I19warnings.filterwarnings("ignore"); T0 = time.time()20V = "data/processed_r3k_v2"; R = "data/raw_russell3000"; T = "results/r3k_v2"21df = pd.read_parquet(f"{V}/analysis_panel_v2.parquet"); RES = {"script": "r3k_18_survivorship.py"}; PRE, POST, ALL = range(2010, 2022), range(2022, 2025), range(2010, 2025)22def zc(g): return (g - g.mean()) / g.std(ddof=0)23def raw(x): return x.get("raw") if isinstance(x, dict) else x24snaps = {}25for fn in sorted(glob.glob(f"{V}/iwv_holdings/IWV_holdings_asof*.json")):26    asof = os.path.basename(fn).split("asof")[1][:8]; d = json.load(open(fn, encoding="utf-8-sig"))27    rows = [{"ticker": r[0], "name": r[1], "sector": r[2], "asset": r[3], "mv": raw(r[4]), "weight": raw(r[5]), "shares": raw(r[7]), "cusip": r[8], "isin": r[9], "price": raw(r[11])} for r in d["aaData"] if len(r) > 11]28    s = pd.DataFrame(rows); s = s[(s.asset == "Equity") & pd.to_numeric(s.mv, errors="coerce").gt(0)].copy(); s["mv"] = pd.to_numeric(s.mv); s["asof"] = pd.Timestamp(asof); snaps[asof] = s29RES["snapshots"] = {k: int(len(v)) for k, v in snaps.items()}; print("snapshots", RES["snapshots"], flush=True)30# reference "current" sets: the latest capture (2025-08-28) by ISIN / CUSIP and the 2026 universe by ticker31latest = snaps[max(snaps)]; cur_isin = set(latest["isin"]) - {"-", ""}; cur_cusip = set(latest["cusip"]) - {"-", ""}32uni = json.load(open(f"{R}/universe.json")); cons = uni["constituents"]; cur_tickers = set((c.get("ticker") or "") for c in cons) if isinstance(cons, list) else set(cons.keys()); panel_tickers = set(df.ticker)33# (ii) attrition by size tercile x snapshot34att = []35for asof, s in snaps.items():36    s = s.copy(); s["present"] = s["isin"].isin(cur_isin) | s["cusip"].isin(cur_cusip) | s["ticker"].isin(cur_tickers); s["in_panel"] = s.ticker.isin(panel_tickers)37    s["terc"] = pd.qcut(s.mv.rank(method="first"), 3, labels=["small", "mid", "large"])38    for tc, g in s.groupby("terc", observed=True): att.append({"asof": asof, "tercile": tc, "n": int(len(g)), "absent_2026_share": round(float(1 - g.present.mean()), 4), "in_panel_share": round(float(g.in_panel.mean()), 4), "weight_share": round(float(g.weight.sum() / s.weight.sum()), 4)})39    att.append({"asof": asof, "tercile": "all", "n": int(len(s)), "absent_2026_share": round(float(1 - s.present.mean()), 4), "in_panel_share": round(float(s.in_panel.mean()), 4), "weight_share": 1.0})40att = pd.DataFrame(att); att.to_csv(f"{T}/attrition_by_tercile_year.csv", index=False); RES["attrition"] = att.to_dict("records")41piv = att[att.tercile != "all"].pivot(index="asof", columns="tercile", values="absent_2026_share"); RES["attrition_pivot_absent_share"] = piv.round(4).to_dict("index"); print(piv.round(3).to_string(), flush=True)42# annualised exit rate per tercile (snapshot -> 2025-08-28)43yrs_to = {a: (pd.Timestamp("2025-08-28") - pd.Timestamp(a)).days / 365.25 for a in snaps}44RES["annualised_exit_rate"] = {a: {tc: round(1 - (1 - piv.loc[a, tc]) ** (1 / yrs_to[a]), 4) for tc in piv.columns} for a in piv.index if yrs_to[a] > 0.5}45# (iii) then-members-present cohort spreads46def nearest_snap(form):47    best = min(snaps, key=lambda a: abs((pd.Timestamp(a) - form).days)); return best if abs((pd.Timestamp(best) - form).days) <= 215 else None48tm = {}49for Y in ALL:50    form = pd.Timestamp(Y + 1, 6, 30); a = nearest_snap(form)51    if a is None: continue52    s = snaps[a]; members = set(s.ticker) | set(df[df.ticker.isin(panel_tickers)].ticker[df.ticker.isin(panel_tickers) & False])53    g = df[(df.fiscal_year == Y)].copy(); g["member_then"] = g.ticker.isin(set(s.ticker)); gm = g[g.member_then]54    def sp(gg, oc):55        gg = gg.dropna(subset=["z_AI_COMPOS", oc]).copy()56        if len(gg) < 40: return None57        gg["q"] = pd.qcut(gg.z_AI_COMPOS.rank(method="first"), 5, labels=False) + 1; return float(gg[gg.q == 5][oc].mean() - gg[gg.q == 1][oc].mean())58    tm[Y] = {"snapshot": a, "n_cohort": int(len(g)), "n_member_then": int(len(gm)), "share_member_then": round(float(g.member_then.mean()), 3), "spread_all_raw": sp(g, "fwd_ret"), "spread_members_raw": sp(gm, "fwd_ret"), "spread_all_w": sp(g, "fwd_w"), "spread_members_w": sp(gm, "fwd_w"), "mean_fwd_all": round(float(g.fwd_ret.mean()), 4), "mean_fwd_members": round(float(gm.fwd_ret.mean()), 4), "mean_fwd_nonmembers": round(float(g[~g.member_then].fwd_ret.mean()), 4) if (~g.member_then).sum() > 10 else None}59RES["then_members_present"] = tm; print("then-members", {y: (v["share_member_then"], v["spread_all_w"], v["spread_members_w"]) for y, v in tm.items()}, flush=True)60# (iv) EW panel return vs IWV / IWM total return by cohort and size group61bm = pd.read_parquet(f"{V}/benchmarks_monthly_v2.parquet"); bm["date"] = pd.to_datetime(bm["date"]).dt.to_period("M").dt.to_timestamp("M"); bix = {t: g.set_index("date")["adj_close"].sort_index() for t, g in bm.groupby("ticker")}62def bret(t, Y):63    s = bix[t]; form = pd.Timestamp(Y + 1, 6, 30); end = form + pd.offsets.MonthEnd(12); p0 = s[s.index <= form]; p1 = s[s.index <= end]64    return float(p1.iloc[-1] / p0.iloc[-1] - 1) if len(p0) and len(p1) else np.nan65gap = []66for Y in ALL:67    g = df[df.fiscal_year == Y]; iwv, iwm = bret("IWV", Y), bret("IWM", Y)68    row = {"cohort": Y, "iwv": round(iwv, 4), "iwm": round(iwm, 4), "ew_all": round(float(g.fwd_ret.mean()), 4), "ew_all_w": round(float(g.fwd_w.mean()), 4), "median_all": round(float(g.fwd_ret.median()), 4)}69    for grp, m in [("large", g.size_group == "large"), ("small", g.size_group == "small"), ("sp500", g.in_sp500 == True)]: row[f"ew_{grp}"] = round(float(g[m].fwd_ret.mean()), 4) if m.sum() > 10 else None70    gap.append(row)71gap = pd.DataFrame(gap); gap.to_csv(f"{T}/ew_vs_index_by_cohort.csv", index=False)72RES["ew_vs_index"] = {"by_cohort": gap.to_dict("records"), "mean_gap_all_minus_iwv_pp": round(float((gap.ew_all - gap.iwv).mean()) * 100, 2), "mean_gap_all_w_minus_iwv_pp": round(float((gap.ew_all_w - gap.iwv).mean()) * 100, 2), "mean_gap_median_minus_iwv_pp": round(float((gap.median_all - gap.iwv).mean()) * 100, 2), "mean_gap_large_minus_iwv_pp": round(float((gap.ew_large - gap.iwv).mean()) * 100, 2), "mean_gap_small_minus_iwm_pp": round(float((gap.ew_small - gap.iwm).mean()) * 100, 2), "mean_gap_sp500_minus_iwv_pp": round(float((gap.ew_sp500 - gap.iwv).mean()) * 100, 2),73                     "mean_gap_pre_pp": round(float((gap[gap.cohort < 2022].ew_all - gap[gap.cohort < 2022].iwv).mean()) * 100, 2), "mean_gap_post_pp": round(float((gap[gap.cohort >= 2022].ew_all - gap[gap.cohort >= 2022].iwv).mean()) * 100, 2)}74print("EW - IWV gap pp:", RES["ew_vs_index"]["mean_gap_all_minus_iwv_pp"], "w", RES["ew_vs_index"]["mean_gap_all_w_minus_iwv_pp"], "large", RES["ew_vs_index"]["mean_gap_large_minus_iwv_pp"], "small-IWM", RES["ew_vs_index"]["mean_gap_small_minus_iwm_pp"], flush=True)75# (v) size-demeaned, low-volatility and below-P99 spreads76def ss(d, z, yrs, oc):77    out = {}78    for yr, g in d[d.fiscal_year.isin(list(yrs))].groupby("fiscal_year"):79        g = g.dropna(subset=[z, oc]).copy()80        if len(g) < 40: continue81        g["q"] = pd.qcut(g[z].rank(method="first"), 5, labels=False) + 1; out[int(yr)] = float(g[g.q == 5][oc].mean() - g[g.q == 1][oc].mean())82    ls = list(out.values()); mu, t = I.nw_t(ls); return {"mean": round(mu, 4) if ls else None, "t": round(t, 2) if t == t else None, "t_plain": round(I.plain_t(ls), 2) if len(ls) > 1 else None, "ci95": [round(x, 4) for x in I.ci95(ls)] if len(ls) > 1 else None, "n": len(ls), "by_cohort": {k: round(v, 4) for k, v in out.items()}}83d = df.copy(); d["fwd_dm"] = d.fwd_w - d.groupby(["fiscal_year", "size_group"])["fwd_w"].transform("mean"); d["fwd_dm_raw"] = d.fwd_ret - d.groupby(["fiscal_year", "size_group"])["fwd_ret"].transform("mean")84d["lowvol"] = d.fwd_vol <= d.groupby("fiscal_year")["fwd_vol"].transform("median"); d["below99"] = d.fwd_ret <= d.groupby("fiscal_year")["fwd_ret"].transform(lambda s: s.quantile(.99))85RES["conditional_spreads"] = {"size_demeaned_w": {"full": ss(d, "z_AI_COMPOS", ALL, "fwd_dm"), "pre": ss(d, "z_AI_COMPOS", PRE, "fwd_dm"), "post": ss(d, "z_AI_COMPOS", POST, "fwd_dm")}, "size_demeaned_raw": {"full": ss(d, "z_AI_COMPOS", ALL, "fwd_dm_raw")},86                               "low_fwd_vol_w": {"full": ss(d[d.lowvol], "z_AI_COMPOS", ALL, "fwd_w"), "pre": ss(d[d.lowvol], "z_AI_COMPOS", PRE, "fwd_w"), "post": ss(d[d.lowvol], "z_AI_COMPOS", POST, "fwd_w")}, "high_fwd_vol_w": {"full": ss(d[~d.lowvol & d.fwd_vol.notna()], "z_AI_COMPOS", ALL, "fwd_w")},87                               "below_p99_raw": {"full": ss(d[d.below99], "z_AI_COMPOS", ALL, "fwd_ret"), "pre": ss(d[d.below99], "z_AI_COMPOS", PRE, "fwd_ret"), "post": ss(d[d.below99], "z_AI_COMPOS", POST, "fwd_ret")},88                               "fwd_vol_gradient": {"full": ss(d, "z_AI_COMPOS", ALL, "fwd_vol"), "pre": ss(d, "z_AI_COMPOS", PRE, "fwd_vol"), "post": ss(d, "z_AI_COMPOS", POST, "fwd_vol")}}89print("size-demeaned w full", RES["conditional_spreads"]["size_demeaned_w"]["full"]["mean"], "| low-vol w full", RES["conditional_spreads"]["low_fwd_vol_w"]["full"]["mean"], "| below-P99 raw full", RES["conditional_spreads"]["below_p99_raw"]["full"]["mean"], flush=True)90# (vi) bounding exercise91S_obs = float(ss(df, "z_AI_COMPOS", ALL, "fwd_w")["mean"]); mean_surv = float(df.fwd_w.mean()); vol_grad = RES["conditional_spreads"]["fwd_vol_gradient"]["full"]["mean"]92small_att = {a: v.get("small") for a, v in RES["annualised_exit_rate"].items()}; large_att = {a: v.get("large") for a, v in RES["annualised_exit_rate"].items()}93RES["bounding"] = {"observed_full_spread_w": round(S_obs, 4), "mean_survivor_fwd_w": round(mean_surv, 4), "fwd_vol_gradient_Q5_minus_Q1": vol_grad, "logic": "if exiting firms earn r_x and are dropped, the survivor spread overstates the true spread by (e1 - e5) x (mean_surv - r_x) where e_q is the one-year exit rate of quintile q; the table gives the exit-rate DIFFERENCE e1 - e5 (negative = Q5 exits more) that would generate the whole observed spread, to compare with the measured annualised exit rates by size tercile (2019-2024 snapshots)",94                   "required_exit_rate_difference_e1_minus_e5": {f"r_x={rx}": round(S_obs / (mean_surv - rx), 4) for rx in (-0.3, -0.5, -0.7, -1.0)}, "measured_annualised_exit_small_tercile": small_att, "measured_annualised_exit_large_tercile": large_att,95                   "max_measured_small_minus_large_exit_rate": round(float(np.nanmax([(small_att[a] or 0) - (large_att[a] or 0) for a in small_att])), 4) if small_att else None}96print("bounding", RES["bounding"]["required_exit_rate_difference_e1_minus_e5"], "| measured small/large annualised exit", small_att, large_att, flush=True)97# entry-side diagnostic (author's companies.date_added where available) and first-price entrants, per cohort98RES["entry_side"] = {"share_entrants_by_cohort": df.assign(entrant=df.first_price > "2009-07-31").groupby("fiscal_year").entrant.mean().round(3).to_dict(), "entrant_minus_seasoned_fwd_w_pp": round(float((df[df.first_price > "2009-07-31"].fwd_w.mean() - df[df.first_price <= "2009-07-31"].fwd_w.mean()) * 100), 2)}99RES["runtime_s"] = round(time.time() - T0); json.dump(RES, open(f"{T}/results_surv.json", "w"), indent=2, default=str); print("saved results_surv.json", RES["runtime_s"], "s", flush=True)100
Files main
Menu

Theme