"""Study: the 2027 health-subsidy cliff, county by county, and the account plans that ended in 2024 (PRD 5.142). Writes the study's frozen files. The rule was written down before any figure was computed, in docs/triage/cliff-study-preregistration-2026-11-13.md; this script implements it as written. Part A, the price of one dollar over the line. CMS "QHP Landscape" individual medical files for plan years 2027 and 2026 (the states that use HealthCare.gov). For each county: among distinct silver plans (standard component plan ID), the second-lowest monthly "Premium Couple 60" times its "EHB Percent of Total Premium", times 12 (one silver plan: that plan). The household is a married couple filing jointly, both 60, no children, covered all year. The price of the cliff is the premium tax credit at exactly 400% of the poverty line, which is lost one dollar above it: max(0, benchmark - round(applicable percentage x income)). Poverty lines and applicable percentages are read from src/plantrace/datafiles/cliffs.json, the same file the calculator uses. Part B, account plans that ended in plan year 2024. DOL Form 5500 "Latest" research files (F_5500, F_5500_SF, F_SCH_H, F_SCH_I) for plan year 2024. One filing per sponsor EIN, plan number and plan year, the latest received. Account plans: a pension feature code starting "2" and none starting "1". Ended: marked final, or Schedule H, Schedule I or 5500-SF says all assets were distributed. People: participants with account balances at the beginning of the year. Money: net assets at the beginning of the year. Blanks are 0. Usage: python -I tools/cliff_study.py ZIP_DIR OUT_DIR ZIP_DIR holds cms_py2027_individual_market_medical.zip, cms_py2026_individual_market_medical.zip and the four DOL zips F_5500_2024_Latest.zip, F_5500_SF_2024_Latest.zip, F_SCH_H_2024_Latest.zip, F_SCH_I_2024_Latest.zip. """ from __future__ import annotations import csv import hashlib import io import json import os import shutil import statistics import sys import zipfile from collections import defaultdict HERE = os.path.dirname(os.path.abspath(__file__)) PARAMS = os.path.join(HERE, "..", "src", "plantrace", "datafiles", "cliffs.json") CMS = {2027: "cms_py2027_individual_market_medical.zip", 2026: "cms_py2026_individual_market_medical.zip"} DOL = ("F_5500_2024_Latest.zip", "F_5500_SF_2024_Latest.zip", "F_SCH_H_2024_Latest.zip", "F_SCH_I_2024_Latest.zip") HOUSEHOLD = 2 PRICE_BARS = (10_000, 20_000, 30_000) LOOKUP_ROWS = 25 PLAN_YEAR = 2024 def sha256(path: str) -> str: h = hashlib.sha256() with open(path, "rb") as fh: for block in iter(lambda: fh.read(1 << 20), b""): h.update(block) return h.hexdigest() def money(x) -> float | None: """'$1,062.70' -> 1062.70; blank -> None.""" if x is None: return None s = str(x).replace("$", "").replace(",", "").strip() try: return float(s) if s else None except ValueError: return None def share(x) -> float | None: """'99.92%' -> 0.9992.""" if x is None: return None s = str(x).replace("%", "").strip() try: return float(s) / 100 if s else None except ValueError: return None def poverty_line(year_params: dict, region: str, size: int) -> int: first, step = year_params["fpl"][region] return first + step * (size - 1) def region_of(state: str) -> str: return state if state in ("AK", "HI") else "48" def landscape(path: str) -> dict: """County -> {state, name, silver: {plan id: annual EHB premium for the couple at 60}} from one landscape zip.""" import openpyxl zf = zipfile.ZipFile(path) name = next(n for n in zf.namelist() if n.lower().endswith(".xlsx")) tmp = os.path.join(os.path.dirname(os.path.abspath(path)), ".cliff_tmp.xlsx") with zf.open(name) as src, open(tmp, "wb") as dst: shutil.copyfileobj(src, dst) try: ws = openpyxl.load_workbook(tmp, read_only=True).worksheets[0] rows = ws.iter_rows(values_only=True) next(rows) # the filter banner head = [str(h or "").strip() for h in next(rows)] col = {h: i for i, h in enumerate(head)} need = ("State Code", "FIPS County Code", "County Name", "Metal Level", "Plan ID (Standard Component)", "EHB Percent of Total Premium", "Premium Couple 60") missing = [n for n in need if n not in col] if missing: raise SystemExit(f"{path}: missing columns {missing}") out: dict = {} for r in rows: if not r or r[col["Metal Level"]] is None or str(r[col["Metal Level"]]).strip().lower() != "silver": continue prem, ehb = money(r[col["Premium Couple 60"]]), share(r[col["EHB Percent of Total Premium"]]) if prem is None: continue fips = str(r[col["FIPS County Code"]]).strip().zfill(5) c = out.setdefault(fips, {"state": str(r[col["State Code"]]).strip(), "name": str(r[col["County Name"]]).strip(), "silver": {}}) pid = str(r[col["Plan ID (Standard Component)"]]).strip() annual = round(prem * (ehb if ehb is not None else 1.0) * 12, 2) c["silver"][pid] = min(annual, c["silver"].get(pid, annual)) return out finally: os.remove(tmp) def cliff_prices(counties: dict, year_params: dict) -> list[dict]: rows = [] for fips, c in sorted(counties.items()): prices = sorted(c["silver"].values()) bench = prices[1] if len(prices) > 1 else prices[0] line = poverty_line(year_params, region_of(c["state"]), HOUSEHOLD) income = 4 * line pct = year_params["applicable"][-1][3] # the 300-400% band is flat at its final percentage contribution = round(income * pct) rows.append({"fips": fips, "state": c["state"], "county": c["name"], "silver_plans": len(prices), "benchmark_annual": round(bench, 2), "income_at_line": income, "contribution": contribution, "cliff_price": max(0, round(bench - contribution))}) return rows def describe(rows: list[dict]) -> dict: p = [r["cliff_price"] for r in rows] return {"counties": len(p), "median": statistics.median(p), "min": min(p), "max": max(p), **{f"at_least_{b}": sum(1 for x in p if x >= b) for b in PRICE_BARS}} def csv_rows(path: str): zf = zipfile.ZipFile(path) name = next(n for n in zf.namelist() if n.lower().endswith(".csv")) rd = csv.reader(io.TextIOWrapper(zf.open(name), encoding="latin-1", newline="")) head = [h.strip().upper() for h in next(rd)] for row in rd: yield dict(zip(head, row)) def num(x) -> float: try: return float(x) if x and str(x).strip() else 0.0 except ValueError: return 0.0 def account_only(codes: str) -> bool: toks = {codes[i:i + 2] for i in range(0, len(codes or ""), 2)} return any(t.startswith("2") for t in toks) and not any(t.startswith("1") for t in toks) def yes(x) -> bool: return str(x or "").strip().upper() in ("1", "Y", "YES", "TRUE") def ended_plans(zdir: str) -> list[dict]: """Account plans whose plan year 2024 filing is final or says every asset was distributed.""" sch_h = {r["ACK_ID"]: r for r in csv_rows(os.path.join(zdir, "F_SCH_H_2024_Latest.zip"))} sch_i = {r["ACK_ID"]: r for r in csv_rows(os.path.join(zdir, "F_SCH_I_2024_Latest.zip"))} latest: dict = {} def keep(key, row): if key not in latest or (row["received"], row["ack"]) > (latest[key]["received"], latest[key]["ack"]): latest[key] = row for r in csv_rows(os.path.join(zdir, "F_5500_2024_Latest.zip")): if not (r.get("FORM_PLAN_YEAR_BEGIN_DATE") or "").startswith(str(PLAN_YEAR)): continue h, i = sch_h.get(r["ACK_ID"]), sch_i.get(r["ACK_ID"]) keep((r["SPONS_DFE_EIN"], r["SPONS_DFE_PN"]), { "ack": r["ACK_ID"], "received": r.get("DATE_RECEIVED") or "", "form": "5500", "ein": r["SPONS_DFE_EIN"], "pn": r["SPONS_DFE_PN"], "plan_name": r.get("PLAN_NAME", ""), "sponsor": r.get("SPONSOR_DFE_NAME", ""), "state": r.get("SPONS_DFE_MAIL_US_STATE", ""), "codes": r.get("TYPE_PENSION_BNFT_CODE", ""), "final": yes(r.get("FINAL_FILING_IND")), "all_distributed": yes((h or {}).get("ALL_PLAN_AST_DISTRIB_IND")) or yes((i or {}).get("SMALL_ALL_PLAN_AST_DISTRIB_IND")), "people_boy": num(r.get("PARTCP_ACCOUNT_BAL_CNT_BOY")), "assets_boy": num((h or {}).get("NET_ASSETS_BOY_AMT")) if h else num((i or {}).get("SMALL_NET_ASSETS_BOY_AMT")), "paid_out": num((h or {}).get("TOT_DISTRIB_BNFT_AMT")) if h else num((i or {}).get("SMALL_TOT_DISTRIB_BNFT_AMT")), "moved_out": num((h or {}).get("TOT_TRANSFERS_FROM_AMT")) if h else abs(num((i or {}).get("SMALL_TOT_PLAN_TRANSFERS_AMT")))}) for r in csv_rows(os.path.join(zdir, "F_5500_SF_2024_Latest.zip")): if not (r.get("SF_PLAN_YEAR_BEGIN_DATE") or "").startswith(str(PLAN_YEAR)): continue keep((r["SF_SPONS_EIN"], r["SF_PLAN_NUM"]), { "ack": r["ACK_ID"], "received": r.get("DATE_RECEIVED") or "", "form": "5500-SF", "ein": r["SF_SPONS_EIN"], "pn": r["SF_PLAN_NUM"], "plan_name": r.get("SF_PLAN_NAME", ""), "sponsor": r.get("SF_SPONSOR_NAME", ""), "state": r.get("SF_SPONS_US_STATE", ""), "codes": r.get("SF_TYPE_PENSION_BNFT_CODE", ""), "final": yes(r.get("SF_FINAL_FILING_IND")), "all_distributed": yes(r.get("SF_ALL_PLAN_AST_DISTRIB_IND")), "people_boy": num(r.get("SF_PARTCP_ACCOUNT_BAL_CNT_BOY")), "assets_boy": num(r.get("SF_NET_ASSETS_BOY_AMT")), "paid_out": num(r.get("SF_TOT_DISTRIB_BNFT_AMT")), "moved_out": abs(num(r.get("SF_TOT_PLAN_TRANSFERS_AMT")))}) return [p for p in latest.values() if account_only(p["codes"]) and (p["final"] or p["all_distributed"])] def plan_summary(plans: list[dict], room: int) -> dict: both = [p for p in plans if p["people_boy"] > 0 and p["assets_boy"] > 0] people_both = sum(p["people_boy"] for p in both) at_room = sum(p["people_boy"] for p in both if p["assets_boy"] / p["people_boy"] >= room) return {"plans": len(plans), "people": int(sum(p["people_boy"] for p in plans)), "money_usd": round(sum(p["assets_boy"] for p in plans)), "plans_with_people_and_money": len(both), "average_per_person": round(sum(p["assets_boy"] for p in both) / people_both) if people_both else None, "room_usd": room, "people_in_plans_averaging_at_least_room": int(at_room), "share_at_least_room": round(at_room / people_both, 4) if people_both else None, "by_form": {f: sum(1 for p in plans if p["form"] == f) for f in ("5500", "5500-SF")}} def paid_out_view(plans: list[dict], room: int) -> dict: """Post-hoc, labeled as such (written 2026-11-13 after the pre-registered count came back): five filings report 4,567,890 participants against under $1 a head, a placeholder, and many final filings are mergers whose people moved to another plan with no choice to make. This view drops filings averaging under $1 a person and keeps plans that paid out at least as much as they moved to other plans (Schedule H line 2e versus 2l(2), Schedule I line 2e versus 2l, 5500-SF line 8d versus 8j; Schedule I and 5500-SF report one net transfer line whose sign filers use both ways, so its size is taken): the people who were handed the money or a rollover choice.""" sane = [p for p in plans if not (p["people_boy"] > 0 and p["assets_boy"] / p["people_boy"] < 1)] paid = [p for p in sane if p["paid_out"] > 0 and p["paid_out"] >= p["moved_out"]] out = plan_summary(paid, room) out["dropped_placeholder_filings"] = len(plans) - len(sane) out["dropped_placeholder_people"] = int(sum(p["people_boy"] for p in plans) - sum(p["people_boy"] for p in sane)) out["moved_rather_than_paid_plans"] = len(sane) - len(paid) out["paid_out_usd"] = round(sum(p["paid_out"] for p in paid)) return out def main(argv: list) -> int: zdir, out = argv[1], argv[2] os.makedirs(out, exist_ok=True) params = json.load(open(PARAMS)) years = {y: cliff_prices(landscape(os.path.join(zdir, CMS[y])), params["years"][str(y)]) for y in CMS} by_fips26 = {r["fips"]: r for r in years[2026]} rows = [] for r in years[2027]: prior = by_fips26.get(r["fips"]) rows.append({**r, "cliff_price_2026": prior["cliff_price"] if prior else "", "change": r["cliff_price"] - prior["cliff_price"] if prior else ""}) with open(os.path.join(out, "counties.csv"), "w", newline="") as fh: w = csv.DictWriter(fh, fieldnames=list(rows[0])) w.writeheader() w.writerows(rows) states = defaultdict(list) for r in rows: states[r["state"]].append(r["cliff_price"]) by_state = sorted(({"state": s, "counties": len(v), "median": statistics.median(v), "max": max(v)} for s, v in states.items()), key=lambda x: (-x["median"], x["state"])) top = sorted(rows, key=lambda r: (-r["cliff_price"], r["fips"]))[:LOOKUP_ROWS] json.dump({"rows": top}, open(os.path.join(out, "lookup.json"), "w"), indent=1) both = [r for r in rows if r["cliff_price_2026"] != ""] p27 = params["years"]["2027"] room = poverty_line(p27, "48", HOUSEHOLD) # 300% to 400% of the line is one line wide plans = ended_plans(zdir) with open(os.path.join(out, "plans.csv"), "w", newline="") as fh: cols = ("ein", "pn", "plan_name", "sponsor", "state", "form", "ack", "final", "all_distributed", "people_boy", "assets_boy", "paid_out", "moved_out") w = csv.DictWriter(fh, fieldnames=cols, extrasaction="ignore") w.writeheader() for p in sorted(plans, key=lambda p: (-p["assets_boy"], p["ein"], p["pn"])): w.writerow({**p, "people_boy": int(p["people_boy"]), "assets_boy": round(p["assets_boy"]), "paid_out": round(p["paid_out"]), "moved_out": round(p["moved_out"])}) s27, s26 = describe(years[2027]), describe(years[2026]) summary = { "study": "health-subsidy-cliff-2027", "data_release": "cms-landscape-2026-10-29+dol-latest-2026-11-13", "preregistration": "docs/triage/cliff-study-preregistration-2026-11-13.md", "inputs": {f: sha256(os.path.join(zdir, f)) for f in list(CMS.values()) + list(DOL)}, "household": {"filing": "joint", "ages": [60, 60], "size": HOUSEHOLD}, "line_2027": {"poverty_line_48": poverty_line(p27, "48", HOUSEHOLD), "income_at_400": 4 * poverty_line(p27, "48", HOUSEHOLD), "applicable_pct": p27["applicable"][-1][3], "contribution_48": round(4 * poverty_line(p27, "48", HOUSEHOLD) * p27["applicable"][-1][3])}, "y2027": s27, "y2026": s26, "matched_counties": len(both), "median_change_matched": statistics.median(r["change"] for r in both) if both else None, "median_2026_matched": statistics.median(r["cliff_price_2026"] for r in both) if both else None, "median_2027_matched": statistics.median(r["cliff_price"] for r in both) if both else None, "states": len(states), "by_state": by_state, "ended_plans_2024": plan_summary(plans, room), "paid_out_2024_post_hoc": paid_out_view(plans, room), } json.dump(summary, open(os.path.join(out, "summary.json"), "w"), indent=1) shutil.copyfile(os.path.abspath(__file__), os.path.join(out, "cliff_study.py.txt")) print(json.dumps({k: summary[k] for k in ("y2027", "y2026", "median_change_matched", "states", "ended_plans_2024", "paid_out_2024_post_hoc")}, indent=1)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))