diff --git a/.github/workflows/modal-api.yml b/.github/workflows/modal-api.yml index e0de2dc..01d51d9 100644 --- a/.github/workflows/modal-api.yml +++ b/.github/workflows/modal-api.yml @@ -10,7 +10,9 @@ on: - modal-requirements.txt - aca_calc/** - src/aca_api/** + - tests/test_api_at_income.py - tests/test_api_explain.py + - tests/test_api_scenarios.py - tests/test_enhanced_ptc_reform.py - tests/test_modal_requirements.py - tests/test_smoke_test_api.py @@ -23,7 +25,9 @@ on: - modal-requirements.txt - aca_calc/** - src/aca_api/** + - tests/test_api_at_income.py - tests/test_api_explain.py + - tests/test_api_scenarios.py - tests/test_enhanced_ptc_reform.py - tests/test_modal_requirements.py - tests/test_smoke_test_api.py @@ -63,7 +67,7 @@ jobs: uv venv --python 3.11 uv pip install -r modal-requirements.txt - name: Run the API tests - run: .venv/bin/python -m pytest tests/test_api_explain.py tests/test_enhanced_ptc_reform.py tests/test_modal_requirements.py tests/test_smoke_test_api.py + run: .venv/bin/python -m pytest tests/test_api_at_income.py tests/test_api_explain.py tests/test_api_scenarios.py tests/test_enhanced_ptc_reform.py tests/test_modal_requirements.py tests/test_smoke_test_api.py deploy: name: Deploy and smoke-test diff --git a/.gitignore b/.gitignore index 06ef44e..39bed5b 100644 --- a/.gitignore +++ b/.gitignore @@ -45,8 +45,8 @@ Thumbs.db # Logs *.log -# Data/cache -data/ +# Data/cache (the root's data/ only: src/data/ holds the site's precomputed results) +/data/ .cache/ # Node.js / React diff --git a/README.md b/README.md index c813112..966bb29 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,21 @@ # ACA Premium Tax Credit Calculator -Compare 2026 Premium Tax Credits with and without Inflation Reduction Act (IRA) enhancements. +How ACA marketplace premiums change from 2026 to 2027 under current law, and what reviving the enhanced premium tax credits (H.R. 1834) would do for households. **🔗 [Try the Calculator](https://policyengine.org/us/aca-calc)** ## Overview -The Inflation Reduction Act enhanced ACA subsidies through 2025. This calculator shows what your credits would be in 2026 with and without extending these enhancements. +The American Rescue Plan Act enhanced ACA premium tax credits for 2021 and 2022, and the Inflation Reduction Act extended them through 2025. They expired after 2025, so 2026 and 2027 coverage follows the original ACA schedule. H.R. 1834, which passed the House on January 8, 2026 and has not been enacted, would revive them for 2026 through 2028. + +The app has three pages: +- **Overview**: how benchmark premiums rise in 2027, who pays the increase under current law, and what H.R. 1834 would mean for four example households. +- **Calculator**: what a household would pay for its benchmark plan, and its credit, in 2026 and 2027 under current law and in 2027 under H.R. 1834. +- **Methodology**: the model and data, the policies compared, and the limitations. **Key Differences:** -- **With IRA Extension**: No income cap, lower premium contributions (0-8.5% of income) -- **After IRA Expires**: 400% FPL cap ("subsidy cliff"), higher contributions (2-9.5% of income) +- **Enhanced credits (2021–2025)**: No income cap; required contributions from 0% to 8.5% of income +- **Current law (2026 on)**: No credit above 400% FPL (the "subsidy cliff"); required contributions from about 2% to 10% of income, set each year by the IRS ## Quick Start @@ -36,19 +41,10 @@ uv run --with fastapi --with uvicorn uvicorn src.aca_api.api:app --port 5001 - ✅ **All 50 States + DC**: Accurate calculations for every jurisdiction - ✅ **3,143 Counties**: County-specific marketplace pricing -- ✅ **Real-time Comparison**: Side-by-side baseline vs. IRA extension +- ✅ **Real-time Comparison**: 2026 and 2027 current law against H.R. 1834 - ✅ **Interactive Charts**: See how credits change across income levels - ✅ **Household Flexibility**: Single, married, with/without dependents -## Example Results - -| Scenario | Income | Baseline PTC | With IRA | Savings | -|----------|--------|--------------|----------|---------| -| NJ Family of 3 | $50,000 | $8,515 | $10,626 | $2,111/year | -| TX Couple (Travis) | $60,000 | $6,974 | $9,195 | $2,221/year | -| CA Couple + Child | $75,000 | $12,913 | $15,695 | $2,782/year | -| NY Single @ 400% FPL | $62,280 | $0 | $2,899 | $2,899/year | - ## Technical Details Built with: @@ -64,14 +60,14 @@ County data sourced from PolicyEngine's ACA rating areas database. . ├── app/ # Next.js entry (layout and page) ├── src/ -│ ├── App.jsx # The Overview, Explore Households and Calculator pages +│ ├── App.jsx # The Overview and Calculator pages │ ├── components/ # Charts, tables and the calculator -│ ├── data/households/ # Precomputed results the Overview and Explore pages read +│ ├── data/ # Precomputed results the Overview reads │ └── aca_api/ # The FastAPI backend (api.py, models.py) ├── aca_calc/calculations/ # The household builder and the scenarios' reforms ├── modal_app.py # The API's Modal deployment ├── modal-requirements.txt # The API image's exact package versions -├── precompute_*.py # Regenerate the precomputed household results +├── precompute_*.py # Regenerate the precomputed results (see below) ├── scripts/ # The post-deploy smoke test ├── counties.json # County lists for the calculator form ├── process_counties.py # Regenerates counties.json @@ -82,7 +78,7 @@ County data sourced from PolicyEngine's ACA rating areas database. ## Development The optional `/api/explain` endpoint uses `claude-sonnet-5-5` with low effort -and requires `ANTHROPIC_API_KEY`. Run its regression tests without provider +and requires `ANTHROPIC_API_KEY`. The calculator page doesn't call it. Run its regression tests without provider credentials or network calls (FastAPI is installed separately in deployment): ```bash @@ -98,6 +94,20 @@ make test python process_counties.py ``` +## Precomputed results + +The Overview reads results computed ahead of time with the API's pinned +policyengine-us. Rerun the scripts after every pin: + +- `precompute_contribution_schedules.py`: the share of income each schedule + charges for the benchmark plan +- `precompute_cliff_household.py`: the Pennsylvania example across incomes +- `precompute_households.py`: four example households at one income each +- `precompute_national.py`: the national effects of H.R. 1834 in 2027, over + policyengine-us's default microdata. It needs about 32 GB of memory, so run + it on Modal or another large machine. The Overview doesn't show these + figures until they are validated against administrative data. + ## Deploying the API The calculator page calls a FastAPI backend on Modal: app `aca-calc-api` in @@ -106,7 +116,8 @@ the `main` environment of PolicyEngine's Modal workspace, defined in runs the API tests against the image's pinned packages on pull requests that touch the backend. When such a change merges to `main`, it deploys the app and smoke-tests `/api/health`, both calculator endpoints (`/api/calculate-stream`, -which the page calls, and `/api/calculate`, its fallback) and `/api/explain`. +which the page calls, and `/api/calculate`, its fallback), `/api/calculate-at-income` +(the "Your household" tab's answer at the earnings entered) and `/api/explain`. The calculator checks set `skip_cache`, which makes both endpoints compute a new answer without reading or writing the 7-day cache, and the stream check confirms that the new code computed its answer. Modal can keep sending diff --git a/aca_calc/calculations/household.py b/aca_calc/calculations/household.py index 6abf224..16950b2 100644 --- a/aca_calc/calculations/household.py +++ b/aca_calc/calculations/household.py @@ -34,7 +34,14 @@ def build_household_situation( "spm_units": {"your household": {"members": ["you"]}}, "tax_units": {"your tax unit": {"members": ["you"]}}, "households": { - "your household": {"members": ["you"], "state_name": {year: state}} + "your household": { + "members": ["you"], + # The credit measures income against the prior year's poverty + # guideline (aca_magi_fraction), so the state is set for that + # year too. Without it, Alaska and Hawaii households get the + # 48 states' lower guideline. + "state_name": {year - 1: state, year: state}, + } }, } diff --git a/aca_calc/calculations/reforms.py b/aca_calc/calculations/reforms.py index 945ba26..78f6bc2 100644 --- a/aca_calc/calculations/reforms.py +++ b/aca_calc/calculations/reforms.py @@ -14,32 +14,41 @@ ENHANCED_INITIAL = [0, 0, 0.02, 0.04, 0.06] ENHANCED_FINAL = [0, 0.02, 0.04, 0.06, 0.085] -ENHANCED_PERIOD = "2026-01-01.2100-12-31" +# H.R. 1834 revives the enhanced schedule for 2026 through 2028. +ENHANCED_PERIOD = "2026-01-01.2028-12-31" + + +def _enhanced_schedule() -> dict: + """The enhanced schedule as policyengine-us parameter overrides. + + The three lists are replaced together: the threshold list has one more + entry than the rate lists, and current law's lists have a 133% FPL + threshold the enhanced schedule doesn't. + """ + return { + "gov.aca.required_contribution_percentage.threshold": {ENHANCED_PERIOD: ENHANCED_THRESHOLDS}, + "gov.aca.required_contribution_percentage.initial": {ENHANCED_PERIOD: ENHANCED_INITIAL}, + "gov.aca.required_contribution_percentage.final": {ENHANCED_PERIOD: ENHANCED_FINAL}, + } + + +# gov.aca.ptc_income_eligibility's third bracket starts at 400% FPL; from 2026 +# it makes incomes there ineligible. +NO_INCOME_CAP = {"gov.aca.ptc_income_eligibility[2].amount": {ENHANCED_PERIOD: True}} def create_enhanced_ptc_reform(): - """Create reform extending enhanced PTCs (IRA extension) from 2026 on. + """H.R. 1834: revive the enhanced premium tax credits for 2026-2028. Restores the ARPA/IRA applicable-percentage schedule and removes the 400% FPL eligibility limit, so households above 400% FPL pay at most 8.5% of - income for the benchmark plan. - - The three schedule lists are replaced together: the threshold list has one - more entry than the rate lists, and the 2026 law's lists have a 133% FPL - threshold the enhanced schedule doesn't. + income for the benchmark plan. H.R. 1834 passed the House on January 8, + 2026; it has not been enacted. Returns: Reform: PolicyEngine reform object """ - return Reform.from_dict( - { - "gov.aca.required_contribution_percentage.threshold": {ENHANCED_PERIOD: ENHANCED_THRESHOLDS}, - "gov.aca.required_contribution_percentage.initial": {ENHANCED_PERIOD: ENHANCED_INITIAL}, - "gov.aca.required_contribution_percentage.final": {ENHANCED_PERIOD: ENHANCED_FINAL}, - "gov.aca.ptc_income_eligibility[2].amount": {ENHANCED_PERIOD: True}, - }, - country_id="us", - ) + return Reform.from_dict({**_enhanced_schedule(), **NO_INCOME_CAP}, country_id="us") def _contrib_reform(module: str, name: str): @@ -57,6 +66,9 @@ def _contrib_reform(module: str, name: str): def create_700fpl_reform(): """Create 700% FPL extension reform (Bipartisan Health Insurance Affordability Act). + Introduced by Reps. Dunn (R-FL) and Schneider (D-IL) on December 9, 2025; + not enacted. + This implements the proposed bill's schedule: - 200-250% FPL: 2% to 4% - 250-300% FPL: 4% to 6% diff --git a/changelog.d/aca-2027-backend.added.md b/changelog.d/aca-2027-backend.added.md new file mode 100644 index 0000000..9e90e62 --- /dev/null +++ b/changelog.d/aca-2027-backend.added.md @@ -0,0 +1 @@ +Model 2027 coverage in the calculator API (requests without a year still get 2026), with H.R. 1834, and return 2026 current law for the same household and incomes alongside 2027 when asked (show_prior_year). Report the benchmark premium at each income. Pin policyengine-us 2.138.2, which has the published 2027 premiums and counts the used premium tax credit in household net income, and give the Modal function 4 GB. diff --git a/changelog.d/aca-2027-backend.fixed.md b/changelog.d/aca-2027-backend.fixed.md new file mode 100644 index 0000000..d86c02c --- /dev/null +++ b/changelog.d/aca-2027-backend.fixed.md @@ -0,0 +1 @@ +Draw the FPL lines from the prior year's poverty guideline, which the credit uses, and give Alaska and Hawaii households their own guideline for the credit instead of the 48 states'. diff --git a/changelog.d/aca-2027-calculator.added.md b/changelog.d/aca-2027-calculator.added.md new file mode 100644 index 0000000..95a1654 --- /dev/null +++ b/changelog.d/aca-2027-calculator.added.md @@ -0,0 +1 @@ +Compare 2027 coverage with 2026 under current law in the calculator, and, with a checkbox, 2027 under H.R. 1834: what the household pays for the benchmark plan after the credit, the credit itself, and both at an income the user enters. The calculator reads top to bottom: the Overview's four example households, whose results are stored (precompute_calculator_examples.py) and appear without a request, then the household form, then the results. diff --git a/changelog.d/aca-2027-calculator.removed.md b/changelog.d/aca-2027-calculator.removed.md new file mode 100644 index 0000000..32e3269 --- /dev/null +++ b/changelog.d/aca-2027-calculator.removed.md @@ -0,0 +1 @@ +Drop the year setting and the other scenarios (the 700% FPL bill and CRFB's two bracket options) from the calculator page; old links still load their household. diff --git a/changelog.d/aca-2027-overview.changed.md b/changelog.d/aca-2027-overview.changed.md new file mode 100644 index 0000000..02fcab8 --- /dev/null +++ b/changelog.d/aca-2027-overview.changed.md @@ -0,0 +1 @@ +Retell the Overview around 2027 premiums, in the earlier version's order: how the credits work, including that households below 100% FPL get none (and that in most non-expansion states an adult without children below that line falls in the coverage gap, qualifying for neither Medicaid nor a credit), their 2021–2025 enhancements and expiry; a Texas adult below 400% FPL and a Pennsylvania adult above it as benchmark premiums rise from 2026 to 2027, the credit absorbing the increase for the first while the second pays all of it; what reviving the enhanced credits (H.R. 1834) would do for it, with a table that adds a column at each step; and four example households, from precomputed policyengine-us results. A new section charts the Pennsylvania example's marginal tax rate across incomes, with current law's cliff at 400% FPL and H.R. 1834's 8.5% phase-out (precompute_cliff_household.py now saves household net income and marginal rates). On wide screens the Overview pins the active section's chart on the left while its text scrolls past in cards on the right, as the earlier version did; on narrower screens it is one column, with each chart under its text. The app uses PolicyEngine's colors and type throughout. The Overview labels its lines directly (with a legend where they run too close), fades its charts in as they scroll into view, and marks the hovered income on each chart. A data check (scripts/check_data.mjs) runs before every build and fails it if the precomputed files disagree. A Methodology tab, beside the Overview and the Calculator, covers the model and data, the policies compared and the limitations; the Overview's methods section moves there, and the Overview ends with buttons to the calculator and to the Methodology tab. The pages sit on a tinted background with raised white cards, pill-shaped tabs and a white header aligned with the Overview's left edge; part headings are pills, section titles are teal, buttons lift on hover, and the calculator's example households show whether their state expanded Medicaid. The calculator's share button moves under the results as "Share results": its link, which the address bar also shows, carries the comparison, the open tab and the income entered as well as the household, and opening it calculates the household and opens the same view. diff --git a/changelog.d/aca-2027-overview.fixed.md b/changelog.d/aca-2027-overview.fixed.md new file mode 100644 index 0000000..eb137bc --- /dev/null +++ b/changelog.d/aca-2027-overview.fixed.md @@ -0,0 +1 @@ +Treat Idaho as a Medicaid expansion state in the calculator's AI explanation. The Overview and the Methodology tab name KFF as the source of the model's 2026 and 2027 benchmark premiums, the Overview says both examples above 400% FPL live in their state's highest-cost rating area, and it gives where H.R. 1834's credit would end for the Pennsylvania example from the benchmark premium (about $174,550) instead of the last $1,000 step with a credit. The calculator's "Your household" tab asks for earnings, up to $1,000,000, and its cards come from the API at the earnings entered instead of from between the income axis's $1,000 steps, so they no longer blend the incomes on either side of an eligibility limit or of the jump in the share of income at 133% FPL, and Alaska's dividend counts toward the 400% FPL limit. Its text names Medicaid and CHIP only for the members they cover, says a state hasn't expanded Medicaid only where that's true, explains Medicaid's 2027 work requirement, and in the coverage gap shows what a plan costs without a credit. The cards' monthly change lines now match the payments shown, and the charts place 400% FPL on the credit's income. The contribution schedule charts no longer clip their x-axis title, and the marginal tax rate chart's 400% FPL label no longer covers the cliff. A link straight to the calculator or the Methodology tab no longer causes a hydration error, and a calculator link opened on the page (pasted, or with back and forward) now shows that link's household. diff --git a/changelog.d/aca-2027-overview.removed.md b/changelog.d/aca-2027-overview.removed.md new file mode 100644 index 0000000..60bd9f2 --- /dev/null +++ b/changelog.d/aca-2027-overview.removed.md @@ -0,0 +1 @@ +Remove the Explore Households page; its links open the Overview. diff --git a/changelog.d/calculate-at-income.added.md b/changelog.d/calculate-at-income.added.md new file mode 100644 index 0000000..b6cea74 --- /dev/null +++ b/changelog.d/calculate-at-income.added.md @@ -0,0 +1 @@ +Add `/api/calculate-at-income`, which calculates each scenario for a household at one level of earnings, with what covers each member (Medicaid, CHIP, or Medicaid's work requirement keeping them off it) and, in the coverage gap, what a plan would cost without a credit. `/api/calculate` also returns the credit's income (`magi`) at each point. The API builds H.R. 1834's version of the model once per process, so a calculation under it takes under a second instead of about ten. diff --git a/changelog.d/calculate-at-income.fixed.md b/changelog.d/calculate-at-income.fixed.md new file mode 100644 index 0000000..6e70613 --- /dev/null +++ b/changelog.d/calculate-at-income.fixed.md @@ -0,0 +1 @@ +Pay current law's premium tax credit at exactly 400% FPL, which 26 U.S.C. 36B(c)(1)(A) allows and policyengine-us 2.138.2 doesn't, in both API endpoints. diff --git a/changelog.d/overview-centered-chart.changed.md b/changelog.d/overview-centered-chart.changed.md new file mode 100644 index 0000000..eb925d7 --- /dev/null +++ b/changelog.d/overview-centered-chart.changed.md @@ -0,0 +1 @@ +On wide screens the Overview's pinned chart is larger and sits in the middle of the screen: its card is as tall as the screen allows (up to 720px) and each chart fills it, and the text cards are the same height, with their text centered, so the card in the middle of the screen lines up with the chart, and that card's section is the active one. The Overview is 1320px wide instead of 1200px, and the header lines up with its left edge. The calculator shows a spinner, with the step the server reports, instead of a progress bar while it calculates a household, and the "Your household" cards show a small spinner while they load. diff --git a/changelog.d/overview-chart-labels.fixed.md b/changelog.d/overview-chart-labels.fixed.md new file mode 100644 index 0000000..c05131b --- /dev/null +++ b/changelog.d/overview-chart-labels.fixed.md @@ -0,0 +1 @@ +The Overview's bulleted lists show their bullets again. The line names on the Overview's and the calculator's charts no longer touch a line, the 400% FPL line or its name: each name moves to the nearest clear spot beside its line, away from where two lines overlap, and a chart shows its legend instead when a name has no room, as on a phone. A legend that wraps onto a second line no longer overlaps the chart. diff --git a/changelog.d/remove-explain-with-ai.removed.md b/changelog.d/remove-explain-with-ai.removed.md new file mode 100644 index 0000000..74df22a --- /dev/null +++ b/changelog.d/remove-explain-with-ai.removed.md @@ -0,0 +1 @@ +Remove the calculator's "Explain with AI" button and its explanation window. A link with `ai=1` opens the household's results. The API's `/api/explain` endpoint is unchanged. diff --git a/example_households.py b/example_households.py new file mode 100644 index 0000000..4421a3f --- /dev/null +++ b/example_households.py @@ -0,0 +1,42 @@ +"""The four example households the Overview walks through. + +Shared by precompute_households.py, which computes the Overview's table, and +precompute_calculator_examples.py, which stores the calculator's result for +each so the calculator can show it without a request. No dependencies, so the +calculator script runs anywhere. +""" + +YEAR = 2027 +PRIOR_YEAR = 2026 + +# Two households below current law's 400% FPL limit and two above it. +EXAMPLES = [ + { + "key": "texas_single", + "name": "Single adult", + "description": "Age 40, Harris County, Texas", + "household": dict(age_head=40, age_spouse=None, dependent_ages=[], state="TX", county="Harris County"), + "income": 40_000, + }, + { + "key": "florida_family", + "name": "Family of four", + "description": "Parents aged 40, children aged 10 and 8, Hillsborough County, Florida", + "household": dict(age_head=40, age_spouse=40, dependent_ages=[10, 8], state="FL", county="Hillsborough County"), + "income": 75_000, + }, + { + "key": "pennsylvania_single", + "name": "Single adult", + "description": "Age 45, Lebanon County, Pennsylvania", + "household": dict(age_head=45, age_spouse=None, dependent_ages=[], state="PA", county="Lebanon County"), + "income": 104_000, + }, + { + "key": "california_couple", + "name": "Couple in their 60s", + "description": "Ages 64 and 62, San Benito County, California", + "household": dict(age_head=64, age_spouse=62, dependent_ages=[], state="CA", county="San Benito County"), + "income": 90_000, + }, +] diff --git a/modal-requirements.txt b/modal-requirements.txt index 18dcc10..a670827 100644 --- a/modal-requirements.txt +++ b/modal-requirements.txt @@ -2,8 +2,13 @@ # # Captured with `pip freeze` from the live aca-calc-api container on 2026-11-03, # minus the 14 packages that Modal's 2025.06 image builder installs at the same -# versions. Deploying from this file reproduces the calculator that has served -# since May 2026 (policyengine-us 1.691.3), so a redeploy changes only the code. +# versions. Since then policyengine-us has moved from 1.691.3 to 2.138.2 +# (2026-11-16), with the policyengine-core and spm-calculator versions it +# requires; every other pin is unchanged. 2.138.2 has the published 2027 +# premiums (policyengine-us #10682), counts the used premium tax credit in +# household net income (#10773), keeps a claimable filer out of the credit's +# tax family (#10041), and uses the Alaska and Hawaii guidelines when the +# state is supplied only for the coverage year (#10860). # # To upgrade a package, change its pin here, run the tests against the new set, # and compare /api/calculate results before deploying. @@ -58,11 +63,8 @@ parso==0.8.7 pexpect==4.9.0 plotly==5.24.1 pluggy==1.6.0 -policyengine-core==3.26.4 -# PyPI no longer serves policyengine-us 1.691.3 (of the 1.691 series it keeps -# only 1.691.1), so this builds it from its release commit. The build matches -# the live container's installed files hash for hash. -policyengine-us @ https://github.com/PolicyEngine/policyengine-us/archive/2cb12a24dad22d85a82549f6d164b9d5fbadbe5e.tar.gz +policyengine-core==3.36.0 +policyengine-us==2.138.2 prompt_toolkit==3.0.52 psutil==6.1.1 ptyprocess==0.7.0 @@ -81,7 +83,7 @@ shellingham==1.5.4 six==1.17.0 sniffio==1.3.1 sortedcontainers==2.4.0 -spm-calculator==0.3.1 +spm-calculator==1.1.0 stack-data==0.6.3 standard-imghdr==3.13.0 starlette==1.0.0 diff --git a/modal_app.py b/modal_app.py index 4a52c5f..adfe96a 100644 --- a/modal_app.py +++ b/modal_app.py @@ -5,13 +5,21 @@ import modal -app = modal.App("aca-calc-api") +# The live app is aca-calc-api. A preview deploy sets ACA_API_APP_NAME, say +# aca-calc-api-preview, to run a branch's backend beside it with caches of its +# own; the image carries the name, so its containers open the same caches. +APP_NAME = os.environ.get("ACA_API_APP_NAME", "aca-calc-api") +CACHE_SUFFIX = APP_NAME.removeprefix("aca-calc-api") + +app = modal.App(APP_NAME) # Persistent cache for calculation results (7-day TTL handled in application) -calculation_cache = modal.Dict.from_name("aca-calc-cache", create_if_missing=True) +calculation_cache = modal.Dict.from_name(f"aca-calc-cache{CACHE_SUFFIX}", create_if_missing=True) # Persistent cache for AI explanations -explanation_cache = modal.Dict.from_name("aca-explain-cache", create_if_missing=True) +explanation_cache = modal.Dict.from_name( + f"aca-explain-cache{CACHE_SUFFIX}", create_if_missing=True +) # Exact package versions from the live container, so a deploy changes only this # repo's code. Read the notes in the file before changing a pin. @@ -25,7 +33,13 @@ .add_local_dir("src/aca_api", "/root/src/aca_api", copy=True) # The commit a CI deploy came from. The API reports it, so the smoke test # can tell this deploy's containers from the previous version's. - .env({"PYTHONPATH": "/root", "ACA_API_COMMIT": os.environ.get("ACA_API_COMMIT", "")}) + .env( + { + "PYTHONPATH": "/root", + "ACA_API_COMMIT": os.environ.get("ACA_API_COMMIT", ""), + "ACA_API_APP_NAME": APP_NAME, + } + ) ) @@ -33,7 +47,9 @@ image=image, secrets=[modal.Secret.from_name("anthropic-api-key")], timeout=300, - memory=2048, + # policyengine-us 2.x needs about 0.9 GB to load and 2.4-2.9 GB once a + # request has run its scenarios' reforms. + memory=4096, ) @modal.asgi_app() def fastapi_app(): diff --git a/package.json b/package.json index f7c77b3..62a5555 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "type": "module", "scripts": { "dev": "next dev --turbopack", - "build": "next build", + "build": "node scripts/check_data.mjs && next build", + "check:data": "node scripts/check_data.mjs", "start": "next start" }, "dependencies": { diff --git a/precompute_calculator_examples.py b/precompute_calculator_examples.py new file mode 100644 index 0000000..e625e54 --- /dev/null +++ b/precompute_calculator_examples.py @@ -0,0 +1,108 @@ +""" +Store the calculator's result for each of the Overview's four example +households, so picking one on the calculator page shows its result without a +request. + +Each household is sent to the calculator API with exactly the request the +calculator's form sends (2027, with H.R. 1834 and 2026 current law alongside), +and the response is saved as it comes back, rounded to the cent, with the +answer at the household's earnings (/api/calculate-at-income) that its "Your +household" cards show. Writes src/data/households/calculator_examples.json, +which the calculator page loads. + +Uses only the standard library: it calls a deployed API rather than running +policyengine-us. Run it against an API serving this branch's backend, after +every policyengine-us pin: + + python precompute_calculator_examples.py --api-url https://policyengine--aca-calc-api-fastapi-app.modal.run +""" + +import argparse +import json +import urllib.request +from pathlib import Path + +from example_households import EXAMPLES, YEAR + +OUTPUT = Path(__file__).parent / "src" / "data" / "households" / "calculator_examples.json" +LIVE_API = "https://policyengine--aca-calc-api-fastapi-app.modal.run" + + +def form_request(household): + """The request CalculatorForm.jsx sends for this household.""" + return { + "year": YEAR, + "age_head": household["age_head"], + "age_spouse": household["age_spouse"], + "dependent_ages": household["dependent_ages"], + "state": household["state"], + "county": household["county"], + "zip_code": None, + "show_ira": True, + "show_prior_year": True, + } + + +def rounded(value): + """Floats to the cent, recursively.""" + if isinstance(value, float): + return round(value, 2) + if isinstance(value, list): + return [rounded(v) for v in value] + if isinstance(value, dict): + return {k: rounded(v) for k, v in value.items()} + return value + + +def calculate(api_url, request, endpoint="calculate"): + """POST the request to an endpoint, computing a fresh answer.""" + body = json.dumps({**request, "skip_cache": True}).encode() + req = urllib.request.Request( + f"{api_url.rstrip('/')}/api/{endpoint}", + data=body, + headers={"Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=300) as response: + return json.load(response), response.headers.get("X-ACA-API-Commit") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[1]) + parser.add_argument("--api-url", default=LIVE_API, help="The calculator API to call") + args = parser.parse_args() + + examples, versions, commits = [], set(), set() + for example in EXAMPLES: + request = form_request(example["household"]) + response, commit = calculate(args.api_url, request) + at_income, at_income_commit = calculate( + args.api_url, {**request, "income": example["income"]}, "calculate-at-income" + ) + versions.update({response.get("model_version"), at_income["model_version"]}) + commits.update({commit, at_income_commit}) + examples.append({ + "key": example["key"], + "name": example["name"], + "description": example["description"], + "income": example["income"], + "request": request, + "response": rounded(response), + "at_income": rounded(at_income), + }) + print(f"{example['key']}: {len(response['income'])} incomes, model {response.get('model_version')}") + + assert len(versions) == 1, f"the API answered with several model versions: {versions}" + data = { + "model_version": versions.pop(), + "api_commit": commits.pop() if len(commits) == 1 else None, + "year": YEAR, + "examples": examples, + } + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + OUTPUT.write_text(json.dumps(data, separators=(",", ":")), encoding="utf-8") + print(f"Saved {OUTPUT} ({OUTPUT.stat().st_size / 1024:.0f} KB)") + + +if __name__ == "__main__": + main() diff --git a/precompute_cliff_household.py b/precompute_cliff_household.py index 7767777..3b8e810 100644 --- a/precompute_cliff_household.py +++ b/precompute_cliff_household.py @@ -1,188 +1,148 @@ """ -Precompute the "cliff household" - single adult at 650% FPL in Lancaster County, PA. - -This household demonstrates the ACA cliff dramatically: -- 2025 (IRA rules): Gets substantial PTC -- 2026 (baseline, no IRA): Gets $0 PTC (above 400% FPL cliff) +Precompute the Overview's example household: a single adult (45) in Lebanon +County, PA, earning 650% of the poverty guideline 2027 credits use. + +Above 400% FPL current law gives no credit, so this household pays the whole +benchmark premium in 2026 and in 2027, the increase included. The file has +- 2026 and 2027 under current law +- 2027 under H.R. 1834, which would revive the enhanced credits of 2021-2025 +at the household's income, and across incomes for the charts. + +The income is the same in both years, so the changes are the law's and the +premiums', not the household's. + +It also has the household's marginal tax rate across incomes in 2027 under +current law and under H.R. 1834: the share of each extra $1,000 of earnings it +loses to taxes and to a smaller credit, from household net income, which counts +the premium tax credit the household uses (policyengine-us #10773). Writes src/data/households/cliff_demo.json, +which the Overview page reads. Rerun after every policyengine-us pin. """ import json -import numpy as np -import gc +from importlib.metadata import version from pathlib import Path + +import numpy as np from policyengine_us import Simulation + from aca_calc.calculations.household import build_household_situation -from aca_calc.calculations.reforms import create_enhanced_ptc_reform, create_700fpl_reform +from aca_calc.calculations.reforms import create_enhanced_ptc_reform + +OUTPUT = Path(__file__).parent / "src" / "data" / "households" / "cliff_demo.json" +HOUSEHOLD = dict(age_head=45, age_spouse=None, dependent_ages=[], state="PA", county="Lebanon County") +FPL_PERCENT = 650 +YEAR = 2027 +PRIOR_YEAR = 2026 + + +def sweep(year, reform=None): + """The household across the income axis for coverage year `year`.""" + situation = build_household_situation(**HOUSEHOLD, year=year, with_axes=True) + sim = Simulation(situation=situation, reform=reform) + fpl = sim.calculate("tax_unit_fpg", period=year - 1) + result = { + name: sim.calculate(name, map_to="household", period=year) + for name in ( + "employment_income", + "aca_ptc", + "slcsp", + "medicaid", + "chip", + "household_net_income", + ) + } + # The credit measures income against the prior year's guideline. + result["fpl"] = float(fpl[len(fpl) // 2]) + return result + + +def marginal_rates(result): + """The marginal tax rate between each income on the axis and the next: + one minus the change in net income over the change in earnings. The last + point repeats the one before it.""" + income = np.asarray(result["employment_income"], dtype=float) + net = np.asarray(result["household_net_income"], dtype=float) + rates = 1 - np.diff(net) / np.diff(income) + return np.append(rates, rates[-1]) + + +def point(result, index): + """Annual values at one point on the axis.""" + return { + "fpl": result["fpl"], + "fpl_percent": round(100 * float(result["employment_income"][index]) / result["fpl"]), + "slcsp": float(result["slcsp"][index]), + "ptc": float(result["aca_ptc"][index]), + } def main(): - output_dir = Path(__file__).parent / "data" / "households" - output_dir.mkdir(parents=True, exist_ok=True) - - print("Precomputing cliff household (single adult, 650% FPL, Lebanon County PA)...") - - # Lebanon County has higher premiums than Lancaster, making the cliff more dramatic - # ========== Build situations with income axes ========== - situation_2025 = build_household_situation( - age_head=45, - age_spouse=None, - dependent_ages=[], - state="PA", - county="Lebanon County", - year=2025, - with_axes=True, - ) - - situation_2026 = build_household_situation( - age_head=45, - age_spouse=None, - dependent_ages=[], - state="PA", - county="Lebanon County", - year=2026, - with_axes=True, - ) - - # Run 2025 simulation (IRA is in effect) - print("\n Running 2025 simulation (IRA in effect)...") - sim_2025 = Simulation(situation=situation_2025) - income_2025 = sim_2025.calculate("employment_income", map_to="household", period=2025) - ptc_2025 = sim_2025.calculate("aca_ptc", map_to="household", period=2025) - slcsp_2025 = sim_2025.calculate("slcsp", map_to="household", period=2025) - fpl_2025 = float(sim_2025.calculate("tax_unit_fpg", period=2025)[len(income_2025)//2]) - - print(f" FPL 2025: ${fpl_2025:,.0f}") - - # Run 2026 baseline simulation (IRA expires) - print("\n Running 2026 baseline simulation (IRA expires)...") - sim_2026_baseline = Simulation(situation=situation_2026) - income_2026 = sim_2026_baseline.calculate("employment_income", map_to="household", period=2026) - ptc_2026_baseline = sim_2026_baseline.calculate("aca_ptc", map_to="household", period=2026) - slcsp_2026 = sim_2026_baseline.calculate("slcsp", map_to="household", period=2026) - fpl_2026 = float(sim_2026_baseline.calculate("tax_unit_fpg", period=2026)[len(income_2026)//2]) - - # Also calculate Medicaid and CHIP for the health benefits chart - medicaid_2026 = sim_2026_baseline.calculate("medicaid", map_to="household", period=2026) - chip_2026 = sim_2026_baseline.calculate("chip", map_to="household", period=2026) - - print(f" FPL 2026: ${fpl_2026:,.0f}") - - # Run 2026 with IRA extension - print("\n Running 2026 with IRA extension...") - reform_ira = create_enhanced_ptc_reform() - sim_2026_ira = Simulation(situation=situation_2026, reform=reform_ira) - ptc_2026_ira = sim_2026_ira.calculate("aca_ptc", map_to="household", period=2026) - - # Run 2026 with 700% FPL bill - print("\n Running 2026 with 700% FPL bill...") - reform_700fpl = create_700fpl_reform() - ptc_2026_700fpl = None - if reform_700fpl: - sim_2026_700fpl = Simulation(situation=situation_2026, reform=reform_700fpl) - ptc_2026_700fpl = sim_2026_700fpl.calculate("aca_ptc", map_to="household", period=2026) - - # Find income at 650% FPL - target_income_2025 = fpl_2025 * 6.5 - target_income_2026 = fpl_2026 * 6.5 - print(f"\n 650% FPL income (2025): ${target_income_2025:,.0f}") - print(f" 650% FPL income (2026): ${target_income_2026:,.0f}") - - # Find index closest to target income for 2025 - idx_2025 = np.argmin(np.abs(income_2025 - target_income_2025)) - actual_income_2025 = float(income_2025[idx_2025]) - ptc_at_650_2025 = float(ptc_2025[idx_2025]) - # Use max SLCSP since it can be 0 at certain income levels due to eligibility modeling - max_slcsp_2025 = float(np.max(slcsp_2025)) - - # Find index closest to target income for 2026 - idx_2026 = np.argmin(np.abs(income_2026 - target_income_2026)) - actual_income_2026 = float(income_2026[idx_2026]) - ptc_at_650_baseline = float(ptc_2026_baseline[idx_2026]) - ptc_at_650_ira = float(ptc_2026_ira[idx_2026]) - ptc_at_650_700fpl = float(ptc_2026_700fpl[idx_2026]) if ptc_2026_700fpl is not None else 0 - # Use max SLCSP since it can be 0 at certain income levels due to eligibility modeling - max_slcsp_2026 = float(np.max(slcsp_2026)) - - print(f"\n Values at 650% FPL:") - print(f" 2025 income: ${actual_income_2025:,.0f}") - print(f" 2025 PTC (IRA): ${ptc_at_650_2025:,.0f}") - print(f" 2025 SLCSP (max): ${max_slcsp_2025:,.0f}") - print(f" 2026 income: ${actual_income_2026:,.0f}") - print(f" 2026 PTC (baseline): ${ptc_at_650_baseline:,.0f}") - print(f" 2026 PTC (IRA ext): ${ptc_at_650_ira:,.0f}") - print(f" 2026 PTC (700% FPL): ${ptc_at_650_700fpl:,.0f}") - print(f" 2026 SLCSP (max): ${max_slcsp_2026:,.0f}") - - # Build output data - cliff_data = { + print("Precomputing the Overview's example household...") + current = {year: sweep(year) for year in (PRIOR_YEAR, YEAR)} + hr1834 = sweep(YEAR, create_enhanced_ptc_reform()) + + income = current[YEAR]["employment_income"] + assert np.array_equal(income, current[PRIOR_YEAR]["employment_income"]) + index = int(np.argmin(np.abs(income - FPL_PERCENT / 100 * current[YEAR]["fpl"]))) + example_income = float(income[index]) + + years = {str(year): {**point(current[year], index), "law": "Current law"} for year in current} + proposals = {"hr1834": {**point(hr1834, index), "name": "H.R. 1834"}} + + data = { "household_key": "cliff_demo", "household_info": { "name": "Pennsylvania Single Adult", - "shortName": "PA Demo", - "description": "Single adult (45) in Lebanon County, PA at 650% FPL", + "description": f"Single adult (45) in Lebanon County, PA at {FPL_PERCENT}% FPL", "location": "Lebanon County, PA", - "age": 45, - "state": "PA", - "county": "Lebanon County", - "fpl_percent": 650, + "age": HOUSEHOLD["age_head"], + "state": HOUSEHOLD["state"], + "county": HOUSEHOLD["county"], + "fpl_percent": FPL_PERCENT, "isExpansion": True, }, - "fpl_2025": fpl_2025, - "fpl_2026": fpl_2026, - # Full income sweep data for 2026 (for charts) - "income": income_2026.tolist(), - "medicaid": medicaid_2026.tolist(), - "chip": chip_2026.tolist(), - "ptc_baseline": ptc_2026_baseline.tolist(), - "ptc_ira": ptc_2026_ira.tolist(), - "ptc_700fpl": ptc_2026_700fpl.tolist() if ptc_2026_700fpl is not None else [], - "slcsp": slcsp_2026.tolist(), - "fpl": fpl_2026, - # Specific values at 650% FPL for the demo - "at_650_fpl": { - "income_2025": actual_income_2025, - "income_2026": actual_income_2026, - "ptc_2025_ira": ptc_at_650_2025, - "slcsp_2025": max_slcsp_2025, - "ptc_2026_baseline": ptc_at_650_baseline, - "ptc_2026_ira": ptc_at_650_ira, - "ptc_2026_700fpl": ptc_at_650_700fpl, - "slcsp_2026": max_slcsp_2026, - "cliff_loss_annual": ptc_at_650_2025 - ptc_at_650_baseline, - "cliff_loss_monthly": (ptc_at_650_2025 - ptc_at_650_baseline) / 12, - }, - # Also include 2025 data for comparison charts - "income_2025": income_2025.tolist(), - "ptc_2025": ptc_2025.tolist(), - "slcsp_2025": slcsp_2025.tolist(), + "model_version": version("policyengine-us"), + "year": YEAR, + "prior_year": PRIOR_YEAR, + "example_income": example_income, + "years": years, + "proposals": proposals, + # Income sweeps for the charts, named as the calculator API names them. + "income": income.tolist(), + "medicaid": current[YEAR]["medicaid"].tolist(), + "chip": current[YEAR]["chip"].tolist(), + "ptc_baseline": current[YEAR]["aca_ptc"].tolist(), + "ptc_ira": hr1834["aca_ptc"].tolist(), + "ptc_prior_year": current[PRIOR_YEAR]["aca_ptc"].tolist(), + "slcsp_by_income": current[YEAR]["slcsp"].tolist(), + "slcsp_by_income_prior_year": current[PRIOR_YEAR]["slcsp"].tolist(), + "fpl": current[YEAR]["fpl"], + "fpl_prior_year": current[PRIOR_YEAR]["fpl"], + # Household net income and the marginal tax rate from each income to + # the next, in 2027. + "net_income_baseline": current[YEAR]["household_net_income"].tolist(), + "net_income_ira": hr1834["household_net_income"].tolist(), + "mtr_baseline": [round(float(r), 4) for r in marginal_rates(current[YEAR])], + "mtr_ira": [round(float(r), 4) for r in marginal_rates(hr1834)], } - - # Save - output_file = output_dir / "cliff_demo.json" - with open(output_file, "w") as f: - json.dump(cliff_data, f, indent=2) - print(f"\nSaved to {output_file}") - - # Print summary - print("\n" + "=" * 70) - print("CLIFF DEMO SUMMARY - Single Adult, Age 45, Lebanon County PA") - print("=" * 70) - print(f"\nIncome: ~${actual_income_2026:,.0f} (650% FPL)") - print() - print(f"{'Year':<8} {'Scenario':<25} {'PTC/year':<12} {'PTC/month':<12} {'SLCSP':<12}") - print("-" * 70) - print(f"{'2025':<8} {'IRA in effect':<25} ${ptc_at_650_2025:>9,.0f} ${ptc_at_650_2025/12:>9,.0f} ${max_slcsp_2025:>9,.0f}") - print(f"{'2026':<8} {'Baseline (IRA expires)':<25} ${ptc_at_650_baseline:>9,.0f} ${ptc_at_650_baseline/12:>9,.0f} ${max_slcsp_2026:>9,.0f}") - print(f"{'2026':<8} {'IRA Extended':<25} ${ptc_at_650_ira:>9,.0f} ${ptc_at_650_ira/12:>9,.0f} ${max_slcsp_2026:>9,.0f}") - print(f"{'2026':<8} {'700% FPL Bill':<25} ${ptc_at_650_700fpl:>9,.0f} ${ptc_at_650_700fpl/12:>9,.0f} ${max_slcsp_2026:>9,.0f}") - print() - loss = ptc_at_650_2025 - ptc_at_650_baseline - print(f"CLIFF IMPACT: This person loses ${loss:,.0f}/year (${loss/12:,.0f}/month) in subsidies") - net_premium_2025 = max(0, max_slcsp_2025 - ptc_at_650_2025) / 12 - net_premium_2026 = max_slcsp_2026 / 12 # No PTC in baseline - print(f" Net premium jumps from ${net_premium_2025:,.0f}/mo to ${net_premium_2026:,.0f}/mo") - - gc.collect() + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + OUTPUT.write_text(json.dumps(data, indent=2), encoding="utf-8") + print(f"Saved {OUTPUT}") + + print(f"\nIncome ${example_income:,.0f}") + print(f"{'':<24} {'FPL':>6} {'SLCSP/mo':>10} {'PTC/mo':>9} {'Net/mo':>9}") + rows = [(f"{y} {v['law']}", v) for y, v in years.items()] + rows += [(f"{YEAR} {v['name']}", v) for v in proposals.values()] + for label, v in rows: + net = max(0, v["slcsp"] - v["ptc"]) / 12 + print(f"{label:<24} {v['fpl_percent']:>5}% {v['slcsp'] / 12:>10,.0f} {v['ptc'] / 12:>9,.0f} {net:>9,.0f}") + print(f"\nMarginal tax rate, {YEAR} (current law / H.R. 1834)") + for fpl_percent in (300, 380, 398, 402, 450, 600, 900): + i = int(np.argmin(np.abs(income - fpl_percent / 100 * current[YEAR]["fpl"]))) + print( + f" ${income[i]:>9,.0f} ({fpl_percent}% FPL): " + f"{100 * data['mtr_baseline'][i]:7.1f}% / {100 * data['mtr_ira'][i]:7.1f}%" + ) if __name__ == "__main__": diff --git a/precompute_contribution_schedules.py b/precompute_contribution_schedules.py new file mode 100644 index 0000000..8d25eef --- /dev/null +++ b/precompute_contribution_schedules.py @@ -0,0 +1,70 @@ +""" +Precompute the Overview's contribution schedule chart: the share of income a +household pays for the benchmark plan, by income as a percent of the poverty +guideline, under current law (2026 and 2027) and the enhanced schedule +(2021-2025, which H.R. 1834 would revive). + +Computed by policyengine-us across an income axis for a single adult in +Travis County, TX: Texas didn't expand Medicaid, so every income from 100% FPL +up is in the credit's range. Writes src/data/contribution_schedules.json. +Rerun after every policyengine-us pin. +""" + +import json +from importlib.metadata import version +from pathlib import Path + +import numpy as np +from policyengine_us import Simulation + +from aca_calc.calculations.household import build_household_situation +from aca_calc.calculations.reforms import create_enhanced_ptc_reform + +OUTPUT = Path(__file__).parent / "src" / "data" / "contribution_schedules.json" +# Percent of the poverty guideline, in steps of 1%. +FPL_PERCENTS = np.arange(0, 801) + + +def schedule(year, reform=None): + """Applicable percentage (percent of income) at each FPL percent, None where + the credit isn't available.""" + situation = build_household_situation(40, None, [], "TX", county="Travis County", year=year) + fpg = float(Simulation(situation=situation).calculate("tax_unit_fpg", year - 1)[0]) + # A tenth of a percent above each step, so the truncated FPL fraction lands on it. + situation["axes"] = [[{ + "name": "employment_income", + "count": len(FPL_PERCENTS), + "min": 0.001 * fpg, + "max": (FPL_PERCENTS[-1] / 100 + 0.001) * fpg, + "period": year, + }]] + sim = Simulation(situation=situation, reform=reform) + rate = sim.calculate("aca_required_contribution_percentage", year) + eligible = sim.calculate("is_aca_ptc_eligible", year) + fraction = sim.calculate("aca_magi_fraction", year) + assert np.allclose(fraction, FPL_PERCENTS / 100), "the axis missed the FPL steps" + return [round(100 * float(r), 2) if e else None for r, e in zip(rate, eligible)] + + +def main(): + print("Precomputing contribution schedules...") + data = { + "model_version": version("policyengine-us"), + "fpl_percent": FPL_PERCENTS.tolist(), + "schedules": { + "current_2026": schedule(2026), + "current_2027": schedule(2027), + # The enhanced schedule doesn't change by year. + "enhanced": schedule(2027, create_enhanced_ptc_reform()), + }, + } + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + OUTPUT.write_text(json.dumps(data), encoding="utf-8") + print(f"Saved {OUTPUT}") + for name, values in data["schedules"].items(): + at = {pct: values[pct] for pct in (100, 150, 200, 300, 400, 450, 650, 750)} + print(f" {name:<13} {at}") + + +if __name__ == "__main__": + main() diff --git a/precompute_households.py b/precompute_households.py index 8c98ac5..e3a96ab 100644 --- a/precompute_households.py +++ b/precompute_households.py @@ -1,171 +1,73 @@ """ -Precompute household data for the scrollytelling interactive. - -Run this script to generate JSON files for each preset household. -This avoids running expensive PolicyEngine simulations when users load the app. - -Usage: - python precompute_households.py +Precompute the Overview's example households: what each pays for its benchmark +plan in 2026 and 2027 under current law, and in 2027 under H.R. 1834, which +would revive the enhanced credits of 2021-2025. + +Each household's income is the same in both years, so the changes are the +law's and the premiums', not the household's. Writes +src/data/households/examples.json, which the Overview reads. Rerun after every +policyengine-us pin. """ import json -import numpy as np -import gc +from importlib.metadata import version from pathlib import Path -from policyengine_us import Simulation -from aca_calc.calculations.household import build_household_situation -from aca_calc.calculations.reforms import create_enhanced_ptc_reform, create_700fpl_reform - -# Preset households (same as in app.py) -PRESET_HOUSEHOLDS = { - "florida_family": { - "name": "Florida Family of 4", - "description": "Two parents (age 40) with two children (ages 10 and 8) in Florida", - "age_head": 40, - "age_spouse": 40, - "dependent_ages": [10, 8], - "state": "FL", - "county": "Hillsborough County", - "is_expansion_state": False, - "key_insight": "Florida didn't expand Medicaid, creating a coverage gap for parents between 32% and 100% FPL.", - }, - "california_couple": { - "name": "California Couple", - "description": "An older couple (ages 64 and 62) in San Benito County, California", - "age_head": 64, - "age_spouse": 62, - "dependent_ages": [], - "state": "CA", - "county": "San Benito County", - "is_expansion_state": True, - "key_insight": "This older couple faces high premiums due to age-based rating, making subsidies especially valuable.", - }, - "texas_couple": { - "name": "Young Texas Couple", - "description": "A married couple (ages 28 and 27) in Harris County, Texas", - "age_head": 28, - "age_spouse": 27, - "dependent_ages": [], - "state": "TX", - "county": "Harris County", - "is_expansion_state": False, - "key_insight": "Texas didn't expand Medicaid. Adults below 100% FPL fall into the coverage gap with no affordable options.", - }, - "ny_family": { - "name": "Young Family in New York", - "description": "Two parents (ages 30 and 28) with a toddler (age 2) in New York City", - "age_head": 30, - "age_spouse": 28, - "dependent_ages": [2], - "state": "NY", - "county": "New York County", - "is_expansion_state": True, - "key_insight": "New York expanded Medicaid, so this family has coverage options at lower incomes, but faces the 400% FPL cliff.", - }, -} - - -def calculate_household_data(household_key: str, household: dict) -> dict: - """Calculate all chart data for a household.""" - print(f" Computing {household_key}...") - - # Build household situation - base_situation = build_household_situation( - age_head=household["age_head"], - age_spouse=household["age_spouse"], - dependent_ages=household["dependent_ages"], - state=household["state"], - county=household["county"], - year=2026, - with_axes=True, - ) - - # Create reforms - reform_ira = create_enhanced_ptc_reform() - reform_700fpl = create_700fpl_reform() - - # Run simulations - print(f" Running baseline simulation...") - sim_baseline = Simulation(situation=base_situation) - - print(f" Running IRA reform simulation...") - sim_ira = Simulation(situation=base_situation, reform=reform_ira) - - sim_700fpl = None - if reform_700fpl: - print(f" Running 700% FPL reform simulation...") - sim_700fpl = Simulation(situation=base_situation, reform=reform_700fpl) - # Get income range - income_range = sim_baseline.calculate("employment_income", map_to="household", period=2026) +from policyengine_us import Simulation - # Calculate all values - data = { - "household_key": household_key, - "household_info": household, - "income": income_range.tolist(), - "medicaid": sim_baseline.calculate("medicaid_cost", map_to="household", period=2026).tolist(), - "chip": sim_baseline.calculate("per_capita_chip", map_to="household", period=2026).tolist(), - "ptc_baseline": sim_baseline.calculate("aca_ptc", map_to="household", period=2026).tolist(), - "ptc_ira": sim_ira.calculate("aca_ptc", map_to="household", period=2026).tolist(), - "ptc_700fpl": sim_700fpl.calculate("aca_ptc", map_to="household", period=2026).tolist() if sim_700fpl else [], - "fpl": float(sim_baseline.calculate("tax_unit_fpg", period=2026)[len(income_range)//2]), - "slcsp": float(np.max(sim_baseline.calculate("slcsp", map_to="household", period=2026))), +from aca_calc.calculations.household import build_household_situation +from aca_calc.calculations.reforms import create_enhanced_ptc_reform +from example_households import EXAMPLES, PRIOR_YEAR, YEAR + +OUTPUT = Path(__file__).parent / "src" / "data" / "households" / "examples.json" + + +def scenario(example, year, reform=None): + """The household's benchmark premium and credit in coverage year `year`, + with all its income as the head's earnings.""" + situation = build_household_situation(**example["household"], year=year) + situation["people"]["you"]["employment_income"] = {year: example["income"]} + sim = Simulation(situation=situation, reform=reform) + slcsp = float(sim.calculate("slcsp", year)[0]) + ptc = float(sim.calculate("aca_ptc", year)[0]) + # The credit measures income against the prior year's guideline. + fpl = float(sim.calculate("tax_unit_fpg", year - 1)[0]) + return { + "fpl_percent": round(100 * example["income"] / fpl), + "slcsp": slcsp, + "ptc": ptc, + "net_premium": max(0.0, slcsp - ptc), + # Members buying a marketplace plan, and members on Medicaid or CHIP. + "marketplace_members": int(sim.calculate("pays_aca_premium", year).sum()), + "medicaid_or_chip_members": int( + ((sim.calculate("medicaid", year) > 0) | (sim.calculate("chip", year) > 0)).sum() + ), } - # Calculate net income for impact chart - print(f" Running net income simulations...") - base_situation["tax_units"]["your tax unit"]["tax_unit_itemizes"] = {2026: False} - - sim_baseline_net = Simulation(situation=base_situation) - sim_ira_net = Simulation(situation=base_situation, reform=reform_ira) - sim_700fpl_net = Simulation(situation=base_situation, reform=reform_700fpl) if reform_700fpl else None - - data["net_income_baseline"] = sim_baseline_net.calculate( - "household_net_income_including_health_benefits", map_to="household", period=2026 - ).tolist() - data["net_income_ira"] = sim_ira_net.calculate( - "household_net_income_including_health_benefits", map_to="household", period=2026 - ).tolist() - data["net_income_700fpl"] = sim_700fpl_net.calculate( - "household_net_income_including_health_benefits", map_to="household", period=2026 - ).tolist() if sim_700fpl_net else [] - - gc.collect() - return data - def main(): - """Precompute and save all household data.""" - output_dir = Path(__file__).parent / "data" / "households" - output_dir.mkdir(parents=True, exist_ok=True) - - print("Precomputing household data for ACA scrollytelling interactive...") - print(f"Output directory: {output_dir}") - print() - - all_data = {} - - for household_key, household in PRESET_HOUSEHOLDS.items(): - print(f"Processing: {household['name']}") - data = calculate_household_data(household_key, household) - all_data[household_key] = data - - # Save individual file - output_file = output_dir / f"{household_key}.json" - with open(output_file, "w") as f: - json.dump(data, f) - print(f" Saved to {output_file}") - print() - - # Also save combined file for single-load option - combined_file = output_dir / "all_households.json" - with open(combined_file, "w") as f: - json.dump(all_data, f) - print(f"Saved combined data to {combined_file}") - - print() - print("Done! Precomputed data ready for the scrollytelling app.") + print("Precomputing the Overview's example households...") + examples = [] + for example in EXAMPLES: + scenarios = { + "current_2026": scenario(example, PRIOR_YEAR), + "current_2027": scenario(example, YEAR), + "hr1834_2027": scenario(example, YEAR, create_enhanced_ptc_reform()), + } + examples.append({key: example[key] for key in ("key", "name", "description", "income")} | { + "people": 1 + bool(example["household"]["age_spouse"]) + len(example["household"]["dependent_ages"]), + "scenarios": scenarios, + }) + print(f" {example['key']}: " + ", ".join( + f"{name} {values['fpl_percent']}% FPL, benchmark ${values['slcsp'] / 12:,.0f}/mo, " + f"credit ${values['ptc'] / 12:,.0f}/mo, net ${values['net_premium'] / 12:,.0f}/mo" + for name, values in scenarios.items() + )) + + data = {"model_version": version("policyengine-us"), "year": YEAR, "prior_year": PRIOR_YEAR, "examples": examples} + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + OUTPUT.write_text(json.dumps(data, indent=2), encoding="utf-8") + print(f"Saved {OUTPUT}") if __name__ == "__main__": diff --git a/precompute_national.py b/precompute_national.py new file mode 100644 index 0000000..1301d27 --- /dev/null +++ b/precompute_national.py @@ -0,0 +1,407 @@ +""" +Precompute the national effects of reviving the enhanced premium tax credits in +2027 (H.R. 1834), and current law's credits in 2026 and 2027. + +Runs policyengine-us over its default microdata (the certified Populace build) +for 2027, under current law and with the enhanced schedule, and writes +src/data/national_impacts.json. The figures follow policyengine.py's +definitions (income deciles, winners and losers, SPM poverty, inequality). + +Since policyengine-us #10773, household net income counts the premium tax +credit a tax unit uses (used_aca_ptc, the credit capped at the premium of the +plan it enrolls in) as a refundable credit, so every figure here is the +model's own. The credits, cost and recipients use the used credit. SPM +resources count the same credit through the marketplace premium net of it +(marketplace_net_premium), so the change in SPM resources should match the +federal cost, and the change in household net income should match each +household's change in the used credit; the checks report both. + +Enrollment above 400% FPL. The microdata's Marketplace take-up flags make +about 6.7 million people above 400% FPL unsubsidized Marketplace buyers in +2027, against CBO's 2.8 million unsubsidized enrollees at all incomes and +KFF's 1.6 million 2025 sign-ups with income above 400% FPL; H.R. 1834 would +give each of them a credit. So above 400% FPL only tax units in which someone +reported Marketplace or other individual coverage in the survey take up +(restrict_takeup below), in both simulations. Take-up at or below 400% FPL is +the data's. + +Needs about 32 GB of memory: run it on Modal, not a laptop. Rerun after every +policyengine-us pin. +""" + +import gc +import json +from datetime import date +from importlib.metadata import version +from pathlib import Path + +import numpy as np +from microdf import MicroSeries +from policyengine_us import Microsimulation +from policyengine_us.system import DEFAULT_DATASET, DEFAULT_DATASET_SHA256 + +from aca_calc.calculations.reforms import create_enhanced_ptc_reform + +OUTPUT = Path(__file__).parent / "src" / "data" / "national_impacts.json" +YEAR = 2027 +PRIOR_YEAR = 2026 +# policyengine.py's winners-and-losers bands: relative change in net income. +BOUNDS = [-np.inf, -0.05, -1e-3, 1e-3, 0.05, np.inf] +CATEGORIES = [ + "lose_more_than_5pct", + "lose_less_than_5pct", + "no_change", + "gain_less_than_5pct", + "gain_more_than_5pct", +] +AGE_GROUPS = { + "all": (0, np.inf), + "child": (0, 17), + "adult": (18, 64), + "senior": (65, np.inf), +} +# Income as a fraction of the poverty guideline the credit uses; upper bounds +# are inclusive, so 400% FPL sits with current law's eligible incomes. +FPL_BANDS = [ + ("Up to 150%", -np.inf, 1.5), + ("150% to 250%", 1.5, 2.5), + ("250% to 400%", 2.5, 4.0), + ("400% to 600%", 4.0, 6.0), + ("Above 600%", 6.0, np.inf), +] + + +def values(sim, variable, year): + return np.asarray(sim.calculate(variable, year).values) + + +def person_share(sim, tax_unit_values): + """Each person's equal share of their tax unit's value, so sums over SPM + units and households keep the total.""" + tax_unit = sim.populations["tax_unit"] + return tax_unit.project(tax_unit_values / tax_unit.nb_persons()) + + +def credits(sim, year): + """Used credits, recipients and benchmark premiums in one year.""" + ptc = values(sim, "used_aca_ptc", year) + weight = values(sim, "tax_unit_weight", year) + slcsp = values(sim, "slcsp", year) + receiving = ptc > 0 + covered = values(sim, "is_aca_ptc_eligible", year) & sim.populations[ + "tax_unit" + ].project(receiving) + person_weight = values(sim, "person_weight", year) + return { + "ptc": ptc, + "summary": { + "total_ptc": float(np.sum(ptc * weight)), + "tax_units_receiving": float(np.sum(weight[receiving])), + "people_receiving": float(np.sum(person_weight[covered])), + # Among tax units receiving a credit. + "mean_benchmark_premium": float( + np.average(slcsp[receiving], weights=weight[receiving]) + ), + "mean_credit": float(np.average(ptc[receiving], weights=weight[receiving])), + "mean_net_benchmark_premium": float( + np.average((slcsp - ptc)[receiving], weights=weight[receiving]) + ), + }, + "covered": covered, + } + + +def gini(income, weight): + """policyengine.py's weighted Gini (area under the Lorenz curve).""" + order = np.argsort(income) + income, weight = income[order], weight[order] + lorenz = np.cumsum(income * weight) / np.sum(income * weight) + fractions = weight / np.sum(weight) + return float(1 - 2 * np.sum(fractions * (lorenz - fractions / 2))) + + +def inequality(income, weight): + """Gini and income shares of household net income, household-weighted, as + policyengine.py's standard US preset.""" + order = np.argsort(income) + sorted_income, sorted_weight = income[order], weight[order] + position = np.cumsum(sorted_weight) / np.sum(sorted_weight) + total = np.sum(sorted_income * sorted_weight) + + def share(mask): + return float(np.sum(sorted_income[mask] * sorted_weight[mask]) / total) + + return { + "gini": gini(income, weight), + "top_10_share": share(position > 0.9), + "top_1_share": share(position > 0.99), + "bottom_50_share": share(position <= 0.5), + } + + +def deciles(baseline, reform, household_weight, people): + """Average household net income by decile, and the share of people in each + winners-and-losers band, as policyengine.py computes them: households + ranked by baseline net income with weights times household size, negative + incomes left out of the deciles.""" + effective_weight = household_weight * people + rank = np.asarray(MicroSeries(baseline, weights=effective_weight).rank(pct=True)) + group = np.clip(np.ceil(rank * 10), 1, 10).astype(int) + group[baseline < 0] = -1 + change = (reform - baseline) / np.maximum(baseline, 1.0) + + def bands(selected): + weight = effective_weight[selected] + return { + name: float( + np.sum(weight[(change[selected] > low) & (change[selected] <= high)]) + / np.sum(weight) + ) + for name, low, high in zip(CATEGORIES, BOUNDS[:-1], BOUNDS[1:]) + } + + rows, winners = [], [] + for decile in range(1, 11): + selected = group == decile + weight = household_weight[selected] + baseline_mean = float(np.average(baseline[selected], weights=weight)) + reform_mean = float(np.average(reform[selected], weights=weight)) + rows.append({ + "decile": decile, + "baseline_mean": baseline_mean, + "reform_mean": reform_mean, + "absolute_change": reform_mean - baseline_mean, + "relative_change": 100 * (reform_mean - baseline_mean) / baseline_mean, + }) + winners.append({"decile": decile, **bands(selected)}) + overall = bands(np.ones(len(baseline), dtype=bool)) + return rows, {"all": overall, "deciles": winners} + + +def poverty(groups, person_weight, baseline_poor, reform_poor): + """Person-weighted poverty rates and headcounts for each group.""" + result = {} + for name, mask in groups.items(): + weight = person_weight[mask] + population = float(np.sum(weight)) + result[name] = { + "baseline_rate": float(np.sum(weight[baseline_poor[mask]]) / population), + "reform_rate": float(np.sum(weight[reform_poor[mask]]) / population), + "baseline_headcount": float(np.sum(weight[baseline_poor[mask]])), + "reform_headcount": float(np.sum(weight[reform_poor[mask]])), + } + return result + + +def takeup_mask(): + """Take-up flags for each year, with tax units above 400% FPL that report + no Marketplace or other individual coverage switched off, and the counts + behind them. Computed in a simulation of its own, so the two simulations + that are compared calculate in their usual order.""" + sim = Microsimulation(dataset_end_year=YEAR) + masks, counts = {}, {} + for year in (PRIOR_YEAR, YEAR): + takes_up = values(sim, "takes_up_aca_if_eligible", year).astype(bool) + above = values(sim, "aca_magi_fraction", year) > 4 + reported = ( + np.asarray(sim.calculate("has_marketplace_health_coverage_at_interview", year, map_to="tax_unit").values) > 0 + ) | ( + np.asarray( + sim.calculate( + "has_non_marketplace_direct_purchase_health_coverage_at_interview", year, map_to="tax_unit" + ).values + ) + > 0 + ) + masks[year] = takes_up & ~(above & ~reported) + weight = values(sim, "tax_unit_weight", year) + counts[str(year)] = { + "tax_units_switched_off": float(np.sum(weight[takes_up & above & ~reported])), + "tax_units_above_400_kept": float(np.sum(weight[takes_up & above & reported])), + } + del sim + gc.collect() + return masks, counts + + +def restrict_takeup(sim, masks): + """Set the restricted take-up flags before anything is calculated.""" + for year, mask in masks.items(): + sim.set_input("takes_up_aca_if_eligible", year, mask) + + +def enrollment(sim, year): + """People the simulation has buying Marketplace coverage: they pay an + age-rated premium and their tax unit takes up, with a premium above zero.""" + tax_unit = sim.populations["tax_unit"] + pays = values(sim, "pays_aca_premium", year).astype(bool) + premium = tax_unit.project(values(sim, "selected_marketplace_plan_premium_proxy", year)) + takes_up = tax_unit.project(values(sim, "takes_up_aca_if_eligible", year)).astype(bool) + credit = tax_unit.project(values(sim, "used_aca_ptc", year)) + fpl = tax_unit.project(values(sim, "aca_magi_fraction", year)) + weight = values(sim, "person_weight", year) + enrolled = pays & takes_up & (premium > 0) + return { + "people_enrolled": float(np.sum(weight[enrolled])), + "people_subsidized": float(np.sum(weight[enrolled & (credit > 0)])), + "people_unsubsidized": float(np.sum(weight[enrolled & (credit <= 0)])), + "people_enrolled_above_400": float(np.sum(weight[enrolled & (fpl > 4)])), + } + + +def main(): + print(f"Running policyengine-us {version('policyengine-us')} over {DEFAULT_DATASET}") + masks, takeup_counts = takeup_mask() + print(f" take-up above 400% FPL: {takeup_counts}") + + # Current law: everything the comparison needs, then free the simulation. + # Net income first in each simulation, since some results depend on the + # order variables are calculated in (policyengine-us #9740). + baseline = Microsimulation(dataset_end_year=YEAR) + restrict_takeup(baseline, masks) + net_income = values(baseline, "household_net_income", YEAR) + current = credits(baseline, YEAR) + print(f" current law {YEAR}: {current['summary']}") + household_weight = values(baseline, "household_weight", YEAR) + people = values(baseline, "household_count_people", YEAR) + resources = values(baseline, "spm_unit_net_income", YEAR) + threshold = values(baseline, "spm_unit_spm_threshold", YEAR) + model_poor = values(baseline, "spm_unit_is_in_spm_poverty", YEAR) + spm_unit_weight = values(baseline, "spm_unit_weight", YEAR) + tax_unit_weight = values(baseline, "tax_unit_weight", YEAR) + fpl_fraction = values(baseline, "aca_magi_fraction", YEAR) + person_weight = values(baseline, "person_weight", YEAR) + age = values(baseline, "age", YEAR) + is_male = values(baseline, "is_male", YEAR) + race = values(baseline, "race", YEAR).astype(str) + person_spm_unit = baseline.populations["spm_unit"].members_entity_id + baseline_enrollment = enrollment(baseline, YEAR) + print(f" enrollment, current law {YEAR}: {baseline_enrollment}") + prior = credits(baseline, PRIOR_YEAR) + print(f" current law {PRIOR_YEAR}: {prior['summary']}") + del baseline + gc.collect() + + reform = Microsimulation(reform=create_enhanced_ptc_reform(), dataset_end_year=YEAR) + restrict_takeup(reform, masks) + reform_net_income = values(reform, "household_net_income", YEAR) + # SPM resources count the credit through lower marketplace premiums. + reform_resources = values(reform, "spm_unit_net_income", YEAR) + revived = credits(reform, YEAR) + print(f" enhanced {YEAR}: {revived['summary']}") + change = revived["ptc"] - current["ptc"] + share = person_share(reform, change) + credit_change = reform.populations["household"].sum(share) + del reform + gc.collect() + + household_change = reform_net_income - net_income + # Anything else the reform changes in net income (expected none). + other_income_change = household_change - credit_change + measured = np.isfinite(resources) & np.isfinite(threshold) + assert np.array_equal( + (resources < threshold)[measured], model_poor[measured] + ), "SPM poverty doesn't match the model's" + + decile_rows, winners = deciles(net_income, reform_net_income, household_weight, people) + + person_measured = measured[person_spm_unit] + groups = { + name: (age >= low) & (age <= high) & person_measured + for name, (low, high) in AGE_GROUPS.items() + } + groups.update({ + "male": is_male & person_measured, + "female": ~is_male & person_measured, + **{ + value.lower(): (race == value) & person_measured + for value in ("WHITE", "BLACK", "HISPANIC", "OTHER") + }, + }) + + def poor(spm_resources, scale): + return (spm_resources < scale * threshold)[person_spm_unit] + + poverty_rates = { + "spm": poverty(groups, person_weight, poor(resources, 1), poor(reform_resources, 1)), + "deep": poverty( + groups, person_weight, poor(resources, 0.5), poor(reform_resources, 0.5) + ), + } + + by_fpl = [] + for label, low, high in FPL_BANDS: + band = (fpl_fraction > low) & (fpl_fraction <= high) + weight = tax_unit_weight[band] + by_fpl.append({ + "band": label, + "baseline_ptc": float(np.sum(current["ptc"][band] * weight)), + "reform_ptc": float(np.sum(revived["ptc"][band] * weight)), + "tax_units_baseline": float(np.sum(weight[current["ptc"][band] > 0])), + "tax_units_reform": float(np.sum(weight[revived["ptc"][band] > 0])), + }) + + gaining = household_change > 0 + data = { + "model_version": version("policyengine-us"), + "dataset": DEFAULT_DATASET, + "dataset_sha256": DEFAULT_DATASET_SHA256, + "computed": date.today().isoformat(), + "year": YEAR, + "current_law": { + str(PRIOR_YEAR): prior["summary"], + str(YEAR): current["summary"], + }, + "enhanced": revived["summary"], + "budget": { + # Positive: the federal government spends more. + "federal_cost": float(np.sum(change * tax_unit_weight)), + }, + "recipients": { + "people_newly_receiving": float( + np.sum(person_weight[revived["covered"] & ~current["covered"]]) + ), + }, + "households": { + "gaining": float(np.sum(household_weight[gaining])), + "people_gaining": float(np.sum((household_weight * people)[gaining])), + "total": float(np.sum(household_weight)), + "people": float(np.sum(household_weight * people)), + "mean_gain_among_gaining": float( + np.average(household_change[gaining], weights=household_weight[gaining]) + ), + }, + "by_fpl": by_fpl, + "deciles": decile_rows, + "winners_losers": winners, + "poverty": poverty_rates, + "inequality": { + "baseline": inequality(net_income, household_weight), + "reform": inequality(reform_net_income, household_weight), + }, + "enrollment": { + "current_law": baseline_enrollment, + "takeup_above_400": takeup_counts, + "rule": ( + "Above 400% FPL, only tax units in which someone reported Marketplace or " + "other individual coverage in the survey take up Marketplace coverage." + ), + }, + "checks": { + "max_other_net_income_change": float(np.max(np.abs(other_income_change))), + # Against the federal cost: how much of the added credit reaches + # SPM resources through lower premiums. + "spm_resource_change": float( + np.nansum((reform_resources - resources) * spm_unit_weight) + ), + "spm_units_not_measured": int(np.sum(~measured)), + }, + } + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + OUTPUT.write_text(json.dumps(data, indent=1), encoding="utf-8") + print(f"Saved {OUTPUT}") + print(json.dumps({key: data[key] for key in ("budget", "recipients", "households", "checks")}, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/scripts/check_data.mjs b/scripts/check_data.mjs new file mode 100644 index 0000000..6698dc3 --- /dev/null +++ b/scripts/check_data.mjs @@ -0,0 +1,159 @@ +// Checks that the precomputed data files agree before the app builds, so a +// figure on the page can't drift from the others. Runs before `next build` +// (package.json); exits 1 with a list of problems. No dependencies. +// +// node scripts/check_data.mjs + +import { readFileSync } from "node:fs"; + +const FILES = { + cliff: "households/cliff_demo.json", + examples: "households/examples.json", + schedules: "contribution_schedules.json", + national: "national_impacts.json", + calculator: "households/calculator_examples.json", +}; + +const read = (path) => + JSON.parse(readFileSync(new URL(`../src/data/${path}`, import.meta.url), "utf8")); +const data = Object.fromEntries(Object.entries(FILES).map(([key, path]) => [key, read(path)])); + +const problems = []; +const check = (ok, message) => { + if (!ok) problems.push(message); +}; + +// 1. Every file comes from the same policyengine-us release. +const versions = Object.fromEntries(Object.entries(data).map(([key, d]) => [key, d.model_version])); +check( + new Set(Object.values(versions)).size === 1, + `the data files come from different policyengine-us versions: ${JSON.stringify(versions)}` +); + +// 2. The same coverage year. +const year = data.national.year; +for (const key of ["cliff", "examples", "calculator"]) { + check(data[key].year === year, `${FILES[key]} is for ${data[key].year}, national_impacts.json for ${year}`); +} + +// 3. The national figures add up: H.R. 1834's credits less current law's are +// the cost, and every SPM unit is measured. +const national = data.national; +const law = national.current_law[String(year)]; +const cost = national.enhanced.total_ptc - law.total_ptc; +check( + Math.abs(cost - national.budget.federal_cost) < 1e7, + `national cost ${national.budget.federal_cost} differs from H.R. 1834's credits less current law's (${cost})` +); +check(national.checks.spm_units_not_measured === 0, "some SPM units are not measured"); +// The national run limits Marketplace take-up above 400% FPL to tax units that +// report individual coverage (precompute_national.py); a file without that +// rule is from an older run. +check( + Boolean(national.enrollment?.takeup_above_400 && national.enrollment?.current_law), + "national_impacts.json lacks the enrollment rule above 400% FPL: rerun precompute_national.py" +); + +// 4. The calculator's stored examples match the Overview's table, at each +// household's income, to the dollar a month. +const overview = Object.fromEntries(data.examples.examples.map((e) => [e.key, e])); +const net = (benchmark, credit) => Math.max(0, benchmark - credit) / 12; +for (const example of data.calculator.examples) { + const table = overview[example.key]; + if (!table) { + problems.push(`calculator example ${example.key} is not in the Overview's table`); + continue; + } + const r = example.response; + let i = 0; + r.income.forEach((income, k) => { + if (Math.abs(income - example.income) < Math.abs(r.income[i] - example.income)) i = k; + }); + const stored = { + [`current_${year - 1}`]: net(r.slcsp_by_income_prior_year[i], r.ptc_prior_year[i]), + [`current_${year}`]: net(r.slcsp_by_income[i], r.ptc_baseline[i]), + [`hr1834_${year}`]: net(r.slcsp_by_income[i], r.ptc_ira[i]), + }; + for (const [scenario, value] of Object.entries(stored)) { + const expected = table.scenarios[scenario].net_premium / 12; + check( + Math.abs(value - expected) < 1, + `${example.key}, ${scenario}: the calculator pays $${value.toFixed(2)}/month, the Overview $${expected.toFixed(2)}` + ); + } +} + +// 5. The Pennsylvania sweep's marginal rates cover every income. +const cliff = data.cliff; +for (const key of ["mtr_baseline", "mtr_ira", "net_income_baseline", "net_income_ira"]) { + check(cliff[key]?.length === cliff.income.length, `cliff_demo.json's ${key} doesn't match its incomes`); +} + +// 6. The Overview's two-income table (HouseholdYearTable) reads the +// Pennsylvania sweep; at the example's income it must match the household +// table, to the dollar a month. +const sweepAt = cliff.income.indexOf(cliff.example_income); +const pennsylvania = overview.pennsylvania_single; +check(sweepAt >= 0, `cliff_demo.json has no row at its example income ${cliff.example_income}`); +check(pennsylvania?.income === cliff.example_income, "the Pennsylvania example's income differs from the sweep's"); +if (sweepAt >= 0 && pennsylvania) { + const sweep = { + [`current_${year - 1}`]: net(cliff.slcsp_by_income_prior_year[sweepAt], cliff.ptc_prior_year[sweepAt]), + [`current_${year}`]: net(cliff.slcsp_by_income[sweepAt], cliff.ptc_baseline[sweepAt]), + [`hr1834_${year}`]: net(cliff.slcsp_by_income[sweepAt], cliff.ptc_ira[sweepAt]), + }; + for (const [scenario, value] of Object.entries(sweep)) { + const expected = pennsylvania.scenarios[scenario].net_premium / 12; + check( + Math.abs(value - expected) < 1, + `Pennsylvania sweep, ${scenario}: $${value.toFixed(2)}/month, the household table $${expected.toFixed(2)}` + ); + } +} + +// 7. Each example's "Your household" cards, which the API calculated at its +// earnings, match the Overview's table, to the dollar a month. +for (const example of data.calculator.examples) { + const table = overview[example.key]; + const answer = example.at_income; + if (!table) continue; + if (!answer || answer.income !== example.income) { + problems.push(`calculator example ${example.key} has no answer at its income: rerun precompute_calculator_examples.py`); + continue; + } + const cards = { + [`current_${year - 1}`]: answer.prior_year, + [`current_${year}`]: answer.current, + [`hr1834_${year}`]: answer.ira, + }; + for (const [scenario, card] of Object.entries(cards)) { + const value = card ? net(card.benchmark, card.credit) : NaN; + const expected = table.scenarios[scenario].net_premium / 12; + check( + Math.abs(value - expected) < 1, + `${example.key}, ${scenario}: the card pays $${value.toFixed(2)}/month, the Overview $${expected.toFixed(2)}` + ); + } +} + +// 8. Current law pays a credit at exactly 400% FPL, which qualifies (26 U.S.C. +// 36B(c)(1)(A)), and none a step above. The Florida family's 400% FPL is on +// the income axis. +const florida = data.calculator.examples.find((example) => example.key === "florida_family")?.response; +check(Boolean(florida), "the calculator examples lack the Florida household"); +if (florida) { + const atLimit = florida.income.indexOf(4 * florida.fpl); + check(atLimit >= 0, `the Florida household's 400% FPL, $${4 * florida.fpl}, isn't on its income axis`); + if (atLimit >= 0) { + check(florida.ptc_baseline[atLimit] > 0, "current law shows no credit at exactly 400% FPL, which qualifies"); + check(florida.ptc_baseline[atLimit + 1] === 0, "current law shows a credit above 400% FPL"); + } +} + +if (problems.length) { + console.error(`Data check failed (${problems.length}):\n- ${problems.join("\n- ")}`); + process.exit(1); +} +console.log( + `Data check passed: policyengine-us ${versions.national}, ${year}, ${data.calculator.examples.length} calculator examples match the Overview.` +); diff --git a/scripts/smoke_test_api.py b/scripts/smoke_test_api.py index cd0956e..4b7435e 100644 --- a/scripts/smoke_test_api.py +++ b/scripts/smoke_test_api.py @@ -3,10 +3,13 @@ Usage: python scripts/smoke_test_api.py API_URL [--explain] [--commit SHA [--wait SECONDS]] Checks /api/health, then both calculator endpoints: /api/calculate-stream, -which the calculator page calls, and /api/calculate, its fallback. Both -requests set skip_cache, so the deployed code computes each answer instead of -returning one from the 7-day calculation cache, and the stream check confirms -that it did. With --explain it checks /api/health and then /api/explain +which the calculator page calls, and /api/calculate, its fallback, then a +2027 calculation with 2026 alongside, as the calculator page asks, and the +same household at one level of earnings (/api/calculate-at-income), which the +page's "Your household" tab asks for. The +requests set skip_cache, so the deployed code computes +each answer instead of returning one from the 7-day calculation cache, and the +stream check confirms that it did. With --explain it checks /api/health and then /api/explain instead of the calculator: it requests a fixed household's AI narrative, which calls the Anthropic API unless the answer is already in the 7-day explanation cache. @@ -170,6 +173,41 @@ def check_calculate(base): check_result("/api/calculate", call(f"{base}/api/calculate", FRESH)) +def check_calculate_2027(base): + # Requests without a year get 2026; the calculator page asks for 2027, with + # 2026 current law for the same household alongside. The credit measures + # income against the prior year's poverty guideline. + result = call(f"{base}/api/calculate", {**FRESH, "year": 2027, "show_prior_year": True}) + assert result.get("year") == 2027, f"asked for 2027, got {result.get('year')}" + assert result.get("fpl_year") == 2026, ( + f"2027 credits use the 2026 guideline, got {result.get('fpl_year')}" + ) + assert max(result.get("ptc_prior_year") or [0]) > 0, "no 2026 credits came back" + assert (result.get("fpl_prior_year") or 0) > 0, "no 2026 guideline came back" + check_result("/api/calculate (2027)", result) + + +def check_calculate_at_income(base): + # The "Your household" tab's request: 2027, with H.R. 1834 and 2026. + result = call( + f"{base}/api/calculate-at-income", + {**FRESH, "year": 2027, "show_prior_year": True, "income": 40_000}, + ) + assert result.get("year") == 2027, f"asked for 2027, got {result.get('year')}" + assert result.get("income") == 40_000, f"asked for $40,000, got {result.get('income')}" + for name in ("current", "ira", "prior_year"): + scenario = result.get(name) + assert scenario, f"/api/calculate-at-income: no {name} scenario" + for field in ("benchmark", "credit", "full_premium", "magi", "fpl"): + value = scenario[field] + assert math.isfinite(value) and value >= 0, f"{name}: {field} is {value}" + assert scenario["credit"] > 0, f"{name}: no credit at $40,000" + print( + f"ok /api/calculate-at-income: 2027 credit {result['current']['credit']:,.0f} " + f"at $40,000, 2026 {result['prior_year']['credit']:,.0f}" + ) + + def check_explain(base): # A fixed household, so after the first deploy the answer usually comes # from the explanation cache rather than a new Anthropic API call. @@ -234,7 +272,13 @@ def main(): if args.explain: checks = [check_health, check_explain] else: - checks = [check_health, check_calculate_stream, check_calculate] + checks = [ + check_health, + check_calculate_stream, + check_calculate, + check_calculate_2027, + check_calculate_at_income, + ] for check in checks: from_this_deploy(check, base) diff --git a/src/App.css b/src/App.css index e6072ec..bb1627c 100644 --- a/src/App.css +++ b/src/App.css @@ -1,246 +1,449 @@ -/* Main App Styles - Scrollytelling Layout */ +/* The page frame, the Overview story and the calculator page. Colors, fonts + and radii come from @policyengine/ui-kit's theme. */ +/* A faintly tinted page, so the white cards (charts, key figures, the + calculator's panels) stand off it. */ .app { min-height: 100vh; - background: linear-gradient(180deg, var(--pe-gray-50) 0%, #f0f4f8 100%); + background: linear-gradient(180deg, var(--pe-gray-50) 0%, var(--pe-gray-100) 100%); + color: var(--foreground); } -/* Header */ +/* Title and page tabs on white, left-aligned with the Overview's split layout + (.overview, 1320px), as on the earlier version of the app. The + PolicyEngine shell above already has a sticky bar, so this header scrolls + with the page. */ .header { - background: var(--pe-surface); - border-bottom: 1px solid var(--pe-border); - padding: var(--pe-space-xl) var(--pe-space-lg); - position: sticky; - top: 0; - z-index: 100; - backdrop-filter: blur(12px); - background: rgba(255, 255, 255, 0.95); + border-bottom: 1px solid var(--border); + padding: 40px 16px 24px; + background: var(--card); } +/* The Overview's 1320px less its 16px sides, so the two left edges line up. */ .header-content { - max-width: 1200px; + max-width: 1288px; margin: 0 auto; } .header h1 { - font-size: 1.75rem; + font-size: 2rem; + line-height: 1.2; font-weight: 700; - color: var(--pe-gray-900); - margin: 0 0 var(--pe-space-xs) 0; - letter-spacing: -0.02em; + color: var(--color-gray-900); + letter-spacing: -0.01em; } .subtitle { - font-size: 1rem; - color: var(--pe-text-secondary); - margin: 0; + margin-top: 8px; + font-size: 1.125rem; + line-height: 1.5; + color: var(--muted-foreground); } -/* Page tabs in header */ +/* Pill tabs, as on the earlier version of the app. */ .page-tabs { display: flex; - gap: var(--pe-space-sm); - margin-top: var(--pe-space-md); + flex-wrap: wrap; + gap: 8px; + margin-top: 24px; } .page-tab { padding: 12px 28px; - border: 2px solid var(--pe-border); - border-radius: 28px; - background: var(--pe-surface); - font-family: var(--pe-font-family); + border: 2px solid var(--border); + border-radius: 9999px; + background: var(--card); + font-family: var(--font-sans); font-size: 1rem; font-weight: 600; - color: var(--pe-text-secondary); + color: var(--muted-foreground); + white-space: nowrap; cursor: pointer; - transition: all var(--pe-transition-fast); + transition: color var(--pe-transition-fast), border-color var(--pe-transition-fast), + background-color var(--pe-transition-fast); } .page-tab:hover { - border-color: var(--pe-accent); - color: var(--pe-accent); + border-color: var(--primary); + color: var(--primary); } .page-tab.active { - background: var(--pe-accent); - border-color: var(--pe-accent); - color: white; + background: var(--primary); + border-color: var(--primary); + color: var(--primary-foreground, #fff); } -/* Household Selector */ -.household-selector-container { - max-width: 1200px; - margin: 0 auto; - padding: var(--pe-space-lg); - display: flex; - flex-direction: column; - gap: var(--pe-space-sm); +.page-tab:focus-visible, +.story-cta:focus-visible { + outline: 2px solid var(--ring); + outline-offset: 2px; } -.household-info { - display: flex; - align-items: center; - gap: var(--pe-space-md); - font-size: 0.875rem; +/* The Methodology tab: one centered column of text. */ +.story-layout { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 760px) minmax(0, 1fr); +} + +.story { + grid-column: 2; + width: 100%; + padding: 16px 16px 64px; } -.location { - color: var(--pe-text-secondary); +.story-section { + padding-top: 40px; + scroll-margin-top: 72px; } -.expansion-badge { - padding: 4px 10px; - border-radius: 20px; +/* The heading that opens each part of the story, as a pill. */ +.story-part { + display: inline-block; + margin-bottom: 12px; + padding: 4px 12px; + border-radius: 9999px; + background: var(--pe-teal-100); font-size: 0.75rem; font-weight: 600; + letter-spacing: 0.04em; text-transform: uppercase; - letter-spacing: 0.02em; + color: var(--pe-teal-800); } -.expansion-badge.expansion { - background: var(--pe-teal-100); +.story-section h2 { + font-size: 1.5rem; + line-height: 1.3; + font-weight: 700; + letter-spacing: -0.01em; color: var(--pe-teal-700); + margin-bottom: 12px; +} + +.story-prose p, +.story-prose ul { + font-size: 1.0625rem; + line-height: 1.7; + color: var(--color-gray-700); + margin-bottom: 16px; +} + +.story-prose ul { + padding-left: 1.25rem; + list-style: disc; +} + +.story-prose li { + margin-bottom: 4px; +} + +.story-prose strong { + font-weight: 600; + color: var(--color-gray-900); +} + +/* A chart or table in the text: a raised white card as wide as the column. + Charts size to the card, so nothing runs past it. */ +.story-figure { + margin: 8px 0 8px; + padding: 20px; + border: 1px solid var(--border); + border-radius: var(--pe-radius-xl); + background: var(--card); + box-shadow: var(--pe-shadow-md); + overflow: hidden; +} + +/* Buttons lift on hover and their arrow slides forward. */ +.story-cta { + display: inline-flex; + align-items: center; + gap: 8px; + margin-top: 8px; + padding: 12px 20px; + border: none; + border-radius: var(--radius-container); + background: var(--primary); + color: var(--primary-foreground, #fff); + font-family: var(--font-sans); + font-size: 1rem; + font-weight: 600; + cursor: pointer; + transition: background-color var(--pe-transition-fast), transform var(--pe-transition-fast), + box-shadow var(--pe-transition-fast); +} + +.story-cta:hover { + background: var(--pe-teal-700); + transform: translateY(-1px); + box-shadow: var(--pe-shadow-md); +} + +.story-cta svg { + transition: transform var(--pe-transition-fast); +} + +.story-cta:hover svg { + transform: translateX(4px); +} + +.story-cta.secondary { + background: var(--card); + color: var(--primary); + box-shadow: inset 0 0 0 1px var(--primary); +} + +.story-cta.secondary:hover { + background: var(--pe-teal-50); +} + +@media (prefers-reduced-motion: reduce) { + .story-cta, + .story-cta svg { + transition: none; + } + + .story-cta:hover, + .story-cta:hover svg { + transform: none; + } +} + +/* The buttons that end the Overview and the Methodology page. */ +.story-ctas { + display: flex; + flex-wrap: wrap; + gap: 12px; + padding-top: 40px; } -.expansion-badge.non-expansion { - background: #fef3c7; - color: #92400e; +.story-prose a { + color: var(--primary); + font-weight: 600; + text-decoration: underline; + text-underline-offset: 2px; } -/* Scrollytelling Container */ -.scrollytelling-container { - max-width: 1200px; +.story-prose code { + font-family: var(--font-mono); + font-size: 0.875em; + overflow-wrap: anywhere; +} + +/* The Overview's split layout, as on the earlier version of the app: on wide + screens the active section's chart is pinned on the left (55%) and the text + scrolls past in cards on the right (45%). The opening paragraph sits above, + at reading width. Below 1025px (useMediaQuery in App.jsx) it is one column, + each chart under its text. */ +.overview { + max-width: 1320px; margin: 0 auto; + padding: 0 16px 64px; +} + +.scrolly { + /* The pinned chart's card and each text card: as tall as the screen below + the PolicyEngine shell's bar allows, less 40px above and below, up to + 720px. */ + --scrolly-card-height: min(calc(100vh - var(--spacing-header, 58px) - 80px), 720px); display: grid; - grid-template-columns: 55% 45%; - gap: var(--pe-space-xl); - padding: 0 var(--pe-space-lg); + grid-template-columns: minmax(0, 55fr) minmax(0, 45fr); + gap: 32px; + padding-top: 32px; } -/* Chart Column - Sticky */ -.chart-column { +.scrolly-chart { position: relative; } -.chart-sticky { +/* In the middle of the screen below the PolicyEngine shell's sticky bar: + useCenteredSticky sets top from the chart's height. */ +.scrolly-sticky { position: sticky; - top: 200px; - height: calc(100vh - 280px); - background: var(--pe-surface); - border-radius: var(--pe-radius-lg); + top: calc(var(--spacing-header, 58px) + 40px); + display: flex; + flex-direction: column; + height: var(--scrolly-card-height); + overflow: auto; + margin: 0; + padding: 20px; + border: 1px solid var(--border); + border-radius: var(--pe-radius-xl); + background: var(--card); box-shadow: var(--pe-shadow-lg); - padding: var(--pe-space-lg); +} + +/* Each new chart fades in, in the middle of the card. A chart fills the card + (its plot takes the height its title and note leave); a table sits in the + middle. */ +.scrolly-swap { display: flex; + flex: 1; flex-direction: column; + justify-content: center; + min-height: 0; + animation: scrolly-fade var(--pe-transition-slow); } -/* Text Column - Scrollable */ -.text-column { - padding-bottom: 50vh; +.scrolly-swap .chart-fill { + display: flex; + flex-direction: column; + height: 100%; } -/* Footer */ -.footer { - text-align: center; - padding: var(--pe-space-2xl) var(--pe-space-lg); - color: var(--pe-text-muted); - font-size: 0.875rem; +.chart-plot.fill { + flex: 1; + min-height: 260px; } -.footer a { - color: var(--pe-accent); - text-decoration: none; - font-weight: 500; +@keyframes scrolly-fade { + from { + opacity: 0; + transform: translateY(6px); + } + to { + opacity: 1; + transform: none; + } } -.footer a:hover { - color: var(--pe-accent-dark); - text-decoration: underline; +/* Room below the last card, so it can reach the line that makes a section + active (the middle of the screen, useActiveSection). */ +.scrolly-text { + padding-bottom: 50vh; } -.calc-link { - background: var(--pe-accent); - color: white !important; - padding: 8px 16px; - border-radius: var(--pe-radius-md); - margin-left: var(--pe-space-md); +/* A section as a card, as tall as the pinned chart's, with its text in the + middle, so the card in the middle of the screen lines up with the chart. + Cards other than the active one are dimmed, but kept readable. */ +.story-section.scroll-card { + display: flex; + flex-direction: column; + align-items: flex-start; + justify-content: center; + min-height: var(--scrolly-card-height); + margin-bottom: 24px; + padding: 28px; + border: 2px solid transparent; + border-radius: var(--pe-radius-xl); + background: var(--card); + box-shadow: var(--pe-shadow-md); + opacity: 0.7; + transition: opacity var(--pe-transition-base), border-color var(--pe-transition-base), + box-shadow var(--pe-transition-base); } -.calc-link:hover { - background: var(--pe-accent-dark); - text-decoration: none !important; +.story-section.scroll-card.active { + opacity: 1; + border-color: var(--primary); + box-shadow: var(--pe-shadow-md), 0 0 0 4px var(--pe-teal-50); } -/* Households page */ -.households-page { - max-width: 1200px; - margin: 0 auto; - padding: var(--pe-space-lg); +.scroll-card .story-prose p:last-child, +.scroll-card .story-prose ul:last-child { + margin-bottom: 0; +} + +@media (prefers-reduced-motion: reduce) { + .scrolly-swap { + animation: none; + } + + .story-section.scroll-card { + transition: none; + } +} + +@media (max-width: 1024px) { + .scrolly { + display: block; + padding-top: 24px; + } + + .scrolly-text { + padding-bottom: 0; + } + + .story-section.scroll-card { + display: block; + min-height: 0; + padding: 20px; + opacity: 1; + } + + /* The chart under the text, inside the card. */ + .scroll-card .story-figure { + margin-top: 16px; + padding: 0; + border: 0; + box-shadow: none; + } } /* Calculator page */ .calculator-page { - max-width: 100%; - padding: var(--pe-space-lg) 0; + max-width: var(--spacing-content, 976px); + margin: 0 auto; + padding: 24px 16px 64px; } -.back-button { - display: inline-flex; - align-items: center; - gap: var(--pe-space-sm); - padding: 8px 16px; - margin-bottom: var(--pe-space-lg); - background: var(--pe-surface); - border: 2px solid var(--pe-border); - border-radius: var(--pe-radius-md); - font-family: var(--pe-font-family); +.footer { + border-top: 1px solid var(--border); + padding: 24px 16px; + text-align: center; font-size: 0.875rem; - font-weight: 500; - color: var(--pe-text-secondary); - cursor: pointer; - transition: all var(--pe-transition-fast); + color: var(--muted-foreground); } -.back-button:hover { - border-color: var(--pe-accent); - color: var(--pe-accent); +.footer a { + color: var(--primary); + font-weight: 600; + text-decoration: none; } -/* Responsive Design */ -@media (max-width: 1024px) { - .scrollytelling-container { - grid-template-columns: 1fr; +.footer a:hover { + text-decoration: underline; +} + +.embedded .story, +.embedded .calculator-page { + padding-top: 0; +} + +@media (max-width: 640px) { + .header { + padding-top: 24px; + padding-bottom: 20px; } - .chart-sticky { - position: relative; - top: 0; - height: 400px; - margin-bottom: var(--pe-space-xl); + .header h1 { + font-size: 1.625rem; } - .text-column { - padding-bottom: var(--pe-space-2xl); + .subtitle { + font-size: 1rem; } -} -@media (max-width: 640px) { - .header h1 { + .story-section h2 { font-size: 1.25rem; } - .subtitle { - font-size: 0.875rem; + .story-prose p, + .story-prose ul { + font-size: 1rem; } - .household-info { - flex-direction: column; - align-items: flex-start; - gap: var(--pe-space-xs); + .story-figure { + padding: 12px; } - .chart-sticky { - height: 300px; - padding: var(--pe-space-md); + .page-tabs { + gap: 6px; + margin-top: 20px; + } + + .page-tab { + padding: 8px 14px; + font-size: 0.875rem; } } diff --git a/src/App.jsx b/src/App.jsx index dee304b..c66486d 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,184 +1,239 @@ -import { useState, useRef, useEffect } from "react"; -import HealthBenefitsChart from "./components/HealthBenefitsChart"; -import ScrollSection from "./components/ScrollSection"; -import CliffComparisonTable from "./components/CliffComparisonTable"; -import ContributionScheduleTable from "./components/ContributionScheduleTable"; +import { useState, useEffect, useLayoutEffect, useRef } from "react"; import ContributionScheduleChart from "./components/ContributionScheduleChart"; -import HouseholdExplorer from "./components/HouseholdExplorer"; +import ExampleHouseholdsTable from "./components/ExampleHouseholdsTable"; +import HouseholdYearTable from "./components/HouseholdYearTable"; +import PremiumChart from "./components/PremiumChart"; +import MarginalRateChart from "./components/MarginalRateChart"; import Calculator from "./components/Calculator"; +import Methodology from "./components/Methodology"; +import useActiveSection from "./components/useActiveSection"; +import useCenteredSticky from "./components/useCenteredSticky"; +import useMediaQuery from "./components/useMediaQuery"; +import { Reveal } from "./components/Motion"; import "./App.css"; -// Import precomputed household data +// Precomputed with policyengine-us: the Pennsylvania example across incomes +// (precompute_cliff_household.py), four example households +// (precompute_households.py) and the contribution schedules +// (precompute_contribution_schedules.py). The national estimates +// (precompute_national.py, national_impacts.json) are held off the page until +// they are validated. import cliffDemoData from "./data/households/cliff_demo.json"; +import examples from "./data/households/examples.json"; +import schedules from "./data/contribution_schedules.json"; + +const formatDollars = (value) => + new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(value); +const monthly = (annual) => formatDollars(annual / 12); +// The change between two annual amounts, per month, taken between the rounded +// monthly figures the page shows, so the text agrees with the table. +const monthlyChange = (from, to) => formatDollars(Math.round(to / 12) - Math.round(from / 12)); +// A scenario's monthly credit as the tables show it: the rounded premium less +// the rounded payment, so the premium, credit and payment in a sentence add up. +const monthlyCredit = (scenario) => + formatDollars(Math.round(scenario.slcsp / 12) - Math.round(scenario.net_premium / 12)); +const share = (value, digits = 1) => `${(100 * value).toFixed(digits)}%`; + +// The lowest and highest share of income a schedule charges where it gives a credit. +const rateRange = (key) => { + const rates = schedules.schedules[key].filter((rate) => rate !== null && rate > 0); + return [Math.min(...rates).toFixed(2), Math.max(...rates).toFixed(2)]; +}; + +function buildSections() { + const year = examples.year; + const priorYear = examples.prior_year; + const household = Object.fromEntries(examples.examples.map((example) => [example.key, example])); + const values = (key) => ({ + prior: household[key].scenarios[`current_${priorYear}`], + current: household[key].scenarios[`current_${year}`], + revived: household[key].scenarios[`hr1834_${year}`], + }); + const texas = values("texas_single"); + const florida = values("florida_family"); + const pennsylvania = values("pennsylvania_single"); + const california = values("california_couple"); + + const benchmarkChanges = examples.examples.map((example) => { + const { prior, current } = values(example.key); + return (100 * (current.slcsp - prior.slcsp)) / prior.slcsp; + }); + const [min2026, max2026] = rateRange(`current_${priorYear}`); + const [minNow, maxNow] = rateRange(`current_${year}`); + + // The two examples the story follows, below and above 400% FPL + // (HouseholdYearTable shows the same two). + const below = { ...texas, income: household.texas_single.income }; + const above = { ...pennsylvania, income: household.pennsylvania_single.income }; + const aboutFpl = (scenario, step) => Math.round(scenario.fpl_percent / step) * step; + const shareOfIncome = (value, income) => `${((100 * value) / income).toFixed(2)}%`; + const rise = (from, to) => `${monthlyChange(from, to)} (${((100 * (to - from)) / from).toFixed(1)}%)`; + + // The Pennsylvania example across incomes: where current law's credit ends, + // and where H.R. 1834's would: the income at which the enhanced schedule's + // top share (8.5%) reaches the benchmark premium, to the nearest $50. + const cliffIncome = 4 * cliffDemoData.fpl; + const enhancedCap = Math.max(...schedules.schedules.enhanced.filter((rate) => rate !== null)); + const revivedEnd = Math.round(pennsylvania.current.slcsp / (enhancedCap / 100) / 50) * 50; + + // The Pennsylvania adult's marginal tax rates in 2027: the share of each + // extra $1,000 of earnings lost to taxes and a smaller credit. + const incomes = cliffDemoData.income; + const median = (values) => { + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.floor(sorted.length / 2)]; + }; + const typicalRate = (rates, lowPercent, highPercent) => + 100 * + median( + rates.filter( + (_, i) => + incomes[i] >= (lowPercent / 100) * cliffDemoData.fpl && + incomes[i] <= (highPercent / 100) * cliffDemoData.fpl + ) + ); + // The step on the income axis that crosses 400% FPL. + const cliffStep = incomes.findIndex((value) => value > cliffIncome) - 1; + const creditLost = cliffDemoData.ptc_baseline[cliffStep] - cliffDemoData.ptc_baseline[cliffStep + 1]; + const netLost = + cliffDemoData.net_income_baseline[cliffStep] - cliffDemoData.net_income_baseline[cliffStep + 1]; + const cliffRate = 100 * cliffDemoData.mtr_baseline[cliffStep]; + // How much higher H.R. 1834's rate is than current law's between 400% FPL + // and the end of its credit. + const pointsHigher = typicalRate( + cliffDemoData.mtr_ira.map((rate, i) => rate - cliffDemoData.mtr_baseline[i]), + 420, + (100 * (revivedEnd - 2000)) / cliffDemoData.fpl + ); + + return [ + // PART 1: How the credits work + { + id: "how_credits_work", + title: "How premium tax credits work", + content: `The Affordable Care Act's **premium tax credits** (PTCs) reduce premiums for enrollees who purchase health insurance through the marketplace. + +The PTCs cap how much of their income enrollees are required to pay for a **benchmark health plan**—the second-lowest-cost silver plan (SLCSP) in their area. If the benchmark plan costs more than the required contribution, the government pays the difference as a tax credit. + +The chart shows the share of income a household pays for the benchmark plan under current law in ${year}: from **${minNow}%** to **${maxNow}%**. The credits are available from 100% to 400% of the federal poverty line (FPL). + +Households below 100% FPL don't qualify for the credits. In states that expanded Medicaid, adults with incomes up to 138% FPL qualify for Medicaid instead of a credit. In most non-expansion states, an adult without children earning less than 100% of the FPL falls in the **coverage gap**, where they qualify for neither Medicaid nor the PTCs.`, + chart: { type: "schedule", policies: [`current${year}`] }, + }, + { + id: "enhancements", + title: "The 2021–2025 enhancements", + content: `The American Rescue Plan Act (ARPA) of 2021 and the Inflation Reduction Act (IRA) of 2022 enhanced the subsidies from 2021 through 2025: +• Households paid **0%** of income for the benchmark plan up to 150% FPL +• No household paid more than **8.5%** of its income +• Credits reached incomes above 400% FPL, with no upper income limit + +They kept the 100% FPL floor. + +The chart compares the enhanced schedule with current law for ${year}.`, + chart: { type: "schedule", policies: [`current${year}`, "enhanced"] }, + }, + { + id: "expiration", + title: "The enhancements expired", + content: `The enhancements expired at the end of 2025. Under the original rules, which returned in 2026, enrollees pay a larger share of their income for the benchmark plan, and those above 400% FPL receive no credit. + +The IRS sets the shares each year: **${min2026}%** to **${max2026}%** of income in ${priorYear}, and **${minNow}%** to **${maxNow}%** in ${year}.`, + chart: { type: "schedule", policies: [`current${priorYear}`, `current${year}`] }, + }, + + // PART 2: A household facing the 2027 increase + { + id: "household_prior", + title: "Example: two households", + content: `Consider two single adults: a 40-year-old in Harris County, Texas, earning **${formatDollars(below.income)}** a year, about ${aboutFpl(below.current, 10)}% of the federal poverty line, and a ${cliffDemoData.household_info.age}-year-old in Lebanon County, Pennsylvania, earning **${formatDollars(above.income)}**, about ${aboutFpl(above.current, 50)}%. + +In ${priorYear} the Texas adult's benchmark plan costs ${monthly(below.prior.slcsp)}/month. Its credit of ${monthlyCredit(below.prior)}/month leaves it paying **${monthly(below.prior.net_premium)}/month**, ${shareOfIncome(below.prior.net_premium, below.income)} of its income. + +The Pennsylvania adult's benchmark plan costs ${monthly(above.prior.slcsp)}/month. Above 400% FPL, it receives no credit and pays the whole premium.`, + chart: { type: "household", columns: ["prior"] }, + }, + { + id: "household_current", + title: `${year}: premiums rise again`, + content: `For ${year}, both benchmark premiums rise: the Texas adult's by ${rise(below.prior.slcsp, below.current.slcsp)}, to ${monthly(below.current.slcsp)}/month, and the Pennsylvania adult's by ${rise(above.prior.slcsp, above.current.slcsp)}, to ${monthly(above.current.slcsp)}/month. + +Below 400% FPL, the credit absorbs the increase. The Texas adult's credit rises to ${monthlyCredit(below.current)}/month, so what it pays rises only ${monthlyChange(below.prior.net_premium, below.current.net_premium)}, to **${monthly(below.current.net_premium)}/month**, as its share of income moves from ${shareOfIncome(below.prior.net_premium, below.income)} to ${shareOfIncome(below.current.net_premium, below.income)}. + +Above 400% FPL, the Pennsylvania adult still receives no credit, so it pays the whole increase: **${monthly(above.current.net_premium)}/month**, ${share(above.current.net_premium / above.income, 0)} of its income. + +Lebanon County is in Pennsylvania's highest-cost rating area in the model's ${year} premium data. The model's benchmark premiums for ${priorYear} and ${year} come from KFF's premium data for each rating area.`, + chart: { type: "household", columns: ["prior", "current"] }, + }, + + // PART 3: Reviving the enhanced credits + { + id: "extension", + title: "What reviving the enhanced credits would do", + content: `Reviving the enhanced credits would bring back the 2021–2025 schedule unchanged. H.R. 1834 would do this for 2026 through 2028. It passed the House on January 8, 2026; it has not been enacted. + +Under H.R. 1834, neither household would pay more than 8.5% of its income for the benchmark plan in ${year}. The Texas adult would pay **${monthly(below.revived.net_premium)}/month**, against ${monthly(below.current.net_premium)} under current law. The Pennsylvania adult would pay **${monthly(above.revived.net_premium)}/month**, with a credit of ${monthlyCredit(above.revived)}/month, against ${monthly(above.current.net_premium)}/month and no credit under current law.`, + chart: { type: "household", columns: ["prior", "current", "revived"] }, + }, + { + id: "across_incomes", + title: "Across incomes", + content: `For a ${cliffDemoData.household_info.age}-year-old in Lebanon County, H.R. 1834 would lower the payment at every income above Pennsylvania's Medicaid limit (138% FPL) up to about **${formatDollars(revivedEnd)}**, where 8.5% of its income reaches the benchmark premium of ${formatDollars(pennsylvania.current.slcsp)} a year. + +Under current law the payment rises with income up to 400% FPL (${formatDollars(cliffIncome)}), then jumps to the full premium of ${monthly(pennsylvania.current.slcsp)}/month.`, + chart: { type: "premium", lines: ["prior", "current", "revived"] }, + }, + { + id: "marginal_rates", + title: "No cliff at 400% FPL", + content: `A household's **marginal tax rate** is the share of an extra dollar of earnings it loses to taxes and to a smaller credit. + +Under current law, the Pennsylvania adult's credit ends at 400% FPL (${formatDollars(cliffIncome)}). Earning ${formatDollars(incomes[cliffStep + 1] - incomes[cliffStep])} more, from ${formatDollars(incomes[cliffStep])} to ${formatDollars(incomes[cliffStep + 1])}, costs it ${formatDollars(creditLost)} of credit, so its net income falls by **${formatDollars(netLost)}**: a marginal tax rate of ${cliffRate.toFixed(0)}% on that ${formatDollars(incomes[cliffStep + 1] - incomes[cliffStep])}. + +Under H.R. 1834 there is no cliff. Above 400% FPL the household pays at most 8.5% of its income for the benchmark plan, so each extra dollar lowers its credit by 8.5 cents. Its marginal tax rate is **${pointsHigher.toFixed(1)} points higher** than under current law at each income from 400% FPL until the credit ends at about ${formatDollars(revivedEnd)}; beyond that, the two are the same.`, + chart: { type: "mtr" }, + }, + + // PART 4: Other households + { + id: "other_households", + title: "Four example households", + content: `Benchmark premiums rise in ${year} for each of four example households, by **${Math.min(...benchmarkChanges).toFixed(1)}%** to **${Math.max(...benchmarkChanges).toFixed(1)}%**. + +Besides the Texas and Pennsylvania adults, the Florida family of four earning ${formatDollars(household.florida_family.income)}, below 400% FPL, pays ${monthly(florida.current.net_premium)}/month for the benchmark plan in ${year}, against ${monthly(florida.prior.net_premium)} in ${priorYear}: its credit grows with the premium. + +The California couple in their 60s earning ${formatDollars(household.california_couple.income)}, just above 400% FPL, pays the whole premium, **${monthly(california.current.net_premium)}/month**: ${share(california.current.net_premium / household.california_couple.income, 0)} of its income. Like the Pennsylvania adult, it lives in its state's highest-cost rating area in the model's ${year} premium data. + +The table shows what each would pay under current law and under H.R. 1834.`, + chart: { type: "examples", view: "net" }, + }, + ]; +} + +const SECTIONS = buildSections(); -// Scroll sections content - background first, then household example, then health programs, then reforms -const SECTIONS = [ - // PART 1: Background on how ACA subsidies work - { - id: "intro", - title: "How ACA premium tax credits work", - content: `The Affordable Care Act (ACA) created **premium tax credits** to help Americans afford health insurance purchased through the marketplace. - -These credits work by capping how much of your income you're required to pay for a benchmark health plan—the **second-lowest cost silver plan (SLCSP)** in your area. - -If the benchmark plan costs more than your required contribution, the government pays the difference as a tax credit.`, - showContributionChart: true, - chartPolicies: ["baseline"], - }, - { - id: "arpa_ira", - title: "ARPA and IRA enhancements (2021–2025)", - content: `The **American Rescue Plan Act (ARPA)** of 2021 temporarily enhanced these subsidies. The **Inflation Reduction Act (IRA)** of 2022 extended them through 2025. - -Key changes: -• Removed the 400% FPL ceiling—credits available at any income -• Capped contributions at 8.5% of income for everyone -• Lowered contributions at every income level - -The chart shows how the IRA (blue) differs from the original ACA (gray).`, - showContributionChart: true, - chartPolicies: ["baseline", "ira"], - }, - { - id: "expiration", - title: "What happened in 2026", - content: `The ARPA/IRA enhancements **expired** at the end of 2025. - -The subsidy structure reverted to the **original ACA rules**: -• The 400% FPL ceiling returned -• Required contributions increased - -The baseline contribution schedule now requires **higher payments** and ends at 400% FPL—the "subsidy cliff."`, - showContributionChart: true, - chartPolicies: ["baseline"], - }, - - // PART 2: Household example - { - id: "example_intro", - title: "Example: a middle-income household", - content: `To illustrate the impact, consider a 45-year-old single adult in Lebanon County, Pennsylvania, earning **$104,200** a year—about **650% of the federal poverty level**. - -In 2025, under the IRA enhancements, this household: -• Paid **$963/month** for the benchmark plan (SLCSP) -• Received a **$242/month** tax credit -• Paid a net premium of **$720/month**`, - useCliffData: true, - showCliffTable: true, - showSlcsp: true, - showBaseline2026: false, - showReforms: false, - }, - { - id: "example_2026", - title: "2026: after expiration", - content: `In 2026, this household: - -**a) Faces a higher premium** for their benchmark plan: $1,003/month (up from $963/month, +4.2%) - -**b) Lost their subsidy** entirely: tax credit dropped from $242/month to **$0** because they exceed the 400% FPL ceiling - -Net premium rose from $720/month to **$1,003/month**—an increase of **$283/month (+39%)**.`, - useCliffData: true, - showCliffTable: true, - showSlcsp: true, - showBaseline2026: true, - showReforms: false, - }, - - // PART 3: Policy options for this household - { - id: "reform_options", - title: "Policy options", - content: `Two proposals were introduced in Congress: - -**IRA Extension:** Maintains the 8.5% cap structure -• Tax credit: **$265/month** → Net premium: **$738/month** - -**Bipartisan Health Insurance Affordability Act:** Introduced by Rep. Dunn (R-FL) and Rep. Schneider (D-IL) on December 9, 2025, this bill extends eligibility to 700% FPL with a 9.25% cap -• Tax credit: **$223/month** → Net premium: **$780/month**`, - useCliffData: true, - showCliffTable: true, - showSlcsp: false, - showReforms: true, - }, - - // PART 4: Health programs overview (using PA single adult) - { - id: "health_programs", - title: "The full picture: health coverage programs", - content: `Premium tax credits are one part of the health coverage landscape. Americans may also qualify for: - -• **Medicaid:** Free coverage for low-income households (eligibility varies by state) -• **Marketplace subsidies:** PTCs for those not eligible for other programs - -The chart shows how these programs interact across income levels for our Pennsylvania example.`, - useCliffData: true, - chartState: "all_programs", - }, - { - id: "medicaid", - title: "Medicaid coverage", - content: `**Medicaid** provides coverage for low-income Americans. Pennsylvania expanded Medicaid, so adults qualify up to **138% FPL**. - -For our 45-year-old, this means Medicaid covers incomes up to about $22,000. If they earn more, they may be eligible for premium tax credits (PTCs).`, - useCliffData: true, - chartState: "medicaid_focus", - }, - { - id: "reforms_chart", - title: "Premium tax credits under different policies", - content: `The chart shows premium tax credits across income levels under three scenarios: - -• **Gray line:** Baseline (post-IRA expiration) -• **Blue line:** IRA extension -• **Purple line:** Bipartisan Health Insurance Affordability Act - -The baseline drops to zero at 400% FPL. Both reform options continue providing credits at higher incomes.`, - useCliffData: true, - chartState: "both_reforms", - }, - { - id: "ira_impact_chart", - title: "IRA extension: the difference", - content: `The **blue shaded area** represents the additional premium tax credits available under the IRA extension compared to baseline. - -For this Pennsylvania household: -• Below 400% FPL: The IRA provides **lower required contributions** -• Above 400% FPL: The IRA provides **full subsidy access** where baseline provides none - -The size of the shaded area shows the dollar value of the difference at each income level.`, - useCliffData: true, - chartState: "ira_impact", - }, - - // PART 5: Household case studies - links to explorer - { - id: "explore_households", - title: "Explore different households", - content: `The impact of ACA policy changes varies by household type, location, and income level. - -Click below to explore how four different households are affected—with details on Medicaid expansion, CHIP eligibility, and the subsidy cliff for each.`, - useCliffData: true, - chartState: "both_reforms", - showHouseholdExplorerLink: true, - }, -]; - -// URL routing helpers +// URL routing helpers. The Explore Households page is gone; its old links +// open the Overview. const PAGE_ROUTES = { "": "main", "overview": "main", - "households": "households", + "households": "main", "calculator": "calculator", + "methodology": "methodology", }; const ROUTE_PAGES = { "main": "", - "households": "households", "calculator": "calculator", + "methodology": "methodology", }; +const ArrowIcon = () => ( + +); + function getPageFromHash() { if (typeof window === "undefined") { return "main"; @@ -197,17 +252,103 @@ function isEmbedded() { return urlParams.get("embedded") === "true"; } +// **bold** spans within a line. +function Inline({ text }) { + return text.split(/(\*\*[^*]+\*\*)/g).map((part, i) => + part.startsWith("**") && part.endsWith("**") ? {part.slice(2, -2)} : part + ); +} + +// A section's text: paragraphs split by blank lines; lines starting with "•" +// become a list. +function Prose({ content }) { + return content.split("\n\n").map((block, i) => { + const lines = block.split("\n"); + const bullets = lines.filter((line) => line.startsWith("•")); + if (!bullets.length) return

; + const lead = lines.filter((line) => !line.startsWith("•")).join(" "); + return ( +
+ {lead &&

} + +
+ ); + }); +} + +// `fill`: the chart fills the pinned card on wide screens. +function Chart({ chart, fill = false }) { + switch (chart.type) { + case "examples": + return ; + case "household": + return ; + case "schedule": + return ; + case "premium": + return ( + + ); + case "mtr": + return ( + + ); + default: + return null; + } +} + +// The story's parts, each opening with a heading, in the order the earlier +// version of the app told it: how the credits work, one household, a policy +// option, other households. +const PARTS = { + how_credits_work: "How the credits work", + household_prior: `Two households facing the ${examples.year} increase`, + extension: "Reviving the enhanced credits", + other_households: "Other households", +}; + function App() { - const [activeSection, setActiveSection] = useState(0); - const [currentPage, setCurrentPage] = useState(() => getPageFromHash()); - const [embedded] = useState(() => isEmbedded()); + // The page and the embed setting come from the address, which the server + // can't see. It renders the Overview, unembedded, and the browser switches + // to what the address asks for once it hydrates, so the two first renders + // match. + const [currentPage, setCurrentPage] = useState("main"); + const [calculatorKey, setCalculatorKey] = useState(0); + const [embedded, setEmbedded] = useState(false); + useLayoutEffect(() => { + setCurrentPage(getPageFromHash()); + setEmbedded(isEmbedded()); + }, []); + // The split layout's breakpoint (App.css): wide screens pin the chart. + const wide = useMediaQuery("(min-width: 1025px)"); + // The pinned chart stays in the middle of the screen. const chartRef = useRef(null); + useCenteredSticky(chartRef, wide && currentPage === "main"); + const activeId = useActiveSection(SECTIONS, currentPage === "main" && wide); + const activeSection = SECTIONS.find((section) => section.id === activeId) || SECTIONS[0]; // Sync URL hash with page state useEffect(() => { const handleHashChange = () => { const page = getPageFromHash(); setCurrentPage(page); + // A calculator link opened on the page (pasted, or with back and + // forward) starts the calculator over from that link. + if (window.location.hash.includes("?")) setCalculatorKey((key) => key + 1); }; window.addEventListener("hashchange", handleHashChange); @@ -234,86 +375,60 @@ function App() { window.scrollTo(0, 0); }, [currentPage]); - // Get current section - const currentSection = SECTIONS[activeSection] || SECTIONS[0]; - - // Handle section visibility changes - const handleSectionInView = (index) => { - setActiveSection(index); - }; - - // Determine what to show in the chart area - const renderChartArea = () => { - if (currentSection.showContributionChart) { - return ( - - ); - } - if (currentSection.showContributionSchedule) { - return ( - - ); - } - if (currentSection.showCliffTable) { - return ( - - ); - } - return ( - - ); - }; - - // Render the main scrolly page + // The Overview, as the earlier version of the app laid it out: on wide + // screens the active section's chart stays pinned on the left while the + // text scrolls past in cards on the right; on narrower screens, one column + // with each chart under its text. const renderMainPage = () => ( - <> -
-
-
- {renderChartArea()} +
+
+ {wide && ( +
+
+
+ +
+
-
- -
- {SECTIONS.map((section, index) => ( - + {SECTIONS.map((section) => ( +
navigateToPage("households")} - /> + id={section.id} + className={`story-section scroll-card${wide && section.id === activeSection.id ? " active" : ""}`} + > + {PARTS[section.id] &&

{PARTS[section.id]}

} +

{section.title}

+
+ +
+ {!wide && section.chart && ( + + + + )} +
))} -
-
- - ); - - // Render the households explorer page - const renderHouseholdsPage = () => ( -
- -
+
+ + +
+ + + ); // Render the calculator page const renderCalculatorPage = () => (
- +
); @@ -322,9 +437,9 @@ function App() { {!embedded && (
-

ACA Premium Tax Credits: 2025 vs 2026

+

ACA Premium Tax Credits

- Modeling how the scheduled expiration of IRA enhancements affects health insurance costs + How 2027 premiums change under current law, and what reviving the enhanced credits would do

- +
)} {currentPage === "main" && renderMainPage()} - {currentPage === "households" && renderHouseholdsPage()} {currentPage === "calculator" && renderCalculatorPage()} + {currentPage === "methodology" && navigateToPage("calculator")} />} {!embedded && (