diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 19ff7d1..0000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "Python 3", - // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile - "image": "mcr.microsoft.com/devcontainers/python:1-3.11-bookworm", - "customizations": { - "codespaces": { - "openFiles": [ - "README.md", - "app.py" - ] - }, - "vscode": { - "settings": {}, - "extensions": [ - "ms-python.python", - "ms-python.vscode-pylance" - ] - } - }, - "updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y 0: - max_income_with_ptc = income_range[i] - break - x_axis_max = min(1000000, max_income_with_ptc * 1.1) - - delta_range = ptc_range_reform - ptc_range_baseline - - # TODO: Implement full chart creation - # For now, return None to keep refactoring incremental - return None, None, None, income_range, ptc_range_baseline, ptc_range_reform, 0, 0, x_axis_max - - except Exception as e: - raise Exception(f"Chart creation error: {str(e)}") from e diff --git a/aca_calc/calculations/ptc.py b/aca_calc/calculations/ptc.py deleted file mode 100644 index 644cba2..0000000 --- a/aca_calc/calculations/ptc.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Premium Tax Credit calculation functions.""" - -import copy -from policyengine_us import Simulation - -from aca_calc.calculations.household import build_household_situation -from aca_calc.calculations.reforms import create_enhanced_ptc_reform - - -def calculate_ptc( - age_head, - age_spouse, - income, - dependent_ages, - state, - county_name=None, - zip_code=None, - use_reform=False, -): - """Calculate PTC for baseline or IRA enhanced scenario using 2026 comparison. - - Args: - age_head: Age of head of household - age_spouse: Age of spouse (None if not married) - income: Annual household income - dependent_ages: List of dependent ages - state: Two-letter state code - county_name: County name (e.g., "Travis County") - zip_code: 5-digit ZIP code (required for LA County) - use_reform: If True, use enhanced PTC reform - - Returns: - tuple: (ptc, slcsp, fpl, fpl_pct) - """ - try: - # Build base household situation - situation = build_household_situation( - age_head=age_head, - age_spouse=age_spouse, - dependent_ages=dependent_ages, - state=state, - county=county_name, - zip_code=zip_code, - year=2026, - with_axes=False, - ) - - # Deep copy and inject income - sit = copy.deepcopy(situation) - - # Split income between adults if married - if age_spouse: - sit["people"]["you"]["employment_income"] = {2026: income / 2} - sit["people"]["your partner"]["employment_income"] = { - 2026: income / 2 - } - else: - sit["people"]["you"]["employment_income"] = {2026: income} - - # Create reform if requested - reform = create_enhanced_ptc_reform() if use_reform else None - - # Run simulation - sim = Simulation(situation=sit, reform=reform) - - ptc = sim.calculate("aca_ptc", map_to="household", period=2026)[0] - slcsp = sim.calculate("slcsp", map_to="household", period=2026)[0] - fpl = sim.calculate("tax_unit_fpg", period=2026)[0] - aca_magi_fraction = sim.calculate("aca_magi_fraction", period=2026)[0] - fpl_pct = aca_magi_fraction * 100 - - return float(max(0, ptc)), float(slcsp), float(fpl), float(fpl_pct) - - except Exception as e: - raise Exception(f"PTC calculation error: {str(e)}") from e diff --git a/app.py b/app.py deleted file mode 100644 index 5b74e71..0000000 --- a/app.py +++ /dev/null @@ -1,929 +0,0 @@ -""" -ACA Health Coverage Interactive Story -====================================== -A scrollytelling experience explaining how ACA premium tax credits work -and how proposed reforms would affect different households. - -Uses precomputed PolicyEngine US simulation data for instant loading. -""" - -import streamlit as st -import numpy as np -import json -import os -from pathlib import Path -import plotly.graph_objects as go -import base64 - -st.set_page_config( - page_title="Understanding ACA Health Coverage Reforms", - layout="wide", - initial_sidebar_state="collapsed", -) - -# ============================================================================ -# Design Tokens (PolicyEngine App V2 Style) -# ============================================================================ - -COLORS = { - # Primary brand - teal - "primary": "#319795", - "primary_light": "#4FD1C5", - "primary_dark": "#285E61", - - # Secondary - gray scale - "gray_50": "#F9FAFB", - "gray_100": "#F2F4F7", - "gray_200": "#E2E8F0", - "gray_300": "#D1D5DB", - "gray_400": "#9CA3AF", - "gray_500": "#6B7280", - "gray_600": "#4B5563", - "gray_700": "#344054", - "gray_800": "#1F2937", - "gray_900": "#101828", - - # Semantic - "success": "#22C55E", - "warning": "#FEC601", - "error": "#EF4444", - - # Chart colors - "baseline": "#9CA3AF", # Gray for baseline/current law - "ira_reform": "#2C6496", # Blue for IRA extension - "bipartisan_reform": "#9467BD", # Purple for 700% FPL - "medicaid": "#319795", # Teal for Medicaid - "chip": "#38B2AC", # Lighter teal for CHIP - - # Text - "text_primary": "#000000", - "text_secondary": "#5A5A5A", - - # Background - "bg_primary": "#FFFFFF", - "bg_secondary": "#F5F9FF", -} - -FONTS = { - "primary": "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif", - "body": "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif", -} - -# ============================================================================ -# Preset Households -# ============================================================================ - -PRESET_HOUSEHOLDS = { - "tampa_family": { - "name": "Tampa 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_single": { - "name": "Single Adult in Texas", - "description": "A single 35-year-old in Harris County, Texas", - "age_head": 35, - "age_spouse": None, - "dependent_ages": [], - "state": "TX", - "county": "Harris County", - "is_expansion_state": False, - "key_insight": "Texas didn't expand Medicaid. Single 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.", - }, -} - -# ============================================================================ -# Scroll Section Content -# ============================================================================ - -SCROLL_SECTIONS = [ - { - "id": "intro", - "title": "Health Coverage in America", - "content": """ - Health insurance coverage in America is a patchwork of programs: **Medicaid** for low-income - households, **CHIP** for children, and **marketplace plans** with premium tax credits (PTCs) - for those who don't qualify for other coverage. - - The Affordable Care Act's premium tax credits help make marketplace coverage affordable, but - they're set to change dramatically in 2026 when current enhancements expire. - - **Scroll to explore how these programs work and how proposed reforms would affect real families.** - """, - "chart_state": "all_programs", - "highlight": None, - }, - { - "id": "medicaid", - "title": "Medicaid: The Foundation", - "content": """ - **Medicaid** provides free or low-cost coverage for low-income Americans. But eligibility - varies dramatically by state. - - In **expansion states** (like California and New York), adults qualify up to **138% of the - Federal Poverty Level (FPL)**. - - In **non-expansion states** (like Florida and Texas), parents may only qualify up to - **~32% FPL**, and childless adults often don't qualify at all—regardless of how low - their income is. - - This creates the infamous **"coverage gap"**: people too poor for subsidies but not - poor enough for Medicaid. - """, - "chart_state": "medicaid_focus", - "highlight": "medicaid", - }, - { - "id": "chip", - "title": "CHIP: Children's Coverage", - "content": """ - The **Children's Health Insurance Program (CHIP)** covers children in families with - incomes too high for Medicaid but who can't afford private insurance. - - CHIP eligibility extends much higher than adult Medicaid—typically up to **200-300% FPL** - depending on the state. - - This means in many families, children have coverage through CHIP while parents must - find other options. - """, - "chart_state": "chip_focus", - "highlight": "chip", - }, - { - "id": "ptc_basics", - "title": "Premium Tax Credits: How They Work", - "content": """ - **Premium Tax Credits** help pay for marketplace health insurance. The credit equals - the difference between: - - - The cost of the **benchmark plan** (second-lowest-cost Silver plan in your area) - - Your **required contribution** (a percentage of your income) - - The lower your income, the lower your required contribution percentage, and the - larger your tax credit. - - Currently, PTCs are available from **100% to 400% FPL** under baseline law. - """, - "chart_state": "ptc_baseline", - "highlight": "ptc_baseline", - }, - { - "id": "the_cliff", - "title": "The 400% FPL Cliff", - "content": """ - Under current law (after IRA enhancements expire), premium tax credits **completely - disappear** at 400% of the Federal Poverty Level. - - This creates a brutal "**subsidy cliff**" where earning just one more dollar can cost - a family **thousands** in lost subsidies. - - For a family of four, this cliff hits at around **$124,800** in 2026. - - Watch how the gray baseline line drops to zero—this is the cliff millions of - Americans face. - """, - "chart_state": "cliff_focus", - "highlight": "cliff", - }, - { - "id": "ira_extension", - "title": "The IRA Extension", - "content": """ - The **Inflation Reduction Act** enhanced premium tax credits through 2025, but these - enhancements are set to expire. - - **Extending the IRA subsidies** would: - - - **Eliminate the 400% FPL cliff** entirely - - **Cap contributions at 8.5%** of income for everyone - - Provide credits to households **at any income level** above 400% FPL - - The **blue line** shows how much more generous this is compared to baseline. - """, - "chart_state": "ira_reform", - "highlight": "ira", - }, - { - "id": "bipartisan_bill", - "title": "The Bipartisan Health Insurance Affordability Act", - "content": """ - A bipartisan group of lawmakers has proposed an alternative: the **Bipartisan Health - Insurance Affordability Act**. - - This bill would: - - - Extend eligibility to **700% FPL** (not unlimited like IRA) - - Use a different contribution schedule topping out at **9.25%** - - Create a **gradual phase-out** rather than a cliff - - The **purple line** shows this alternative. It's less generous than the IRA extension - at high incomes, but still far better than baseline. - """, - "chart_state": "both_reforms", - "highlight": "bipartisan", - }, - { - "id": "impact", - "title": "The Impact: Who Benefits?", - "content": """ - Both reforms primarily benefit households in the **middle-income range**—those earning - between 200% and 600% of FPL. - - For our example households: - - - **Younger families** see modest but meaningful gains - - **Older households** (like our California couple) see the largest dollar benefits - because their premiums are higher - - **Everyone above 400% FPL** benefits from cliff elimination - - The chart now shows the **change in net income**—the total benefit from reform. - """, - "chart_state": "impact", - "highlight": "impact", - }, - { - "id": "your_turn", - "title": "See How It Affects You", - "content": """ - Every household's situation is different. Your age, location, family size, and - income all affect your premium tax credits. - - **Try our calculator** to see exactly how these reforms would affect your family: - - 👉 [Open the ACA Calculator](/calc) - - Or explore the example households above to understand the patterns. - """, - "chart_state": "both_reforms", - "highlight": None, - }, -] - -# ============================================================================ -# Data Loading Functions -# ============================================================================ - -# Path to precomputed household data -DATA_DIR = Path(__file__).parent / "data" / "households" - - -@st.cache_data -def load_household_data(household_key): - """Load precomputed household data from JSON file. - - Data is precomputed by running: python precompute_households.py - This avoids expensive PolicyEngine simulations on page load. - """ - json_file = DATA_DIR / f"{household_key}.json" - - if json_file.exists(): - with open(json_file, "r") as f: - return json.load(f) - else: - st.error(f"Precomputed data not found for {household_key}. Run `python precompute_households.py` to generate.") - return None - - -@st.cache_data -def load_all_household_data(): - """Load all precomputed household data at once.""" - combined_file = DATA_DIR / "all_households.json" - - if combined_file.exists(): - with open(combined_file, "r") as f: - return json.load(f) - else: - # Fall back to loading individual files - all_data = {} - for key in PRESET_HOUSEHOLDS.keys(): - data = load_household_data(key) - if data: - all_data[key] = data - return all_data - - -def create_chart(data, chart_state, highlight=None): - """Create a Plotly chart based on the current scroll state.""" - income = np.array(data["income"]) - fpl = data["fpl"] - - fig = go.Figure() - - # Determine x-axis range - if chart_state == "cliff_focus": - x_max = fpl * 5 # Show up to 500% FPL for cliff focus - else: - # Find where PTCs end - ptc_ira = np.array(data["ptc_ira"]) - last_nonzero = np.where(ptc_ira > 0)[0] - x_max = income[last_nonzero[-1]] * 1.1 if len(last_nonzero) > 0 else 200000 - x_max = min(x_max, 300000) - - # Common layout settings - layout_kwargs = dict( - height=500, - plot_bgcolor="white", - paper_bgcolor="white", - font=dict(family=FONTS["body"], size=14), - margin=dict(l=80, r=40, t=60, b=80), - xaxis=dict( - tickformat="$,.0f", - range=[0, x_max], - gridcolor=COLORS["gray_200"], - title="Household Income", - title_font=dict(size=14, color=COLORS["text_secondary"]), - ), - yaxis=dict( - tickformat="$,.0f", - gridcolor=COLORS["gray_200"], - rangemode="tozero", - title_font=dict(size=14, color=COLORS["text_secondary"]), - ), - legend=dict( - orientation="h", - yanchor="bottom", - y=1.02, - xanchor="right", - x=1, - font=dict(size=12), - ), - hovermode="x unified", - ) - - # Add FPL markers as vertical lines - fpl_markers = [ - (1.0, "100% FPL"), - (1.38, "138% FPL"), - (4.0, "400% FPL"), - (7.0, "700% FPL"), - ] - - for mult, label in fpl_markers: - fpl_income = fpl * mult - if fpl_income < x_max: - fig.add_vline( - x=fpl_income, - line_dash="dot", - line_color=COLORS["gray_300"], - line_width=1, - annotation_text=label, - annotation_position="top", - annotation_font_size=10, - annotation_font_color=COLORS["gray_500"], - ) - - # Build traces based on chart state - if chart_state in ["all_programs", "medicaid_focus", "chip_focus"]: - # Show all health programs - medicaid = np.array(data["medicaid"]) - chip = np.array(data["chip"]) - ptc_baseline = np.array(data["ptc_baseline"]) - - # Medicaid trace - opacity = 1.0 if chart_state == "medicaid_focus" or highlight == "medicaid" else 0.7 - fig.add_trace(go.Scatter( - x=income, y=medicaid, - mode="lines", - name="Medicaid", - line=dict(color=COLORS["medicaid"], width=3 if opacity == 1.0 else 2), - opacity=opacity, - )) - - # CHIP trace (if any children) - if np.any(chip > 0): - opacity = 1.0 if chart_state == "chip_focus" or highlight == "chip" else 0.7 - fig.add_trace(go.Scatter( - x=income, y=chip, - mode="lines", - name="CHIP", - line=dict(color=COLORS["chip"], width=3 if opacity == 1.0 else 2), - opacity=opacity, - )) - - # PTC baseline - fig.add_trace(go.Scatter( - x=income, y=ptc_baseline, - mode="lines", - name="Premium Tax Credit (Baseline)", - line=dict(color=COLORS["baseline"], width=2), - opacity=0.7, - )) - - layout_kwargs["yaxis"]["title"] = "Annual Benefit Value" - layout_kwargs["title"] = dict( - text="Health Coverage Programs by Income", - font=dict(size=20, color=COLORS["primary"]), - ) - - elif chart_state in ["ptc_baseline", "cliff_focus"]: - # Focus on PTC baseline and the cliff - ptc_baseline = np.array(data["ptc_baseline"]) - - fig.add_trace(go.Scatter( - x=income, y=ptc_baseline, - mode="lines", - name="PTC (Current Law after 2025)", - line=dict(color=COLORS["baseline"], width=3), - fill="tozeroy", - fillcolor="rgba(156, 163, 175, 0.2)", - )) - - # Add cliff annotation - if chart_state == "cliff_focus": - cliff_income = fpl * 4 - fig.add_annotation( - x=cliff_income, - y=0, - text="THE CLIFF
Credits drop to $0", - showarrow=True, - arrowhead=2, - arrowcolor=COLORS["error"], - ax=0, - ay=-60, - bgcolor=COLORS["error"], - font=dict(color="white", size=12), - borderpad=8, - ) - - layout_kwargs["yaxis"]["title"] = "Annual Premium Tax Credit" - layout_kwargs["title"] = dict( - text="Premium Tax Credits Under Current Law", - font=dict(size=20, color=COLORS["primary"]), - ) - - elif chart_state == "ira_reform": - # Show baseline vs IRA reform - ptc_baseline = np.array(data["ptc_baseline"]) - ptc_ira = np.array(data["ptc_ira"]) - - fig.add_trace(go.Scatter( - x=income, y=ptc_baseline, - mode="lines", - name="Baseline (Current Law)", - line=dict(color=COLORS["baseline"], width=2), - )) - - fig.add_trace(go.Scatter( - x=income, y=ptc_ira, - mode="lines", - name="IRA Extension", - line=dict(color=COLORS["ira_reform"], width=3), - fill="tonexty", - fillcolor="rgba(44, 100, 150, 0.2)", - )) - - layout_kwargs["yaxis"]["title"] = "Annual Premium Tax Credit" - layout_kwargs["title"] = dict( - text="IRA Extension vs Current Law", - font=dict(size=20, color=COLORS["primary"]), - ) - - elif chart_state == "both_reforms": - # Show all three scenarios - ptc_baseline = np.array(data["ptc_baseline"]) - ptc_ira = np.array(data["ptc_ira"]) - ptc_700fpl = np.array(data["ptc_700fpl"]) if data["ptc_700fpl"] else None - - fig.add_trace(go.Scatter( - x=income, y=ptc_baseline, - mode="lines", - name="Baseline", - line=dict(color=COLORS["baseline"], width=2), - )) - - fig.add_trace(go.Scatter( - x=income, y=ptc_ira, - mode="lines", - name="IRA Extension", - line=dict(color=COLORS["ira_reform"], width=3), - )) - - if ptc_700fpl is not None: - fig.add_trace(go.Scatter( - x=income, y=ptc_700fpl, - mode="lines", - name="Bipartisan 700% FPL", - line=dict(color=COLORS["bipartisan_reform"], width=3), - )) - - layout_kwargs["yaxis"]["title"] = "Annual Premium Tax Credit" - layout_kwargs["title"] = dict( - text="Comparing Reform Options", - font=dict(size=20, color=COLORS["primary"]), - ) - - elif chart_state == "impact": - # Show change in net income - net_baseline = np.array(data["net_income_baseline"]) - net_ira = np.array(data["net_income_ira"]) - net_700fpl = np.array(data["net_income_700fpl"]) if data["net_income_700fpl"] else None - - delta_ira = net_ira - net_baseline - delta_700fpl = net_700fpl - net_baseline if net_700fpl is not None else None - - fig.add_trace(go.Scatter( - x=income, y=delta_ira, - mode="lines", - name="Gain from IRA Extension", - line=dict(color=COLORS["ira_reform"], width=3), - fill="tozeroy", - fillcolor="rgba(44, 100, 150, 0.2)", - )) - - if delta_700fpl is not None: - fig.add_trace(go.Scatter( - x=income, y=delta_700fpl, - mode="lines", - name="Gain from Bipartisan Bill", - line=dict(color=COLORS["bipartisan_reform"], width=3), - )) - - # Add zero line - fig.add_hline(y=0, line_color=COLORS["gray_400"], line_width=1) - - layout_kwargs["yaxis"]["title"] = "Change in Annual Net Income" - layout_kwargs["title"] = dict( - text="Impact of Reform on Household Finances", - font=dict(size=20, color=COLORS["primary"]), - ) - - fig.update_layout(**layout_kwargs) - return fig - - -# ============================================================================ -# Custom CSS for Scrollytelling Layout -# ============================================================================ - -def inject_custom_css(): - st.markdown(""" - - """, unsafe_allow_html=True) - - -# ============================================================================ -# Main App -# ============================================================================ - -def main(): - inject_custom_css() - - # Header - st.markdown('

Understanding ACA Health Coverage Reforms

', unsafe_allow_html=True) - st.markdown('

An interactive guide to how premium tax credits work and what\'s at stake in 2026

', unsafe_allow_html=True) - - # Household selector - st.markdown("### Select an Example Household") - - cols = st.columns(len(PRESET_HOUSEHOLDS)) - selected_household = st.session_state.get("selected_household", "tampa_family") - - for i, (key, household) in enumerate(PRESET_HOUSEHOLDS.items()): - with cols[i]: - is_selected = key == selected_household - button_type = "primary" if is_selected else "secondary" - if st.button( - household["name"], - key=f"btn_{key}", - type=button_type, - use_container_width=True, - ): - st.session_state.selected_household = key - st.rerun() - - # Show household info - household = PRESET_HOUSEHOLDS[selected_household] - st.markdown(f""" -
-

{household['name']}

-

{household['description']}

-
-

Key insight: {household['key_insight']}

-
-
- """, unsafe_allow_html=True) - - # Load precomputed data for selected household - data = load_household_data(selected_household) - - if data is None: - st.stop() - - # Two-column layout: scrollable text on right, sticky chart on left - chart_col, text_col = st.columns([3, 2]) - - # Track current section - current_section = st.session_state.get("current_section", 0) - - with text_col: - # Progress indicator - progress_html = '
' - for i in range(len(SCROLL_SECTIONS)): - if i < current_section: - progress_html += '
' - elif i == current_section: - progress_html += '
' - else: - progress_html += '
' - progress_html += '
' - st.markdown(progress_html, unsafe_allow_html=True) - - # Navigation buttons - nav_cols = st.columns([1, 3, 1]) - with nav_cols[0]: - if current_section > 0: - if st.button("← Back", use_container_width=True): - st.session_state.current_section = current_section - 1 - st.rerun() - with nav_cols[2]: - if current_section < len(SCROLL_SECTIONS) - 1: - if st.button("Next →", use_container_width=True, type="primary"): - st.session_state.current_section = current_section + 1 - st.rerun() - - # Current section content - section = SCROLL_SECTIONS[current_section] - st.markdown(f"### {section['title']}") - st.markdown(section['content']) - - # Link to calculator on last section - if section['id'] == 'your_turn': - st.markdown("---") - if st.button("🧮 Open the Full Calculator", type="primary", use_container_width=True): - st.switch_page("pages/calculator.py") - - with chart_col: - # Create and display chart based on current section - section = SCROLL_SECTIONS[current_section] - fig = create_chart(data, section['chart_state'], section.get('highlight')) - st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False}) - - # Show key metrics below chart - if section['chart_state'] in ['ira_reform', 'both_reforms', 'impact']: - fpl = data['fpl'] - - # Calculate key values at 400% FPL - income_arr = np.array(data['income']) - idx_400fpl = np.argmin(np.abs(income_arr - fpl * 4)) - - ptc_baseline = data['ptc_baseline'][idx_400fpl] - ptc_ira = data['ptc_ira'][idx_400fpl] - ptc_700 = data['ptc_700fpl'][idx_400fpl] if data['ptc_700fpl'] else 0 - - metric_cols = st.columns(3) - with metric_cols[0]: - st.metric( - "At 400% FPL", - f"${fpl * 4:,.0f}", - help="Income at 400% of Federal Poverty Level" - ) - with metric_cols[1]: - st.metric( - "Baseline PTC", - f"${ptc_baseline:,.0f}", - help="Premium tax credit under current law" - ) - with metric_cols[2]: - reform_value = ptc_ira if section['chart_state'] != 'both_reforms' else max(ptc_ira, ptc_700) - gain = reform_value - ptc_baseline - st.metric( - "With Reform", - f"${reform_value:,.0f}", - f"+${gain:,.0f}" if gain > 0 else None, - ) - - -if __name__ == "__main__": - main() diff --git a/app_backup.py b/app_backup.py deleted file mode 100644 index b21bee1..0000000 --- a/app_backup.py +++ /dev/null @@ -1,1414 +0,0 @@ -""" -ACA Premium Tax Credit Calculator -================================== -Explore how extending enhanced premium tax credits would affect your household. - -This app calculates ACA premium tax credits under two scenarios: -1. Current law: Enhanced PTCs expire after 2025 -2. Extended: Enhanced PTCs extended to 2026 - -Uses PolicyEngine US for accurate tax-benefit microsimulation. -""" - -import streamlit as st - -try: - import pandas as pd - import numpy as np - import json - import gc - from policyengine_us import Simulation - import plotly.graph_objects as go - import base64 - - # Import calculation functions from package - from aca_calc.calculations.ptc import calculate_ptc - from aca_calc.calculations.household import build_household_situation - from aca_calc.calculations.reforms import create_enhanced_ptc_reform, create_700fpl_reform - - # Try to import reform capability - try: - from policyengine_core.reforms import Reform - - REFORM_AVAILABLE = True - except ImportError: - REFORM_AVAILABLE = False - - st.set_page_config( - page_title="Enhanced ACA Subsidies Calculator", - layout="wide", - initial_sidebar_state="expanded", - ) - -except Exception as e: - st.error(f"Startup Error: {str(e)}") - st.error("Please report this error with the details above.") - import traceback - - st.code(traceback.format_exc()) - st.stop() - - -# Load PolicyEngine logo -def get_logo_base64(): - """Load PolicyEngine logo and convert to base64""" - try: - with open("blue.png", "rb") as f: - return base64.b64encode(f.read()).decode() - except: - return None - - -# Load counties from PolicyEngine data -@st.cache_data -def load_counties(): - try: - with open("counties.json", "r") as f: - return json.load(f) - except: - return None - - -# PolicyEngine brand colors -COLORS = { - "primary": "#2C6496", # Blue for extension/reform - "secondary": "#39C6C0", - "green": "#28A745", - "gray": "#BDBDBD", # Medium light gray for baseline (matches policyengine-app) - "blue_gradient": ["#D1E5F0", "#92C5DE", "#2166AC", "#053061"], -} - - -def get_logo_base64(): - """Get base64 encoded PolicyEngine logo""" - try: - with open("blue.png", "rb") as f: - return base64.b64encode(f.read()).decode() - except: - return None - - -def add_logo_to_layout(): - """Add PolicyEngine logo to chart layout (matches policyengine-app positioning)""" - logo_base64 = get_logo_base64() - if logo_base64: - return { - "images": [ - { - "source": f"data:image/png;base64,{logo_base64}", - "xref": "paper", - "yref": "paper", - "x": 1.01, - "y": -0.18, - "sizex": 0.10, - "sizey": 0.10, - "xanchor": "right", - "yanchor": "bottom", - } - ] - } - return {} - - -def main(): - # Header with PolicyEngine branding - st.markdown( - f""" - - """, - unsafe_allow_html=True, - ) - - st.title("How would extending enhanced subsidies affect you?") - - counties = load_counties() - - # Sidebar for household configuration - with st.sidebar: - st.header("Reform scenarios") - st.markdown("Select which reform(s) to compare against baseline:") - - show_ira = st.checkbox( - "IRA Extension", - value=True, - help="Extends current enhanced subsidies indefinitely with 8.5% cap and no income limit above 400% FPL" - ) - - show_700fpl = st.checkbox( - "700% FPL Extension (Bipartisan Bill)", - value=False, - help="Bipartisan Health Insurance Affordability Act: extends eligibility to 700% FPL with 9.25% cap" - ) - - if not show_ira and not show_700fpl: - st.warning("Please select at least one reform to compare.") - - st.markdown("---") - - st.header("Household configuration") - - married = st.checkbox("Are you married?", value=False) - - age_head = st.number_input( - "How old are you?", min_value=18, max_value=100, value=35 - ) - - if married: - age_spouse = st.number_input( - "How old is your spouse?", - min_value=18, - max_value=100, - value=35, - ) - else: - age_spouse = None - - num_dependents = st.number_input( - "How many children or dependents do you have?", - min_value=0, - max_value=10, - value=0, - ) - dependent_ages = [] - - if num_dependents > 0: - st.write("What are their ages?") - for i in range(num_dependents): - age_dep = st.number_input( - f"Child {i+1} age", - min_value=0, - max_value=25, - value=10, - key=f"dep_{i}", - ) - dependent_ages.append(age_dep) - - states = [ - "AL", - "AK", - "AZ", - "AR", - "CA", - "CO", - "CT", - "DE", - "FL", - "GA", - "HI", - "ID", - "IL", - "IN", - "IA", - "KS", - "KY", - "LA", - "ME", - "MD", - "MA", - "MI", - "MN", - "MS", - "MO", - "MT", - "NE", - "NV", - "NH", - "NJ", - "NM", - "NY", - "NC", - "ND", - "OH", - "OK", - "OR", - "PA", - "RI", - "SC", - "SD", - "TN", - "TX", - "UT", - "VT", - "VA", - "WA", - "WV", - "WI", - "WY", - "DC", - ] - - state = st.selectbox( - "Which state do you live in?", states, index=0 - ) # Default to AL - - # County selection - auto-select first alphabetically - county = None - if counties and state in counties: - sorted_counties = sorted(counties[state]) - county = st.selectbox( - "Which county?", - sorted_counties, - index=0, - help="County used for marketplace calculations", - ) - - # ZIP code input - required for LA County - zip_code = None - if state == "CA" and county == "Los Angeles County": - zip_code = st.text_input( - "What is your ZIP code?", - max_chars=5, - help="Los Angeles County has multiple rating areas. ZIP code is required for accurate premium calculations.", - placeholder="90001", - ) - if zip_code and (len(zip_code) != 5 or not zip_code.isdigit()): - st.error("Please enter a valid 5-digit ZIP code") - zip_code = None - - st.markdown("---") - - calculate_button = st.button( - "Analyze premium subsidies", - type="primary", - use_container_width=True, - ) - - if calculate_button: - st.session_state.calculate = True - new_params = { - "age_head": age_head, - "age_spouse": age_spouse, - "dependent_ages": dependent_ages, - "state": state, - "county": county, - "married": married, - "zip_code": zip_code, - "show_ira": show_ira, - "show_700fpl": show_700fpl, - } - # Clear cached charts if params changed - if hasattr(st.session_state, "params") and st.session_state.params != new_params: - st.session_state.income_range = None - st.session_state.fig_net_income = None - st.session_state.fig_mtr = None - st.session_state.params = new_params - - # Main content area - if not hasattr(st.session_state, "calculate") or not st.session_state.calculate: - # Show instructional text when first loading - st.markdown( - """ - ### Get started - - Enter your household information in the sidebar, then click **"Analyze premium subsidies"** to see: - - - How premium tax credits vary across income levels for your household - - The income range where extending enhanced subsidies would benefit you - - Your specific impact at any income level you choose - - **Available reform scenarios:** - - **IRA Extension**: Continues current enhanced subsidies with 8.5% cap and no income limit - - **700% FPL Extension**: [Bipartisan Health Insurance Affordability Act](https://punchbowl.news/wp-content/uploads/Bipartisan-Health-Insurance-Affordability-Act-Section-by-Section-copy.pdf) extending eligibility to 700% FPL with 9.25% cap - - Select one or both reforms in the sidebar to compare against baseline (current law after IRA expiration). - """ - ) - else: - params = st.session_state.params - - # Generate charts only if not already in session state (avoid recalculation) - if not hasattr(st.session_state, "income_range") or st.session_state.income_range is None: - with st.spinner("Generating analysis..."): - county_name = params["county"] if params["county"] else None - zip_code = params.get("zip_code") - - ( - fig_comparison, - fig_delta, - benefit_info, - income_range, - ptc_baseline_range, - ptc_reform_range, - ptc_700fpl_range, - slcsp_2026, - fpl, - x_axis_max, - ) = create_chart( - params["age_head"], - params["age_spouse"], - tuple(params["dependent_ages"]), - params["state"], - county_name, - zip_code, - show_ira=params.get("show_ira", True), - show_700fpl=params.get("show_700fpl", False), - ) - - # Store arrays and charts in session state for later use - if income_range is not None: - st.session_state.income_range = income_range - st.session_state.ptc_baseline_range = ptc_baseline_range - st.session_state.ptc_reform_range = ptc_reform_range - st.session_state.ptc_700fpl_range = ptc_700fpl_range - st.session_state.slcsp_2026 = slcsp_2026 - st.session_state.fpl = fpl - st.session_state.benefit_info = benefit_info - st.session_state.fig_comparison = fig_comparison - st.session_state.fig_delta = fig_delta - st.session_state.x_axis_max = x_axis_max - - # Show tabs using cached charts - if hasattr(st.session_state, "fig_delta") and st.session_state.fig_delta is not None: - tab1, tab2, tab3, tab4, tab5 = st.tabs([ - "Gain from extension", - "Baseline vs. extension", - "Net income", - "Marginal tax rates", - "Your impact" - ]) - - with tab1: - st.plotly_chart( - st.session_state.fig_delta, - use_container_width=True, - config={"displayModeBar": False}, - key="gain_chart", - ) - - with tab2: - st.plotly_chart( - st.session_state.fig_comparison, - use_container_width=True, - config={"displayModeBar": False}, - key="comparison_chart", - ) - - with tab3: - # Auto-generate net income chart if not cached - if not hasattr(st.session_state, "fig_net_income") or st.session_state.fig_net_income is None: - with st.spinner("Calculating net income (this may take a few seconds)..."): - x_axis_max = st.session_state.get("x_axis_max", 200000) - ( - fig_net_income, - fig_mtr, - net_income_range, - net_income_baseline, - net_income_reform, - ) = create_net_income_and_mtr_charts( - params["age_head"], - params["age_spouse"], - tuple(params["dependent_ages"]), - params["state"], - params.get("county"), - params.get("zip_code"), - x_axis_max, - show_ira=params.get("show_ira", True), - show_700fpl=params.get("show_700fpl", False), - ) - - # Store in session state - if fig_net_income is not None: - st.session_state.fig_net_income = fig_net_income - st.session_state.fig_mtr = fig_mtr - - # Display cached chart - if hasattr(st.session_state, "fig_net_income") and st.session_state.fig_net_income is not None: - st.plotly_chart( - st.session_state.fig_net_income, - use_container_width=True, - config={"displayModeBar": False}, - key="net_income_chart", - ) - - with tab4: - # Check if chart needs to be generated - if not hasattr(st.session_state, "fig_mtr") or st.session_state.fig_mtr is None: - with st.spinner("Calculating marginal tax rates (this may take a few seconds)..."): - x_axis_max = st.session_state.get("x_axis_max", 200000) - ( - fig_net_income, - fig_mtr, - net_income_range, - net_income_baseline, - net_income_reform, - ) = create_net_income_and_mtr_charts( - params["age_head"], - params["age_spouse"], - tuple(params["dependent_ages"]), - params["state"], - params.get("county"), - params.get("zip_code"), - x_axis_max, - show_ira=params.get("show_ira", True), - show_700fpl=params.get("show_700fpl", False), - ) - - # Store in session state - if fig_mtr is not None: - st.session_state.fig_net_income = fig_net_income - st.session_state.fig_mtr = fig_mtr - - # Display chart - if hasattr(st.session_state, "fig_mtr") and st.session_state.fig_mtr is not None: - st.plotly_chart( - st.session_state.fig_mtr, - use_container_width=True, - config={"displayModeBar": False}, - key="mtr_chart", - ) - - with tab5: - st.markdown("Enter your annual household income to see your specific impact.") - - user_income = st.number_input( - "Annual household income:", - min_value=0, - value=0, - step=1000, - help="Modified Adjusted Gross Income (MAGI) as defined in 26 USC § 36B(d)(2). Includes: wages, self-employment income, capital gains, interest, dividends, pensions, Social Security, unemployment, rental income, and other income sources. Also includes tax-exempt interest and tax-exempt Social Security.", - format="%d", - ) - - # Interpolate values at user's income (only if income > 0) - if ( - hasattr(st.session_state, "income_range") - and user_income is not None - and user_income > 0 - ): - ptc_2026_baseline = np.interp( - user_income, - st.session_state.income_range, - st.session_state.ptc_baseline_range, - ) - ptc_2026_with_ira = np.interp( - user_income, - st.session_state.income_range, - st.session_state.ptc_reform_range, - ) - difference = ptc_2026_with_ira - ptc_2026_baseline - slcsp_2026 = st.session_state.slcsp_2026 - fpl = st.session_state.fpl - - # Calculate FPL percentage - household_size = ( - 1 - + (1 if params["age_spouse"] else 0) - + len(params["dependent_ages"]) - ) - fpl_pct = (user_income / fpl * 100) if fpl > 0 else 0 - - # Display metrics with custom CSS to prevent truncation - st.markdown( - """ - - """, - unsafe_allow_html=True, - ) - - col_baseline, col_with_ira, col_diff = st.columns(3) - - with col_baseline: - st.metric( - "Current law", - f"${ptc_2026_baseline:,.0f} per year", - help="Your credits under current law (enhanced PTCs expire)", - ) - - with col_with_ira: - st.metric( - "Enhanced PTCs extended", - f"${ptc_2026_with_ira:,.0f} per year", - help="Your credits if enhanced subsidies were extended", - ) - - with col_diff: - if difference > 0: - st.metric( - "You gain", - f"${difference:,.0f} per year", - f"+${difference/12:,.0f} per month", - delta_color="normal", - ) - else: - st.metric("No change", "$0") - - # Details - with st.expander("See calculation details"): - st.write( - f""" - ### Your household - - **Size:** {household_size} people - - **Income:** ${user_income:,} ({fpl_pct:.0f}% of FPL) - - **2026 Federal Poverty Guideline:** ${fpl:,.0f} - - **Location:** {params['county'] + ', ' if params['county'] else ''}{params['state']} - - **Second Lowest Cost Silver Plan:** ${slcsp_2026:,.0f} per year (${slcsp_2026/12:,.0f} per month) - - ### How premium tax credits work - - **Formula:** PTC = Benchmark Plan Cost - Your Required Contribution - - **Your Required Contribution** is a percentage of your income: - - Lower percentages with IRA extension (2026): 0-8.5% based on income - - Higher percentages without IRA (2026): 2-9.5% based on income - - No credits at all above 400% FPL without IRA extension - - If the benchmark plan costs less than your required contribution, you get no credit. - """ - ) - - # Move "About this calculator" below the tabs - with st.expander("About this calculator"): - try: - from importlib.metadata import version - pe_version = version("policyengine-us") - except Exception: - pe_version = "development" - - st.markdown( - f""" - The Inflation Reduction Act enhanced ACA subsidies through 2025. This calculator shows how extending these enhancements to 2026 would affect your household's premium tax credits. - - This calculator uses [PolicyEngine's open-source tax-benefit microsimulation model](https://github.com/PolicyEngine/policyengine-us) (version {pe_version}). - - **2026 premium projections:** This calculator projects Second Lowest Cost Silver Plan (SLCSP) premiums for 2026 by applying a 4.19% increase to actual 2025 benchmark premiums from KFF, based on 2024-25 growth patterns. Actual premiums may rise faster, and we will update the calculator when CMS releases official data in October 2025. - - 📖 [Learn more about enhanced premium tax credits](https://policyengine.org/us/research/enhanced-premium-tax-credits-extension) - - **Reform scenarios:** - - *IRA Extension:* - - No income cap - households above 400% FPL can still receive credits - - Lower premium contribution percentages (0-8.5% of income) - - More generous subsidies at all income levels - - *700% FPL Extension ([Bipartisan Health Insurance Affordability Act](https://punchbowl.news/wp-content/uploads/Bipartisan-Health-Insurance-Affordability-Act-Section-by-Section-copy.pdf)):* - - Eligibility extends to 700% FPL (vs no limit under IRA extension) - - Contribution percentages: 2-9.25% of income - - Different phase-out schedule than IRA extension - - **Current law (baseline - enhanced PTCs expire):** - - Hard cap at 400% FPL - no credits above this level (the "subsidy cliff") - - Higher contribution percentages (2.1-9.96% of income, per IRS Revenue Procedure 2025-25) - - Less generous subsidies, especially for middle incomes - - **Key assumptions:** - - Households have no employer-sponsored insurance (ESI), making them eligible for Medicaid, CHIP, and premium tax credits - - Net income and MTR calculations assume standard deduction (set as input to avoid expensive itemization branching) - - **Technical note on MTR chart:** The IRS requires MAGI/FPL ratios to be truncated to whole percentages per [Form 8962 instructions](https://www.irs.gov/pub/irs-pdf/i8962.pdf#page=8). This creates ~$10 jumps in PTCs approximately every $100-200 income. The MTR chart applies a $1,000 moving average to smooth over these artifacts while preserving major cliffs (like PTC eligibility thresholds). - """ - ) - - -def create_chart( - age_head, - age_spouse, - dependent_ages, - state, - county=None, - zip_code=None, - income=None, - show_ira=True, - show_700fpl=False, -): - """Create income curve charts showing PTC across income range - - Args: - zip_code: 5-digit ZIP code string (required for LA County) - income: Optional income to mark on chart. If None, no marker shown. - show_ira: Whether to show IRA extension reform - show_700fpl: Whether to show 700% FPL extension reform - - Returns tuple of (comparison_fig, delta_fig, benefit_info, income_range, ptc_baseline_range, ptc_reform_range, ptc_700fpl_range, slcsp, fpl, x_axis_max) - Arrays are returned for interpolation - - Note: Caching removed to prevent signature mismatch issues on Streamlit Cloud - """ - - # Create base household structure for income sweep - base_household = build_household_situation( - age_head=age_head, - age_spouse=age_spouse, - dependent_ages=list(dependent_ages) if dependent_ages else [], - state=state, - county=county, - zip_code=zip_code, - year=2026, - with_axes=True, - ) - - # Color for 700% FPL reform - PURPLE = "#9467BD" - - try: - # Create reforms for chart calculation - reform_ira = create_enhanced_ptc_reform() - reform_700fpl = create_700fpl_reform() - - # Calculate baseline - sim_baseline = Simulation(situation=base_household) - - income_range = sim_baseline.calculate( - "employment_income", map_to="household", period=2026 - ) - ptc_range_baseline = sim_baseline.calculate( - "aca_ptc", map_to="household", period=2026 - ) - - # Calculate IRA reform if selected - ptc_range_reform = None - if show_ira: - sim_ira = Simulation(situation=base_household, reform=reform_ira) - ptc_range_reform = sim_ira.calculate( - "aca_ptc", map_to="household", period=2026 - ) - - # Calculate 700% FPL reform if selected - ptc_range_700fpl = None - if show_700fpl and reform_700fpl is not None: - sim_700fpl = Simulation(situation=base_household, reform=reform_700fpl) - ptc_range_700fpl = sim_700fpl.calculate( - "aca_ptc", map_to="household", period=2026 - ) - - # Calculate Medicaid and CHIP values - medicaid_range = sim_baseline.calculate( - "medicaid_cost", map_to="household", period=2026 - ) - chip_range = sim_baseline.calculate( - "per_capita_chip", map_to="household", period=2026 - ) - - # Find where PTC goes to zero for dynamic x-axis range - max_income_with_ptc = 200000 # Default fallback - # Check all active reform PTCs - ptc_arrays_to_check = [ptc_range_baseline] - if ptc_range_reform is not None: - ptc_arrays_to_check.append(ptc_range_reform) - if ptc_range_700fpl is not None: - ptc_arrays_to_check.append(ptc_range_700fpl) - - for ptc_arr in ptc_arrays_to_check: - for i in range(len(ptc_arr) - 1, -1, -1): - if ptc_arr[i] > 0: - max_income_with_ptc = max(max_income_with_ptc, income_range[i]) - break - - # Add 10% padding to the range - x_axis_max = min(1000000, max_income_with_ptc * 1.1) - - # Calculate delta (use IRA if available, otherwise 700% FPL) - if ptc_range_reform is not None: - delta_range = ptc_range_reform - ptc_range_baseline - elif ptc_range_700fpl is not None: - delta_range = ptc_range_700fpl - ptc_range_baseline - else: - delta_range = np.zeros_like(ptc_range_baseline) - - # Create hover text based on program eligibility - import numpy as np - - hover_text = [] - for i in range(len(income_range)): - inc = income_range[i] - ptc_base = ptc_range_baseline[i] - ptc_ira = ptc_range_reform[i] if ptc_range_reform is not None else 0 - ptc_700 = ptc_range_700fpl[i] if ptc_range_700fpl is not None else 0 - medicaid = medicaid_range[i] - chip = chip_range[i] - - text = f"Income: ${inc:,.0f}

" - - # Show all applicable benefits (not mutually exclusive) - if medicaid > 0: - text += f"Medicaid: ${medicaid:,.0f}/year
" - if chip > 0: - text += f"CHIP: ${chip:,.0f}/year
" - - # Always show PTC information if present - if ptc_base > 0 or ptc_ira > 0 or ptc_700 > 0: - text += f"PTC (baseline): ${ptc_base:,.0f}/year
" - if show_ira and ptc_range_reform is not None: - text += f"PTC (IRA extension): ${ptc_ira:,.0f}/year
" - if show_700fpl and ptc_range_700fpl is not None: - text += f"PTC (700% FPL): ${ptc_700:,.0f}/year
" - - hover_text.append(text) - - # Create the plot - fig = go.Figure() - - # Build list of arrays to find max for hover trace - arrays_for_max = [medicaid_range, chip_range, ptc_range_baseline] - if ptc_range_reform is not None: - arrays_for_max.append(ptc_range_reform) - if ptc_range_700fpl is not None: - arrays_for_max.append(ptc_range_700fpl) - - # Add invisible hover trace with unified information - fig.add_trace( - go.Scatter( - x=income_range, - y=np.maximum.reduce(arrays_for_max), - mode="lines", - line=dict(width=0), - hovertext=hover_text, - hoverinfo="text", - showlegend=False, - name="", - ) - ) - - # Add Medicaid line (always show in legend, hidden by default) - fig.add_trace( - go.Scatter( - x=income_range, - y=medicaid_range, - mode="lines", - name="Medicaid", - line=dict(color=COLORS["green"], width=3), - hoverinfo="skip", - visible="legendonly", - ) - ) - - # Add CHIP line only if any household member is eligible - if np.any(chip_range > 0): - fig.add_trace( - go.Scatter( - x=income_range, - y=chip_range, - mode="lines", - name="Children's Health Insurance Program (CHIP)", - line=dict(color=COLORS["secondary"], width=3), - hoverinfo="skip", - visible="legendonly", - ) - ) - - # Add baseline line (current law) - show first in legend - fig.add_trace( - go.Scatter( - x=income_range, - y=ptc_range_baseline, - mode="lines", - name="PTC (baseline)", - line=dict(color=COLORS["gray"], width=3), - hoverinfo="skip", - ) - ) - - # Add IRA extension line if selected - if show_ira and ptc_range_reform is not None: - fig.add_trace( - go.Scatter( - x=income_range, - y=ptc_range_reform, - mode="lines", - name="PTC (IRA extension)", - line=dict(color=COLORS["primary"], width=3), - hoverinfo="skip", - ) - ) - - # Add 700% FPL extension line if selected - if show_700fpl and ptc_range_700fpl is not None: - fig.add_trace( - go.Scatter( - x=income_range, - y=ptc_range_700fpl, - mode="lines", - name="PTC (700% FPL extension)", - line=dict(color=PURPLE, width=3), - hoverinfo="skip", - ) - ) - - # Add user's position markers (only if income is provided) - if income is not None and income > 10000: - # Interpolate PTC values at user's income - ptc_baseline_user = np.interp( - income, income_range, ptc_range_baseline - ) - - # Add baseline marker - fig.add_annotation( - x=income, - y=ptc_baseline_user, - text=f"Baseline: ${ptc_baseline_user:,.0f}", - showarrow=True, - arrowhead=2, - arrowsize=1, - arrowwidth=2, - arrowcolor=COLORS["gray"], - ax=60, - ay=40, - bgcolor="white", - bordercolor=COLORS["gray"], - borderwidth=2, - ) - - if show_ira and ptc_range_reform is not None: - ptc_ira_user = np.interp(income, income_range, ptc_range_reform) - fig.add_annotation( - x=income, - y=ptc_ira_user, - text=f"IRA: ${ptc_ira_user:,.0f}", - showarrow=True, - arrowhead=2, - arrowsize=1, - arrowwidth=2, - arrowcolor=COLORS["primary"], - ax=60, - ay=-40, - bgcolor="white", - bordercolor=COLORS["primary"], - borderwidth=2, - ) - - if show_700fpl and ptc_range_700fpl is not None: - ptc_700_user = np.interp(income, income_range, ptc_range_700fpl) - fig.add_annotation( - x=income, - y=ptc_700_user, - text=f"700% FPL: ${ptc_700_user:,.0f}", - showarrow=True, - arrowhead=2, - arrowsize=1, - arrowwidth=2, - arrowcolor=PURPLE, - ax=-60, - ay=-40, - bgcolor="white", - bordercolor=PURPLE, - borderwidth=2, - ) - - # Update layout for comparison chart - fig.update_layout( - title={ - "text": "Healthcare assistance by household income (2026)", - "font": {"size": 20, "color": COLORS["primary"]}, - }, - xaxis_title="Annual household income", - yaxis_title="Annual healthcare assistance value", - height=400, - xaxis=dict( - tickformat="$,.0f", range=[0, x_axis_max], automargin=True - ), - yaxis=dict( - tickformat="$,.0f", rangemode="tozero", automargin=True - ), - plot_bgcolor="white", - paper_bgcolor="white", - font=dict(family="Roboto, sans-serif"), - legend=dict( - orientation="h", yanchor="bottom", y=0.98, xanchor="right", x=1 - ), - margin=dict(l=80, r=40, t=60, b=80), - **add_logo_to_layout(), - ) - - # Create delta chart - fig_delta = go.Figure() - - # Create hover text for delta chart - delta_hover_text = [] - for i in range(len(income_range)): - inc = income_range[i] - delta = delta_range[i] - ptc_base = ptc_range_baseline[i] - ptc_ira = ptc_range_reform[i] if ptc_range_reform is not None else 0 - ptc_700 = ptc_range_700fpl[i] if ptc_range_700fpl is not None else 0 - medicaid = medicaid_range[i] - chip = chip_range[i] - - text = f"Income: ${inc:,.0f}

" - - # Show all applicable benefits - if medicaid > 0: - text += f"Medicaid: ${medicaid:,.0f}/year
" - if chip > 0: - text += f"CHIP: ${chip:,.0f}/year
" - - # Show PTC amounts - text += f"PTC (baseline): ${ptc_base:,.0f}/year
" - if show_ira and ptc_range_reform is not None: - text += f"PTC (IRA extension): ${ptc_ira:,.0f}/year
" - if show_700fpl and ptc_range_700fpl is not None: - text += f"PTC (700% FPL): ${ptc_700:,.0f}/year
" - - delta_hover_text.append(text) - - # Add delta lines for each selected reform - if show_ira and ptc_range_reform is not None: - delta_ira = ptc_range_reform - ptc_range_baseline - fig_delta.add_trace( - go.Scatter( - x=income_range, - y=delta_ira, - mode="lines", - name="IRA extension gain", - line=dict(color=COLORS["primary"], width=3), - fill="tozeroy", - fillcolor="rgba(44, 100, 150, 0.2)", - hovertext=delta_hover_text, - hoverinfo="text", - ) - ) - - if show_700fpl and ptc_range_700fpl is not None: - delta_700 = ptc_range_700fpl - ptc_range_baseline - fig_delta.add_trace( - go.Scatter( - x=income_range, - y=delta_700, - mode="lines", - name="700% FPL extension gain", - line=dict(color=PURPLE, width=3), - fill="tozeroy" if not show_ira else None, - fillcolor="rgba(148, 103, 189, 0.2)" if not show_ira else None, - hovertext=delta_hover_text, - hoverinfo="text", - ) - ) - - fig_delta.update_layout( - title={ - "text": "PTC gain from extending enhanced subsidies (2026)", - "font": {"size": 20, "color": COLORS["primary"]}, - }, - xaxis_title="Annual household income", - yaxis_title="Annual PTC gain (extended - current law)", - height=400, - xaxis=dict( - tickformat="$,.0f", range=[0, x_axis_max], automargin=True - ), - yaxis=dict( - tickformat="$,.0f", rangemode="tozero", automargin=True - ), - plot_bgcolor="white", - paper_bgcolor="white", - font=dict(family="Roboto, sans-serif"), - showlegend=False, - margin=dict(l=80, r=40, t=60, b=80), - **add_logo_to_layout(), - ) - - # Calculate benefit range information - benefit_indices = np.where(delta_range > 0)[0] - if len(benefit_indices) > 0: - min_benefit_income = income_range[benefit_indices[0]] - max_benefit_income = income_range[benefit_indices[-1]] - max_benefit = np.max(delta_range[benefit_indices]) - peak_benefit_index = benefit_indices[np.argmax(delta_range[benefit_indices])] - peak_benefit_income = income_range[peak_benefit_index] - - benefit_info = { - "min_income": float(min_benefit_income), - "max_income": float(max_benefit_income), - "max_benefit": float(max_benefit), - "peak_income": float(peak_benefit_income), - } - - # Add annotations to delta chart for min/max/peak - # Min income annotation - fig_delta.add_annotation( - x=min_benefit_income, - y=delta_range[benefit_indices[0]], - text=f"Benefit starts
${min_benefit_income:,.0f}", - showarrow=True, - arrowhead=2, - arrowsize=1, - arrowwidth=2, - arrowcolor=COLORS["primary"], - ax=-50, - ay=-50, - bgcolor=COLORS["primary"], - bordercolor=COLORS["primary"], - borderwidth=0, - borderpad=8, - font=dict(size=11, color="white"), - ) - - # Peak benefit annotation - fig_delta.add_annotation( - x=peak_benefit_income, - y=max_benefit, - text=f"Max benefit: ${max_benefit:,.0f}
at ${peak_benefit_income:,.0f}", - showarrow=True, - arrowhead=2, - arrowsize=1, - arrowwidth=2, - arrowcolor=COLORS["primary"], - ax=0, - ay=50, - bgcolor=COLORS["primary"], - bordercolor=COLORS["primary"], - borderwidth=0, - borderpad=8, - font=dict(size=12, color="white"), - ) - - # Max income annotation - fig_delta.add_annotation( - x=max_benefit_income, - y=delta_range[benefit_indices[-1]], - text=f"Benefit ends
${max_benefit_income:,.0f}", - showarrow=True, - arrowhead=2, - arrowsize=1, - arrowwidth=2, - arrowcolor=COLORS["primary"], - ax=50, - ay=-50, - bgcolor=COLORS["primary"], - bordercolor=COLORS["primary"], - borderwidth=0, - borderpad=8, - font=dict(size=11, color="white"), - ) - else: - benefit_info = None - - # Get SLCSP and FPL for display - # SLCSP and FPL don't vary with income, but get from middle of array to avoid edge cases - slcsp_array = sim_baseline.calculate("slcsp", map_to="household", period=2026) - fpl_array = sim_baseline.calculate("tax_unit_fpg", period=2026) - - # Use max value for SLCSP (should be constant, but this handles any edge cases) - slcsp = float(np.max(slcsp_array)) - fpl = float(fpl_array[len(fpl_array) // 2]) # Use middle value - - return ( - fig, - fig_delta, - benefit_info, - income_range, - ptc_range_baseline, - ptc_range_reform, - ptc_range_700fpl, - slcsp, - fpl, - x_axis_max, - ) - - except Exception as e: - # If chart generation fails, return None for everything - st.error(f"Error generating charts: {str(e)}") - import traceback - - st.error(traceback.format_exc()) - return None, None, None, None, None, None, None, 0, 0, 200000 - - -def create_net_income_and_mtr_charts( - age_head, - age_spouse, - dependent_ages, - state, - county=None, - zip_code=None, - x_axis_max=200000, - show_ira=True, - show_700fpl=False, -): - """Create net income and MTR charts including health benefits - - Args: - x_axis_max: Maximum income for x-axis (from PTC charts) - show_ira: Whether to show IRA extension reform - show_700fpl: Whether to show 700% FPL extension reform - - Returns tuple of (net_income_fig, mtr_fig, income_range, net_income_baseline, net_income_reform) - """ - - # Color for 700% FPL reform - PURPLE = "#9467BD" - - # Create base household structure for income sweep - base_household = build_household_situation( - age_head=age_head, - age_spouse=age_spouse, - dependent_ages=list(dependent_ages) if dependent_ages else [], - state=state, - county=county, - zip_code=zip_code, - year=2026, - with_axes=True, - ) - - # Set tax_unit_itemizes=False to avoid expensive itemization branching - # This is an input variable, not a reform, so it doesn't slow down baseline - base_household["tax_units"]["your tax unit"]["tax_unit_itemizes"] = {2026: False} - - try: - # Create reforms - reform_ira = create_enhanced_ptc_reform() - reform_700fpl = create_700fpl_reform() - - # Run simulations (itemization already set to False via input) - sim_baseline = Simulation(situation=base_household) - - sim_ira = None - if show_ira: - sim_ira = Simulation(situation=base_household, reform=reform_ira) - - sim_700fpl = None - if show_700fpl and reform_700fpl is not None: - sim_700fpl = Simulation(situation=base_household, reform=reform_700fpl) - - income_range = sim_baseline.calculate( - "employment_income", map_to="household", period=2026 - ) - - # Calculate net income including health benefits - net_income_baseline = sim_baseline.calculate( - "household_net_income_including_health_benefits", map_to="household", period=2026 - ) - - net_income_ira = None - if sim_ira is not None: - net_income_ira = sim_ira.calculate( - "household_net_income_including_health_benefits", map_to="household", period=2026 - ) - - net_income_700fpl = None - if sim_700fpl is not None: - net_income_700fpl = sim_700fpl.calculate( - "household_net_income_including_health_benefits", map_to="household", period=2026 - ) - - # Apply 10-step ($1k) moving average to smooth IRS truncation artifacts - window = 10 - def moving_average(arr, window_size): - """Apply simple moving average smoothing.""" - result = np.copy(arr) - for i in range(len(arr)): - start = max(0, i - window_size // 2) - end = min(len(arr), i + window_size // 2 + 1) - result[i] = np.mean(arr[start:end]) - return result - - def calc_mtr(net_income_arr): - """Calculate MTR from net income array.""" - mtr_raw = np.zeros_like(income_range) - for i in range(len(income_range) - 1): - d_income = income_range[i+1] - income_range[i] - d_net = net_income_arr[i+1] - net_income_arr[i] - mtr_raw[i] = 1 - d_net / d_income - mtr_raw[-1] = mtr_raw[-2] if len(income_range) > 1 else 0 - mtr_viz = moving_average(mtr_raw, window) - return np.clip(mtr_viz, -1.0, 1.5) - - mtr_baseline_viz = calc_mtr(net_income_baseline) - mtr_ira_viz = calc_mtr(net_income_ira) if net_income_ira is not None else None - mtr_700fpl_viz = calc_mtr(net_income_700fpl) if net_income_700fpl is not None else None - - # Create hover text for net income chart - net_income_hover = [] - for i in range(len(income_range)): - text = f"Income: ${income_range[i]:,.0f}

" - text += f"Net income (baseline): ${net_income_baseline[i]:,.0f}
" - if net_income_ira is not None: - text += f"Net income (IRA extension): ${net_income_ira[i]:,.0f}
" - if net_income_700fpl is not None: - text += f"Net income (700% FPL): ${net_income_700fpl[i]:,.0f}
" - net_income_hover.append(text) - - # Create MTR hover text - mtr_hover = [] - for i in range(len(income_range)): - text = f"Income: ${income_range[i]:,.0f}

" - text += f"MTR (baseline): {mtr_baseline_viz[i]*100:.1f}%
" - if mtr_ira_viz is not None: - text += f"MTR (IRA extension): {mtr_ira_viz[i]*100:.1f}%
" - if mtr_700fpl_viz is not None: - text += f"MTR (700% FPL): {mtr_700fpl_viz[i]*100:.1f}%
" - mtr_hover.append(text) - - # Create net income chart - fig_net_income = go.Figure() - - fig_net_income.add_trace( - go.Scatter( - x=income_range, - y=net_income_baseline, - mode="lines", - name="Baseline", - line=dict(color=COLORS["gray"], width=3), - hovertext=net_income_hover, - hoverinfo="text", - ) - ) - - if net_income_ira is not None: - fig_net_income.add_trace( - go.Scatter( - x=income_range, - y=net_income_ira, - mode="lines", - name="IRA extension", - line=dict(color=COLORS["primary"], width=3), - hovertext=net_income_hover, - hoverinfo="text", - ) - ) - - if net_income_700fpl is not None: - fig_net_income.add_trace( - go.Scatter( - x=income_range, - y=net_income_700fpl, - mode="lines", - name="700% FPL extension", - line=dict(color=PURPLE, width=3), - hovertext=net_income_hover, - hoverinfo="text", - ) - ) - - # Set y-axis range to 1.2x the max value within visible x range - # Find indices within x_axis_max - visible_indices = income_range <= x_axis_max - net_income_arrays = [net_income_baseline[visible_indices]] - if net_income_ira is not None: - net_income_arrays.append(net_income_ira[visible_indices]) - if net_income_700fpl is not None: - net_income_arrays.append(net_income_700fpl[visible_indices]) - net_income_max = max(np.max(arr) for arr in net_income_arrays) - net_income_y_max = net_income_max * 1.2 - - fig_net_income.update_layout( - title={ - "text": "Net income (2026)", - "font": {"size": 20, "color": COLORS["primary"]}, - }, - xaxis_title="Annual household income", - yaxis_title="Net income", - height=400, - xaxis=dict( - tickformat="$,.0f", range=[0, x_axis_max], automargin=True - ), - yaxis=dict( - tickformat="$,.0f", range=[0, net_income_y_max], automargin=True - ), - plot_bgcolor="white", - paper_bgcolor="white", - font=dict(family="Roboto, sans-serif"), - legend=dict( - orientation="h", yanchor="bottom", y=0.98, xanchor="right", x=1 - ), - margin=dict(l=80, r=40, t=60, b=80), - **add_logo_to_layout(), - ) - - # Create MTR chart - fig_mtr = go.Figure() - - fig_mtr.add_trace( - go.Scatter( - x=income_range, - y=mtr_baseline_viz, - mode="lines", - name="Baseline", - line=dict(color=COLORS["gray"], width=3), - hovertext=mtr_hover, - hoverinfo="text", - ) - ) - - if mtr_ira_viz is not None: - fig_mtr.add_trace( - go.Scatter( - x=income_range, - y=mtr_ira_viz, - mode="lines", - name="IRA extension", - line=dict(color=COLORS["primary"], width=3), - hovertext=mtr_hover, - hoverinfo="text", - ) - ) - - if mtr_700fpl_viz is not None: - fig_mtr.add_trace( - go.Scatter( - x=income_range, - y=mtr_700fpl_viz, - mode="lines", - name="700% FPL extension", - line=dict(color=PURPLE, width=3), - hovertext=mtr_hover, - hoverinfo="text", - ) - ) - - fig_mtr.update_layout( - title={ - "text": "Marginal tax rate (2026)", - "font": {"size": 20, "color": COLORS["primary"]}, - }, - xaxis_title="Annual household income", - yaxis_title="Marginal tax rate", - height=400, - xaxis=dict( - tickformat="$,.0f", range=[0, x_axis_max], automargin=True - ), - yaxis=dict( - tickformat=".0%", range=[-0.1, 1.0], automargin=True, zeroline=True, zerolinecolor="black", zerolinewidth=2 - ), - plot_bgcolor="white", - paper_bgcolor="white", - font=dict(family="Roboto, sans-serif"), - legend=dict( - orientation="h", yanchor="bottom", y=0.98, xanchor="right", x=1 - ), - margin=dict(l=80, r=40, t=60, b=80), - **add_logo_to_layout(), - ) - - # Clean up memory before returning - gc.collect() - - return ( - fig_net_income, - fig_mtr, - income_range, - net_income_baseline, - net_income_ira, - ) - - except Exception as e: - st.error(f"Error generating net income/MTR charts: {str(e)}") - import traceback - st.error(traceback.format_exc()) - return None, None, None, None, None - - -if __name__ == "__main__": - main() diff --git a/blue.png b/blue.png deleted file mode 100644 index 12736e4..0000000 Binary files a/blue.png and /dev/null differ diff --git a/changelog.d/remove-streamlit-app.removed.md b/changelog.d/remove-streamlit-app.removed.md new file mode 100644 index 0000000..a211f36 --- /dev/null +++ b/changelog.d/remove-streamlit-app.removed.md @@ -0,0 +1 @@ +Remove the retired Streamlit app, its calculation modules and the tests and scripts that only it used. diff --git a/pages/calculator.py b/pages/calculator.py deleted file mode 100644 index 7b12440..0000000 --- a/pages/calculator.py +++ /dev/null @@ -1,623 +0,0 @@ -""" -ACA Premium Tax Credit Calculator Page -====================================== -Full calculator for exploring ACA premium tax credits. -""" - -import streamlit as st -import sys -import os - -# Add parent directory to path to import from aca_calc -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -try: - import pandas as pd - import numpy as np - import json - import gc - from policyengine_us import Simulation - import plotly.graph_objects as go - import base64 - - # Import calculation functions from package - from aca_calc.calculations.ptc import calculate_ptc - from aca_calc.calculations.household import build_household_situation - from aca_calc.calculations.reforms import create_enhanced_ptc_reform, create_700fpl_reform - - # Try to import reform capability - try: - from policyengine_core.reforms import Reform - REFORM_AVAILABLE = True - except ImportError: - REFORM_AVAILABLE = False - - st.set_page_config( - page_title="ACA Calculator", - page_icon="🧮", - layout="wide", - initial_sidebar_state="expanded", - ) - -except Exception as e: - st.error(f"Startup Error: {str(e)}") - st.error("Please report this error with the details above.") - import traceback - st.code(traceback.format_exc()) - st.stop() - - -# PolicyEngine brand colors (app-v2 style) -COLORS = { - "primary": "#319795", # Teal - "secondary": "#2C6496", # Blue for IRA reform - "purple": "#9467BD", # Purple for 700% FPL - "gray": "#9CA3AF", # Gray for baseline - "green": "#22C55E", -} - - -def get_logo_base64(): - """Get base64 encoded PolicyEngine logo""" - try: - logo_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "blue.png") - with open(logo_path, "rb") as f: - return base64.b64encode(f.read()).decode() - except: - return None - - -def add_logo_to_layout(): - """Add PolicyEngine logo to chart layout""" - logo_base64 = get_logo_base64() - if logo_base64: - return { - "images": [ - { - "source": f"data:image/png;base64,{logo_base64}", - "xref": "paper", - "yref": "paper", - "x": 1.01, - "y": -0.18, - "sizex": 0.10, - "sizey": 0.10, - "xanchor": "right", - "yanchor": "bottom", - } - ] - } - return {} - - -# Load counties -@st.cache_data -def load_counties(): - try: - counties_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "counties.json") - with open(counties_path, "r") as f: - return json.load(f) - except: - return None - - -def main(): - # Header styling - st.markdown( - f""" - - """, - unsafe_allow_html=True, - ) - - st.title("🧮 ACA Premium Tax Credit Calculator") - st.markdown("Explore how extending enhanced premium tax credits would affect your household.") - - # Link back to interactive story - st.markdown("← [Back to Interactive Guide](/)") - - counties = load_counties() - - # Sidebar for household configuration - with st.sidebar: - st.header("Reform scenarios") - st.markdown("Select which reform(s) to compare against baseline:") - - show_ira = st.checkbox( - "IRA Extension", - value=True, - help="Extends current enhanced subsidies indefinitely with 8.5% cap and no income limit above 400% FPL" - ) - - show_700fpl = st.checkbox( - "700% FPL Extension (Bipartisan Bill)", - value=False, - help="Bipartisan Health Insurance Affordability Act: extends eligibility to 700% FPL with 9.25% cap" - ) - - if not show_ira and not show_700fpl: - st.warning("Please select at least one reform to compare.") - - st.markdown("---") - - st.header("Household configuration") - - married = st.checkbox("Are you married?", value=False) - - age_head = st.number_input( - "How old are you?", min_value=18, max_value=100, value=35 - ) - - if married: - age_spouse = st.number_input( - "How old is your spouse?", - min_value=18, - max_value=100, - value=35, - ) - else: - age_spouse = None - - num_dependents = st.number_input( - "How many children or dependents do you have?", - min_value=0, - max_value=10, - value=0, - ) - dependent_ages = [] - - if num_dependents > 0: - st.write("What are their ages?") - for i in range(num_dependents): - age_dep = st.number_input( - f"Child {i+1} age", - min_value=0, - max_value=25, - value=10, - key=f"dep_{i}", - ) - dependent_ages.append(age_dep) - - states = [ - "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", - "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", - "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", - "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", - "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY", "DC", - ] - - state = st.selectbox("Which state do you live in?", states, index=0) - - # County selection - county = None - if counties and state in counties: - sorted_counties = sorted(counties[state]) - county = st.selectbox( - "Which county?", - sorted_counties, - index=0, - help="County used for marketplace calculations", - ) - - # ZIP code for LA County - zip_code = None - if state == "CA" and county == "Los Angeles County": - zip_code = st.text_input( - "What is your ZIP code?", - max_chars=5, - help="Los Angeles County has multiple rating areas.", - placeholder="90001", - ) - if zip_code and (len(zip_code) != 5 or not zip_code.isdigit()): - st.error("Please enter a valid 5-digit ZIP code") - zip_code = None - - st.markdown("---") - - calculate_button = st.button( - "Analyze premium subsidies", - type="primary", - use_container_width=True, - ) - - if calculate_button: - st.session_state.calculate = True - new_params = { - "age_head": age_head, - "age_spouse": age_spouse, - "dependent_ages": dependent_ages, - "state": state, - "county": county, - "married": married, - "zip_code": zip_code, - "show_ira": show_ira, - "show_700fpl": show_700fpl, - } - # Clear cached charts if params changed - if hasattr(st.session_state, "params") and st.session_state.params != new_params: - st.session_state.income_range = None - st.session_state.fig_net_income = None - st.session_state.fig_mtr = None - st.session_state.params = new_params - - # Main content area - if not hasattr(st.session_state, "calculate") or not st.session_state.calculate: - st.markdown( - """ - ### Get started - - Enter your household information in the sidebar, then click **"Analyze premium subsidies"** to see: - - - How premium tax credits vary across income levels for your household - - The income range where extending enhanced subsidies would benefit you - - Your specific impact at any income level you choose - - **Available reform scenarios:** - - **IRA Extension**: Continues current enhanced subsidies with 8.5% cap and no income limit - - **700% FPL Extension**: [Bipartisan Health Insurance Affordability Act](https://punchbowl.news/wp-content/uploads/Bipartisan-Health-Insurance-Affordability-Act-Section-by-Section-copy.pdf) extending eligibility to 700% FPL with 9.25% cap - - Select one or both reforms in the sidebar to compare against baseline (current law after IRA expiration). - """ - ) - else: - params = st.session_state.params - - # Generate charts - if not hasattr(st.session_state, "income_range") or st.session_state.income_range is None: - with st.spinner("Generating analysis..."): - county_name = params["county"] if params["county"] else None - zip_code = params.get("zip_code") - - ( - fig_comparison, - fig_delta, - benefit_info, - income_range, - ptc_baseline_range, - ptc_reform_range, - ptc_700fpl_range, - slcsp_2026, - fpl, - x_axis_max, - ) = create_chart( - params["age_head"], - params["age_spouse"], - tuple(params["dependent_ages"]), - params["state"], - county_name, - zip_code, - show_ira=params.get("show_ira", True), - show_700fpl=params.get("show_700fpl", False), - ) - - if income_range is not None: - st.session_state.income_range = income_range - st.session_state.ptc_baseline_range = ptc_baseline_range - st.session_state.ptc_reform_range = ptc_reform_range - st.session_state.ptc_700fpl_range = ptc_700fpl_range - st.session_state.slcsp_2026 = slcsp_2026 - st.session_state.fpl = fpl - st.session_state.benefit_info = benefit_info - st.session_state.fig_comparison = fig_comparison - st.session_state.fig_delta = fig_delta - st.session_state.x_axis_max = x_axis_max - - # Show tabs - if hasattr(st.session_state, "fig_delta") and st.session_state.fig_delta is not None: - tab1, tab2, tab3 = st.tabs([ - "Gain from extension", - "Baseline vs. extension", - "Your impact" - ]) - - with tab1: - st.plotly_chart( - st.session_state.fig_delta, - use_container_width=True, - config={"displayModeBar": False}, - key="gain_chart", - ) - - with tab2: - st.plotly_chart( - st.session_state.fig_comparison, - use_container_width=True, - config={"displayModeBar": False}, - key="comparison_chart", - ) - - with tab3: - st.markdown("Enter your annual household income to see your specific impact.") - - user_income = st.number_input( - "Annual household income:", - min_value=0, - value=0, - step=1000, - help="Modified Adjusted Gross Income (MAGI)", - format="%d", - ) - - if ( - hasattr(st.session_state, "income_range") - and user_income is not None - and user_income > 0 - ): - ptc_2026_baseline = np.interp( - user_income, - st.session_state.income_range, - st.session_state.ptc_baseline_range, - ) - ptc_2026_with_ira = np.interp( - user_income, - st.session_state.income_range, - st.session_state.ptc_reform_range, - ) - difference = ptc_2026_with_ira - ptc_2026_baseline - fpl = st.session_state.fpl - - # Calculate FPL percentage - household_size = ( - 1 - + (1 if params["age_spouse"] else 0) - + len(params["dependent_ages"]) - ) - fpl_pct = (user_income / fpl * 100) if fpl > 0 else 0 - - col_baseline, col_with_ira, col_diff = st.columns(3) - - with col_baseline: - st.metric( - "Current law", - f"${ptc_2026_baseline:,.0f}/year", - ) - - with col_with_ira: - st.metric( - "With reform", - f"${ptc_2026_with_ira:,.0f}/year", - ) - - with col_diff: - if difference > 0: - st.metric( - "You gain", - f"${difference:,.0f}/year", - f"+${difference/12:,.0f}/month", - ) - else: - st.metric("No change", "$0") - - -def create_chart( - age_head, - age_spouse, - dependent_ages, - state, - county=None, - zip_code=None, - income=None, - show_ira=True, - show_700fpl=False, -): - """Create income curve charts showing PTC across income range""" - - base_household = build_household_situation( - age_head=age_head, - age_spouse=age_spouse, - dependent_ages=list(dependent_ages) if dependent_ages else [], - state=state, - county=county, - zip_code=zip_code, - year=2026, - with_axes=True, - ) - - PURPLE = "#9467BD" - - try: - reform_ira = create_enhanced_ptc_reform() - reform_700fpl = create_700fpl_reform() - - sim_baseline = Simulation(situation=base_household) - - income_range = sim_baseline.calculate( - "employment_income", map_to="household", period=2026 - ) - ptc_range_baseline = sim_baseline.calculate( - "aca_ptc", map_to="household", period=2026 - ) - - ptc_range_reform = None - if show_ira: - sim_ira = Simulation(situation=base_household, reform=reform_ira) - ptc_range_reform = sim_ira.calculate( - "aca_ptc", map_to="household", period=2026 - ) - - ptc_range_700fpl = None - if show_700fpl and reform_700fpl is not None: - sim_700fpl = Simulation(situation=base_household, reform=reform_700fpl) - ptc_range_700fpl = sim_700fpl.calculate( - "aca_ptc", map_to="household", period=2026 - ) - - # Find x-axis range - max_income_with_ptc = 200000 - ptc_arrays_to_check = [ptc_range_baseline] - if ptc_range_reform is not None: - ptc_arrays_to_check.append(ptc_range_reform) - if ptc_range_700fpl is not None: - ptc_arrays_to_check.append(ptc_range_700fpl) - - for ptc_arr in ptc_arrays_to_check: - for i in range(len(ptc_arr) - 1, -1, -1): - if ptc_arr[i] > 0: - max_income_with_ptc = max(max_income_with_ptc, income_range[i]) - break - - x_axis_max = min(1000000, max_income_with_ptc * 1.1) - - # Delta - if ptc_range_reform is not None: - delta_range = ptc_range_reform - ptc_range_baseline - elif ptc_range_700fpl is not None: - delta_range = ptc_range_700fpl - ptc_range_baseline - else: - delta_range = np.zeros_like(ptc_range_baseline) - - # Create comparison chart - fig = go.Figure() - - fig.add_trace( - go.Scatter( - x=income_range, - y=ptc_range_baseline, - mode="lines", - name="PTC (baseline)", - line=dict(color=COLORS["gray"], width=3), - ) - ) - - if show_ira and ptc_range_reform is not None: - fig.add_trace( - go.Scatter( - x=income_range, - y=ptc_range_reform, - mode="lines", - name="PTC (IRA extension)", - line=dict(color=COLORS["secondary"], width=3), - ) - ) - - if show_700fpl and ptc_range_700fpl is not None: - fig.add_trace( - go.Scatter( - x=income_range, - y=ptc_range_700fpl, - mode="lines", - name="PTC (700% FPL extension)", - line=dict(color=PURPLE, width=3), - ) - ) - - fig.update_layout( - title={ - "text": "Premium Tax Credits by Household Income (2026)", - "font": {"size": 20, "color": COLORS["primary"]}, - }, - xaxis_title="Annual household income", - yaxis_title="Annual premium tax credit", - height=400, - xaxis=dict(tickformat="$,.0f", range=[0, x_axis_max]), - yaxis=dict(tickformat="$,.0f", rangemode="tozero"), - plot_bgcolor="white", - paper_bgcolor="white", - font=dict(family="Inter, sans-serif"), - legend=dict(orientation="h", yanchor="bottom", y=0.98, xanchor="right", x=1), - margin=dict(l=80, r=40, t=60, b=80), - **add_logo_to_layout(), - ) - - # Create delta chart - fig_delta = go.Figure() - - if show_ira and ptc_range_reform is not None: - delta_ira = ptc_range_reform - ptc_range_baseline - fig_delta.add_trace( - go.Scatter( - x=income_range, - y=delta_ira, - mode="lines", - name="IRA extension gain", - line=dict(color=COLORS["secondary"], width=3), - fill="tozeroy", - fillcolor="rgba(44, 100, 150, 0.2)", - ) - ) - - if show_700fpl and ptc_range_700fpl is not None: - delta_700 = ptc_range_700fpl - ptc_range_baseline - fig_delta.add_trace( - go.Scatter( - x=income_range, - y=delta_700, - mode="lines", - name="700% FPL extension gain", - line=dict(color=PURPLE, width=3), - fill="tozeroy" if not show_ira else None, - fillcolor="rgba(148, 103, 189, 0.2)" if not show_ira else None, - ) - ) - - fig_delta.update_layout( - title={ - "text": "PTC Gain from Extending Enhanced Subsidies (2026)", - "font": {"size": 20, "color": COLORS["primary"]}, - }, - xaxis_title="Annual household income", - yaxis_title="Annual PTC gain", - height=400, - xaxis=dict(tickformat="$,.0f", range=[0, x_axis_max]), - yaxis=dict(tickformat="$,.0f", rangemode="tozero"), - plot_bgcolor="white", - paper_bgcolor="white", - font=dict(family="Inter, sans-serif"), - showlegend=True, - margin=dict(l=80, r=40, t=60, b=80), - **add_logo_to_layout(), - ) - - # Calculate benefit info - benefit_indices = np.where(delta_range > 0)[0] - if len(benefit_indices) > 0: - benefit_info = { - "min_income": float(income_range[benefit_indices[0]]), - "max_income": float(income_range[benefit_indices[-1]]), - "max_benefit": float(np.max(delta_range[benefit_indices])), - } - else: - benefit_info = None - - # Get SLCSP and FPL - slcsp_array = sim_baseline.calculate("slcsp", map_to="household", period=2026) - fpl_array = sim_baseline.calculate("tax_unit_fpg", period=2026) - slcsp = float(np.max(slcsp_array)) - fpl = float(fpl_array[len(fpl_array) // 2]) - - return ( - fig, - fig_delta, - benefit_info, - income_range, - ptc_range_baseline, - ptc_range_reform if ptc_range_reform is not None else np.zeros_like(ptc_range_baseline), - ptc_range_700fpl, - slcsp, - fpl, - x_axis_max, - ) - - except Exception as e: - st.error(f"Error generating charts: {str(e)}") - import traceback - st.error(traceback.format_exc()) - return None, None, None, None, None, None, None, 0, 0, 200000 - - -if __name__ == "__main__": - main() diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index f4fa2ac..0000000 --- a/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -streamlit -policyengine_us>=1.409.0 -numpy -pandas -plotly diff --git a/tests/test_400_fpl_cliff.py b/tests/test_400_fpl_cliff.py deleted file mode 100644 index 45c796c..0000000 --- a/tests/test_400_fpl_cliff.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Test the 400% FPL cliff.""" -import sys -sys.path.insert(0, '.') - -from app import calculate_ptc, get_fpl - - -def test_cliff_at_400_fpl(): - """Test that baseline has cliff at 400% FPL but reform doesn't.""" - - # 60-year-old couple in WV - household_size = 2 - fpl = get_fpl(household_size) - - print(f"2-person FPL: ${fpl:,}") - print(f"400% FPL: ${fpl * 4:,}") - - # Test just below 400% FPL - income_below = int(fpl * 3.99) - print(f"\nTesting at 399% FPL (${income_below:,}):") - - ptc_reform_below, slcsp = calculate_ptc(60, 60, income_below, [], "WV", None, use_reform=True) - ptc_baseline_below, _ = calculate_ptc(60, 60, income_below, [], "WV", None, use_reform=False) - - print(f" Baseline PTC: ${ptc_baseline_below:,.0f}") - print(f" Reform PTC: ${ptc_reform_below:,.0f}") - - # Test at 400% FPL - income_at = int(fpl * 4.0) - print(f"\nTesting at 400% FPL (${income_at:,}):") - - ptc_reform_at, _ = calculate_ptc(60, 60, income_at, [], "WV", None, use_reform=True) - ptc_baseline_at, _ = calculate_ptc(60, 60, income_at, [], "WV", None, use_reform=False) - - print(f" Baseline PTC: ${ptc_baseline_at:,.0f}") - print(f" Reform PTC: ${ptc_reform_at:,.0f}") - - # Test above 400% FPL - income_above = int(fpl * 4.5) - print(f"\nTesting at 450% FPL (${income_above:,}):") - - ptc_reform_above, _ = calculate_ptc(60, 60, income_above, [], "WV", None, use_reform=True) - ptc_baseline_above, _ = calculate_ptc(60, 60, income_above, [], "WV", None, use_reform=False) - - print(f" Baseline PTC: ${ptc_baseline_above:,.0f}") - print(f" Reform PTC: ${ptc_reform_above:,.0f}") - - print("\n" + "="*70) - print("VERIFICATION:") - print("="*70) - - # Baseline should be $0 above 400% FPL - if ptc_baseline_above == 0: - print("✓ Baseline correctly has cliff (PTC = $0 above 400% FPL)") - else: - print(f"✗ FAIL: Baseline should be $0 above 400% FPL, got ${ptc_baseline_above:,.0f}") - - # Reform should still have PTC above 400% FPL - if ptc_reform_above > 0: - print("✓ Reform correctly has no cliff (PTC > $0 above 400% FPL)") - else: - print(f"✗ FAIL: Reform should have PTC above 400% FPL, got ${ptc_reform_above:,.0f}") - - -if __name__ == "__main__": - test_cliff_at_400_fpl() diff --git a/tests/test_app_comprehensive.py b/tests/test_app_comprehensive.py deleted file mode 100644 index 39ceb57..0000000 --- a/tests/test_app_comprehensive.py +++ /dev/null @@ -1,177 +0,0 @@ -""" -Comprehensive verification test for the fixed app.py -Tests all critical scenarios to ensure calculations match notebook values -""" -import sys -sys.path.insert(0, '.') - -# Import the fixed calculate_ptc function from app.py -from app import calculate_ptc - -print("="*70) -print("COMPREHENSIVE APP VERIFICATION TEST") -print("="*70) - -# Test scenarios from notebook -test_cases = [ - { - "name": "Texas couple at 300% FPL ($63,450)", - "age_head": 25, - "age_spouse": 28, - "income": 63450, - "dependent_ages": [], - "state": "TX", - "county": None, - "expected_baseline": 4062, - "expected_reform": 6283, - }, - { - "name": "Texas couple at 400% FPL ($84,600) - THE CLIFF", - "age_head": 25, - "age_spouse": 28, - "income": 84600, - "dependent_ages": [], - "state": "TX", - "county": None, - "expected_baseline": 0, - "expected_reform": 2899, - }, - { - "name": "Texas couple at 138% FPL ($29,187)", - "age_head": 25, - "age_spouse": 28, - "income": 29187, - "dependent_ages": [], - "state": "TX", - "county": None, - "expected_baseline": 9129, - "expected_reform": 10090, - }, - { - "name": "NY family (30+30+3yo) at 300% FPL ($79,950)", - "age_head": 30, - "age_spouse": 30, - "income": 79950, - "dependent_ages": [3], - "state": "NY", - "county": None, - "expected_baseline": 13848, - "expected_reform": 16646, - }, - { - "name": "NY family at 405% FPL ($107,933) - Above cliff", - "age_head": 30, - "age_spouse": 30, - "income": 107933, - "dependent_ages": [3], - "state": "NY", - "county": None, - "expected_baseline": 0, - "expected_reform": 12269, - }, -] - -passed = 0 -failed = 0 -tolerance = 100 # Allow $100 difference due to rounding - -for i, test in enumerate(test_cases, 1): - print(f"\n{'='*70}") - print(f"TEST {i}: {test['name']}") - print(f"{'='*70}") - - # Calculate baseline - ptc_baseline, slcsp = calculate_ptc( - test['age_head'], - test['age_spouse'], - test['income'], - test['dependent_ages'], - test['state'], - test['county'], - use_reform=False - ) - - # Calculate reform - ptc_reform, _ = calculate_ptc( - test['age_head'], - test['age_spouse'], - test['income'], - test['dependent_ages'], - test['state'], - test['county'], - use_reform=True - ) - - # Check results - baseline_diff = abs(ptc_baseline - test['expected_baseline']) - reform_diff = abs(ptc_reform - test['expected_reform']) - - baseline_ok = baseline_diff < tolerance - reform_ok = reform_diff < tolerance - - print(f"\nBaseline PTC:") - print(f" Expected: ${test['expected_baseline']:,.0f}") - print(f" Got: ${ptc_baseline:,.0f}") - print(f" Diff: ${baseline_diff:,.0f}") - print(f" Status: {'✓ PASS' if baseline_ok else '✗ FAIL'}") - - print(f"\nReform PTC:") - print(f" Expected: ${test['expected_reform']:,.0f}") - print(f" Got: ${ptc_reform:,.0f}") - print(f" Diff: ${reform_diff:,.0f}") - print(f" Status: {'✓ PASS' if reform_ok else '✗ FAIL'}") - - print(f"\nSLCSP: ${slcsp:,.0f}/year") - print(f"Difference (Reform - Baseline): ${ptc_reform - ptc_baseline:,.0f}") - - if baseline_ok and reform_ok: - print(f"\n✓ TEST {i} PASSED") - passed += 1 - else: - print(f"\n✗ TEST {i} FAILED") - failed += 1 - -# Edge case tests -print(f"\n{'='*70}") -print("EDGE CASE TESTS") -print(f"{'='*70}") - -# Test with multiple children -print(f"\n--- Test: Family with 3 children ---") -ptc_base, slcsp = calculate_ptc(35, 35, 80000, [5, 8, 12], "TX", None, use_reform=False) -ptc_ref, _ = calculate_ptc(35, 35, 80000, [5, 8, 12], "TX", None, use_reform=True) -print(f"Baseline: ${ptc_base:,.0f}, Reform: ${ptc_ref:,.0f}, SLCSP: ${slcsp:,.0f}") -if ptc_ref > ptc_base and slcsp > 0: - print("✓ PASS - Reform gives higher benefit and SLCSP exists") - passed += 1 -else: - print("✗ FAIL - Something wrong with multi-child calculation") - failed += 1 - -# Test single person -print(f"\n--- Test: Single person at 250% FPL ---") -ptc_base, slcsp = calculate_ptc(40, None, 40000, [], "TX", None, use_reform=False) -ptc_ref, _ = calculate_ptc(40, None, 40000, [], "TX", None, use_reform=True) -print(f"Baseline: ${ptc_base:,.0f}, Reform: ${ptc_ref:,.0f}, SLCSP: ${slcsp:,.0f}") -if ptc_ref >= ptc_base and slcsp > 0: - print("✓ PASS - Single person calculation works") - passed += 1 -else: - print("✗ FAIL - Single person calculation issue") - failed += 1 - -# Summary -print(f"\n{'='*70}") -print("FINAL RESULTS") -print(f"{'='*70}") -print(f"Passed: {passed}") -print(f"Failed: {failed}") -print(f"Total: {passed + failed}") - -if failed == 0: - print("\n✓✓✓ ALL TESTS PASSED! ✓✓✓") - print("The app is working correctly!") -else: - print(f"\n✗ {failed} test(s) failed. Review issues above.") - -sys.exit(0 if failed == 0 else 1) \ No newline at end of file diff --git a/tests/test_app_function.py b/tests/test_app_function.py deleted file mode 100644 index 932bf8a..0000000 --- a/tests/test_app_function.py +++ /dev/null @@ -1,196 +0,0 @@ -""" -Test the actual calculate_ptc function from app.py to see what's wrong -""" -from policyengine_us import Simulation -from policyengine_core.reforms import Reform - -def calculate_ptc(age_head, age_spouse, income, dependent_ages, state, use_reform=False): - """Calculate PTC for baseline or IRA enhanced scenario using 2026 comparison""" - try: - # Build household for 2026 - household = { - "people": { - "you": {"age": {2026: age_head}} - }, - "families": {"your family": {"members": ["you"]}}, - "spm_units": {"your household": {"members": ["you"]}}, - "tax_units": {"your tax unit": {"members": ["you"]}}, - "households": { - "your household": { - "members": ["you"], - "state_name": {2026: state}, - "county_fips": {2026: "48015"} # Default to Austin, TX like notebook - } - } - } - - # Add income and spouse - if age_spouse: - household["people"]["you"]["employment_income"] = {2026: income / 2} - household["people"]["your partner"] = { - "age": {2026: age_spouse}, - "employment_income": {2026: income / 2} - } - household["families"]["your family"]["members"].append("your partner") - household["spm_units"]["your household"]["members"].append("your partner") - household["tax_units"]["your tax unit"]["members"].append("your partner") - household["households"]["your household"]["members"].append("your partner") - household["marital_units"] = {"your marital unit": {"members": ["you", "your partner"]}} - else: - household["people"]["you"]["employment_income"] = {2026: income} - - # Add dependents with proper marital unit structure - for i, dep_age in enumerate(dependent_ages): - child_id = f"your child {i+1}" if i == 0 else f"your child {i+1}" - if i == 0: - child_id = "your first dependent" - elif i == 1: - child_id = "your second dependent" - else: - child_id = f"child_{i+1}" - - household["people"][child_id] = {"age": {2026: dep_age}} - household["families"]["your family"]["members"].append(child_id) - household["spm_units"]["your household"]["members"].append(child_id) - household["tax_units"]["your tax unit"]["members"].append(child_id) - household["households"]["your household"]["members"].append(child_id) - - # Add child's marital unit - if "marital_units" not in household: - household["marital_units"] = {} - household["marital_units"][f"{child_id}'s marital unit"] = { - "members": [child_id], - "marital_unit_id": {2026: i + (2 if age_spouse else 1)} - } - - # Create reform for IRA enhancements (exactly from notebook) - if use_reform: - try: - from policyengine_core.reforms import Reform - reform = Reform.from_dict({ - "gov.aca.ptc_phase_out_rate[0].amount": {"2026-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[1].amount": {"2025-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[2].amount": {"2026-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[3].amount": {"2026-01-01.2100-12-31": 0.02}, - "gov.aca.ptc_phase_out_rate[4].amount": {"2026-01-01.2100-12-31": 0.04}, - "gov.aca.ptc_phase_out_rate[5].amount": {"2026-01-01.2100-12-31": 0.06}, - "gov.aca.ptc_phase_out_rate[6].amount": {"2026-01-01.2100-12-31": 0.085}, - "gov.aca.ptc_income_eligibility[2].amount": {"2026-01-01.2100-12-31": True} - }, country_id="us") - sim = Simulation(situation=household, reform=reform) - except ImportError: - # Fallback if reform import fails - sim = Simulation(situation=household) - else: - # Baseline - original ACA rules for 2026 - sim = Simulation(situation=household) - - ptc = sim.calculate("aca_ptc", map_to="household", period=2026)[0] - slcsp = sim.calculate("slcsp", map_to="household", period=2026)[0] - - return float(max(0, ptc)), float(slcsp) - - except Exception as e: - print(f"Calculation error: {str(e)}") - return 0, 0 - -# Test with Texas couple at 300% FPL -print("="*60) -print("TESTING APP'S calculate_ptc FUNCTION") -print("Texas couple at 300% FPL ($63,450)") -print("="*60) - -ptc_baseline, slcsp = calculate_ptc( - age_head=25, - age_spouse=28, - income=63450, - dependent_ages=[], - state="TX", - use_reform=False -) - -ptc_reform, _ = calculate_ptc( - age_head=25, - age_spouse=28, - income=63450, - dependent_ages=[], - state="TX", - use_reform=True -) - -print(f"\nBaseline PTC: ${ptc_baseline:,.2f}") -print(f"Reform PTC: ${ptc_reform:,.2f}") -print(f"SLCSP: ${slcsp:,.2f}") -print(f"Difference: ${ptc_reform - ptc_baseline:,.2f}") - -print(f"\nExpected: Baseline=$4,062, Reform=$6,283, Diff=$2,221") -print(f"Match: {'✓' if abs(ptc_baseline - 4062) < 50 and abs(ptc_reform - 6283) < 50 else '✗'}") - -# Test with 400% FPL -print("\n" + "="*60) -print("TESTING 400% FPL ($84,600) - THE CLIFF") -print("="*60) - -ptc_baseline_400, _ = calculate_ptc( - age_head=25, - age_spouse=28, - income=84600, - dependent_ages=[], - state="TX", - use_reform=False -) - -ptc_reform_400, _ = calculate_ptc( - age_head=25, - age_spouse=28, - income=84600, - dependent_ages=[], - state="TX", - use_reform=True -) - -print(f"\nBaseline PTC: ${ptc_baseline_400:,.2f} (should be $0)") -print(f"Reform PTC: ${ptc_reform_400:,.2f} (should be ~$2,899)") -print(f"Match: {'✓' if ptc_baseline_400 == 0 and abs(ptc_reform_400 - 2899) < 50 else '✗'}") - -# Test with single person -print("\n" + "="*60) -print("TESTING SINGLE PERSON, NJ, $50k") -print("="*60) - -ptc_baseline_single, slcsp_single = calculate_ptc( - age_head=35, - age_spouse=None, - income=50000, - dependent_ages=[], - state="NJ", - use_reform=False -) - -ptc_reform_single, _ = calculate_ptc( - age_head=35, - age_spouse=None, - income=50000, - dependent_ages=[], - state="NJ", - use_reform=True -) - -print(f"\nBaseline PTC: ${ptc_baseline_single:,.2f}") -print(f"Reform PTC: ${ptc_reform_single:,.2f}") -print(f"SLCSP: ${slcsp_single:,.2f}") -print(f"Difference: ${ptc_reform_single - ptc_baseline_single:,.2f}") - -print("\n" + "="*60) -print("CONCLUSION:") -if all([ - abs(ptc_baseline - 4062) < 50, - abs(ptc_reform - 6283) < 50, - ptc_baseline_400 == 0, - abs(ptc_reform_400 - 2899) < 50 -]): - print("✓ The app's calculate_ptc function works correctly!") - print("The issue must be somewhere else in the app.") -else: - print("✗ The app's calculate_ptc function has issues.") -print("="*60) \ No newline at end of file diff --git a/tests/test_app_imports.py b/tests/test_app_imports.py deleted file mode 100644 index b3c6ec9..0000000 --- a/tests/test_app_imports.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Test that app imports and basic functions work.""" -import sys -sys.path.insert(0, '.') - - -def test_app_imports(): - """Test that the app module can be imported without errors.""" - try: - import app - assert hasattr(app, 'main') - assert hasattr(app, 'calculate_ptc') - assert hasattr(app, 'get_fpl') - assert hasattr(app, 'COLORS') - except Exception as e: - raise AssertionError(f"Failed to import app: {e}") - - -def test_colors_defined(): - """Test that color palette is properly defined.""" - import app - assert 'primary' in app.COLORS - assert 'gray' in app.COLORS - assert 'green' in app.COLORS - assert app.COLORS['primary'] == '#2C6496' - assert app.COLORS['gray'] == '#808080' - - -def test_fpl_calculation(): - """Test Federal Poverty Level calculation.""" - import app - - # Test known FPL values for 2026 - assert app.get_fpl(1) == 15570 - assert app.get_fpl(2) == 21130 - assert app.get_fpl(4) == 32200 - - # Test that it increases for larger households - assert app.get_fpl(9) > app.get_fpl(8) - - -def test_fpl_percentage(): - """Test FPL percentage calculation.""" - import app - - # Single person at 100% FPL - pct = app.calculate_fpl_percentage(15570, 1) - assert pct == 100.0 - - # Family of 4 at 300% FPL - income = 32200 * 3 - pct = app.calculate_fpl_percentage(income, 4) - assert 299 < pct < 301 # Allow for rounding - - -if __name__ == "__main__": - test_app_imports() - test_colors_defined() - test_fpl_calculation() - test_fpl_percentage() - print("✓ All tests passed!") diff --git a/tests/test_austin.py b/tests/test_austin.py deleted file mode 100644 index dba2cd6..0000000 --- a/tests/test_austin.py +++ /dev/null @@ -1,91 +0,0 @@ -from policyengine_us import Simulation - -# Austin, TX couple - 25 and 28 years old, $60k income -household = { - "people": { - "you": { - "age": {2025: 25, 2026: 25}, - "employment_income": {2025: 30000, 2026: 30000} # Split income - }, - "your partner": { - "age": {2025: 28, 2026: 28}, - "employment_income": {2025: 30000, 2026: 30000} # Split income - } - }, - "families": { - "your family": { - "members": ["you", "your partner"] - } - }, - "tax_units": { - "your tax unit": { - "members": ["you", "your partner"] - } - }, - "households": { - "your household": { - "members": ["you", "your partner"], - "state_name": {2025: "TX", 2026: "TX"} - } - }, - "marital_units": { - "your marital unit": { - "members": ["you", "your partner"] - } - } -} - -# Calculate for 2025 (with IRA enhancements) -sim_2025 = Simulation(situation=household) -ptc_2025 = sim_2025.calculate("aca_ptc", map_to="household", period=2025)[0] -slcsp_2025 = sim_2025.calculate("slcsp", map_to="household", period=2025)[0] - -# Calculate for 2026 (after IRA expires) -sim_2026 = Simulation(situation=household) -ptc_2026 = sim_2026.calculate("aca_ptc", map_to="household", period=2026)[0] -slcsp_2026 = sim_2026.calculate("slcsp", map_to="household", period=2026)[0] - -# Calculate FPL percentage -fpl_2026_couple = 21130 # Couple FPL -fpl_pct = (60000 / fpl_2026_couple) * 100 - -print("="*60) -print("AUSTIN, TEXAS") -print("Married couple, ages 25 & 28, $60,000 household income") -print("="*60) -print(f"\nIncome as % of FPL: {fpl_pct:.0f}%") -print(f"\nBenchmark Plan (SLCSP):") -print(f" 2025: ${slcsp_2025:,.2f}/year") -print(f" 2026: ${slcsp_2026:,.2f}/year") - -print(f"\nPremium Tax Credit:") -print(f" 2025 (with IRA): ${ptc_2025:,.2f}/year (${ptc_2025/12:,.2f}/month)") -print(f" 2026 (after expire): ${ptc_2026:,.2f}/year (${ptc_2026/12:,.2f}/month)") - -difference = ptc_2025 - ptc_2026 -print(f"\nIMPACT OF IRA EXPIRATION:") -if difference > 0: - print(f" Loss: ${difference:,.2f}/year (${difference/12:,.2f}/month)") - print(f" This couple will pay ${difference/12:,.2f} more per month for health insurance") -elif difference < 0: - print(f" Gain: ${abs(difference):,.2f}/year (${abs(difference)/12:,.2f}/month)") -else: - print(f" No change") - -# Calculate what percentage of income they pay -if slcsp_2025 > 0 and ptc_2025 >= 0: - contrib_2025 = slcsp_2025 - ptc_2025 - contrib_2025_pct = (contrib_2025 / 60000) * 100 - print(f"\nYour contribution in 2025: ${contrib_2025:,.2f}/year ({contrib_2025_pct:.1f}% of income)") - -if slcsp_2026 > 0 and ptc_2026 >= 0: - contrib_2026 = slcsp_2026 - ptc_2026 - contrib_2026_pct = (contrib_2026 / 60000) * 100 - print(f"Your contribution in 2026: ${contrib_2026:,.2f}/year ({contrib_2026_pct:.1f}% of income)") - -# Compare to notebook example at 300% FPL ($63,450) -print(f"\n" + "="*60) -print("Comparison to notebook Texas couple at 300% FPL ($63,450):") -print("The notebook showed: baseline=$4,062, reform=$6,283") -print("(Note: notebook tested extending IRA vs letting expire)") -print("="*60) \ No newline at end of file diff --git a/tests/test_calculate_ptc.py b/tests/test_calculate_ptc.py deleted file mode 100644 index 676e157..0000000 --- a/tests/test_calculate_ptc.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Test calculate_ptc function.""" - -import sys - -sys.path.insert(0, ".") - -from app import calculate_ptc - - -def test_simple_calculation(): - """Test a simple PTC calculation.""" - print("Testing simple single person calculation...") - - # Single person, age 35, $50,000 income in TX - ptc_reform, slcsp, fpl, fpl_pct = calculate_ptc( - age_head=35, - age_spouse=None, - income=50000, - dependent_ages=[], - state="TX", - county_name=None, - use_reform=True, - ) - - print(f"Reform PTC: ${ptc_reform:,.0f}") - print(f"SLCSP: ${slcsp:,.0f}") - - # Should get some PTC and SLCSP > 0 - assert slcsp > 0, f"SLCSP should be > 0, got {slcsp}" - assert ptc_reform >= 0, f"PTC should be >= 0, got {ptc_reform}" - - print("✓ Simple calculation works") - - -def test_baseline_vs_reform(): - """Test baseline vs reform calculation.""" - print("\nTesting baseline vs reform...") - - # Couple at 300% FPL - ptc_reform, slcsp, fpl, fpl_pct = calculate_ptc( - age_head=25, - age_spouse=28, - income=63450, - dependent_ages=[], - state="TX", - county_name=None, - use_reform=True, - ) - - ptc_baseline, _, _, _ = calculate_ptc( - age_head=25, - age_spouse=28, - income=63450, - dependent_ages=[], - state="TX", - county_name=None, - use_reform=False, - ) - - print(f"Reform PTC: ${ptc_reform:,.0f}") - print(f"Baseline PTC: ${ptc_baseline:,.0f}") - print(f"SLCSP: ${slcsp:,.0f}") - - assert slcsp > 0, "SLCSP should be > 0" - # Reform should give more credits than baseline at 300% FPL - assert ( - ptc_reform >= ptc_baseline - ), f"Reform ({ptc_reform}) should be >= baseline ({ptc_baseline})" - - print("✓ Baseline vs reform works") - - -if __name__ == "__main__": - try: - test_simple_calculation() - test_baseline_vs_reform() - print("\n✅ All tests passed!") - except Exception as e: - print(f"\n❌ Test failed: {e}") - import traceback - - traceback.print_exc() - sys.exit(1) diff --git a/tests/test_cliff_fixed.py b/tests/test_cliff_fixed.py deleted file mode 100644 index fb77903..0000000 --- a/tests/test_cliff_fixed.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Test cliff works with employment_income.""" -import sys -sys.path.insert(0, '.') - -from app import calculate_ptc, get_fpl - -# 60yo couple -fpl_2 = get_fpl(2) -income_at_405_fpl = int(fpl_2 * 4.05) - -print(f"Testing 60yo couple at 405% FPL (${income_at_405_fpl:,})") -print(f"FPL for 2: ${fpl_2:,}, 400% FPL: ${fpl_2 * 4:,}") - -ptc_baseline, slcsp = calculate_ptc(60, 60, income_at_405_fpl, [], "WV", None, use_reform=False) -ptc_reform, _ = calculate_ptc(60, 60, income_at_405_fpl, [], "WV", None, use_reform=True) - -print(f"\nBaseline PTC (should be $0): ${ptc_baseline:,.0f}") -print(f"Reform PTC (should be >$0): ${ptc_reform:,.0f}") -print(f"SLCSP: ${slcsp:,.0f}") - -print("\n" + "="*70) -if ptc_baseline == 0 and ptc_reform > 0: - print("✓ CLIFF WORKS CORRECTLY!") - print(f" Baseline has cliff at 400% FPL (PTC = $0)") - print(f" Reform removes cliff (PTC = ${ptc_reform:,.0f})") -else: - print(f"✗ CLIFF BROKEN!") - print(f" Expected: Baseline=$0, Reform>$0") - print(f" Got: Baseline=${ptc_baseline:,.0f}, Reform=${ptc_reform:,.0f}") diff --git a/tests/test_cliff_simple.py b/tests/test_cliff_simple.py deleted file mode 100644 index 2da7598..0000000 --- a/tests/test_cliff_simple.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Simple cliff test.""" -import sys -sys.path.insert(0, '.') - -from policyengine_us import Simulation -from policyengine_core.reforms import Reform -from app import get_fpl - -# 60yo couple in WV -fpl_2 = get_fpl(2) -income_at_405_fpl = int(fpl_2 * 4.05) - -print(f"FPL for 2 people: ${fpl_2:,}") -print(f"405% FPL: ${income_at_405_fpl:,}") - -situation = { - 'people': { - 'p1': {'age': {2026: 60}}, - 'p2': {'age': {2026: 60}} - }, - 'families': {'f1': {'members': ['p1', 'p2']}}, - 'marital_units': {'mu1': {'members': ['p1', 'p2']}}, - 'spm_units': {'spm1': {'members': ['p1', 'p2']}}, - 'tax_units': {'tu1': {'members': ['p1', 'p2'], 'aca_magi': {2026: income_at_405_fpl}}}, - 'households': {'h1': {'members': ['p1', 'p2'], 'state_name': {2026: 'WV'}}} -} - -# Test baseline (should be $0 above 400% FPL) -print("\n=== BASELINE (no reform) ===") -sim_baseline = Simulation(situation=situation) -ptc_baseline = sim_baseline.calculate('aca_ptc', period=2026)[0] -print(f"PTC at 405% FPL: ${ptc_baseline:,.0f}") - -# Test with reform (should have PTC above 400% FPL) -print("\n=== WITH REFORM ===") -reform = Reform.from_dict({ - "gov.aca.ptc_phase_out_rate[0].amount": {"2026-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[1].amount": {"2025-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[2].amount": {"2026-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[3].amount": {"2026-01-01.2100-12-31": 0.02}, - "gov.aca.ptc_phase_out_rate[4].amount": {"2026-01-01.2100-12-31": 0.04}, - "gov.aca.ptc_phase_out_rate[5].amount": {"2026-01-01.2100-12-31": 0.06}, - "gov.aca.ptc_phase_out_rate[6].amount": {"2026-01-01.2100-12-31": 0.085}, - "gov.aca.ptc_income_eligibility[2].amount": {"2026-01-01.2100-12-31": True} -}, country_id="us") - -sim_reform = Simulation(situation=situation, reform=reform) -ptc_reform = sim_reform.calculate('aca_ptc', period=2026)[0] -print(f"PTC at 405% FPL: ${ptc_reform:,.0f}") - -print("\n" + "="*70) -if ptc_baseline == 0 and ptc_reform > 0: - print("✓ CLIFF WORKS: Baseline=$0, Reform>$0 above 400% FPL") -else: - print(f"✗ CLIFF BROKEN: Baseline=${ptc_baseline:,.0f}, Reform=${ptc_reform:,.0f}") diff --git a/tests/test_comparison.py b/tests/test_comparison.py deleted file mode 100644 index 688bf0c..0000000 --- a/tests/test_comparison.py +++ /dev/null @@ -1,93 +0,0 @@ -from policyengine_us import Simulation - -print("Testing different household structures to find the discrepancy...\n") - -# Test 1: Exact match to our test script -household_v1 = { - "people": { - "you": { - "age": {2025: 35, 2026: 36}, - "employment_income": {2025: 50000, 2026: 50000} - } - }, - "families": {"your family": {"members": ["you"]}}, - "tax_units": {"your tax unit": {"members": ["you"]}}, - "households": { - "your household": { - "members": ["you"], - "state_name": {2025: "NJ", 2026: "NJ"} - } - } -} - -# Test 2: How the app might be structuring it (no marital units) -household_v2 = { - "people": { - "you": { - "age": {2025: 35, 2026: 35}, # Maybe not aging? - "employment_income": {2025: 50000, 2026: 50000} - } - }, - "families": {"your family": {"members": ["you"]}}, - "tax_units": {"your tax unit": {"members": ["you"]}}, - "households": { - "your household": { - "members": ["you"], - "state_name": {2025: "NJ", 2026: "NJ"} - } - } -} - -# Test 3: With county specified (though we didn't in app) -household_v3 = { - "people": { - "you": { - "age": {2025: 35, 2026: 35}, - "employment_income": {2025: 50000, 2026: 50000} - } - }, - "families": {"your family": {"members": ["you"]}}, - "tax_units": {"your tax unit": {"members": ["you"]}}, - "households": { - "your household": { - "members": ["you"], - "state_name": {2025: "NJ", 2026: "NJ"}, - "county": {2025: "ESSEX_COUNTY_NJ", 2026: "ESSEX_COUNTY_NJ"} - } - } -} - -print("Version 1: Age 35->36, no county") -sim = Simulation(situation=household_v1) -ptc_2025 = sim.calculate("aca_ptc", map_to="household", period=2025)[0] -ptc_2026 = sim.calculate("aca_ptc", map_to="household", period=2026)[0] -print(f" 2025: ${ptc_2025:,.2f}") -print(f" 2026: ${ptc_2026:,.2f}") -print(f" Difference: ${ptc_2025 - ptc_2026:,.2f}\n") - -print("Version 2: Age stays 35, no county") -sim = Simulation(situation=household_v2) -ptc_2025 = sim.calculate("aca_ptc", map_to="household", period=2025)[0] -ptc_2026 = sim.calculate("aca_ptc", map_to="household", period=2026)[0] -print(f" 2025: ${ptc_2025:,.2f}") -print(f" 2026: ${ptc_2026:,.2f}") -print(f" Difference: ${ptc_2025 - ptc_2026:,.2f}\n") - -print("Version 3: Age 35, with Essex County") -sim = Simulation(situation=household_v3) -ptc_2025 = sim.calculate("aca_ptc", map_to="household", period=2025)[0] -ptc_2026 = sim.calculate("aca_ptc", map_to="household", period=2026)[0] -print(f" 2025: ${ptc_2025:,.2f}") -print(f" 2026: ${ptc_2026:,.2f}") -print(f" Difference: ${ptc_2025 - ptc_2026:,.2f}\n") - -# Check SLCSP differences -print("Checking SLCSP (benchmark plan costs):") -for i, (name, hh) in enumerate([("v1", household_v1), ("v2", household_v2), ("v3", household_v3)]): - sim = Simulation(situation=hh) - slcsp_2025 = sim.calculate("slcsp", map_to="household", period=2025)[0] - slcsp_2026 = sim.calculate("slcsp", map_to="household", period=2026)[0] - print(f" {name}: 2025=${slcsp_2025:,.2f}, 2026=${slcsp_2026:,.2f}") - -print("\nThe app said: 2025=$2,197, 2026=$933, Difference=$1,264") -print("Our test said: 2025=$2,197.29, 2026=$969.85, Difference=$1,227.44") \ No newline at end of file diff --git a/tests/test_debug_app.py b/tests/test_debug_app.py deleted file mode 100644 index 927e886..0000000 --- a/tests/test_debug_app.py +++ /dev/null @@ -1,32 +0,0 @@ -"""Debug Streamlit app to see what's rendering.""" -import sys -sys.path.insert(0, '.') - -from streamlit.testing.v1 import AppTest - - -def debug_app(): - """Debug what's in the app.""" - at = AppTest.from_file("app.py") - at.run() - - print("=== APP STATE ===") - print(f"Exception: {at.exception}") - print(f"Main elements: {len(at.main)}") - print(f"Sidebar elements: {len(at.sidebar)}") - - print("\n=== MAIN CONTENT ===") - for i, element in enumerate(at.main): - print(f"{i}: {type(element).__name__}") - - print("\n=== SIDEBAR CONTENT ===") - for i, element in enumerate(at.sidebar): - print(f"{i}: {type(element).__name__}") - - # Check if there are any errors in rendering - if at.exception: - print(f"\n=== EXCEPTION ===") - print(at.exception) - -if __name__ == "__main__": - debug_app() diff --git a/tests/test_eligibility.py b/tests/test_eligibility.py deleted file mode 100644 index cb7d2dd..0000000 --- a/tests/test_eligibility.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Test ACA eligibility with different input methods.""" -import sys -sys.path.insert(0, '.') - -from policyengine_us import Simulation -from policyengine_core.reforms import Reform - -reform = Reform.from_dict({ - "gov.aca.ptc_income_eligibility[2].amount": {"2026-01-01.2100-12-31": True} -}, country_id="us") - -print("Testing 60yo couple at $85,000 income") - -# Test 1: Setting aca_magi directly -print("\n=== Setting aca_magi directly ===") -sit1 = { - 'people': {'p1': {'age': {2026: 60}}, 'p2': {'age': {2026: 60}}}, - 'families': {'f1': {'members': ['p1', 'p2']}}, - 'marital_units': {'mu1': {'members': ['p1', 'p2']}}, - 'spm_units': {'spm1': {'members': ['p1', 'p2']}}, - 'tax_units': {'tu1': {'members': ['p1', 'p2'], 'aca_magi': {2026: 85000}}}, - 'households': {'h1': {'members': ['p1', 'p2'], 'state_name': {2026: 'WV'}}} -} - -sim1 = Simulation(situation=sit1, reform=reform) -eligible1 = sim1.calculate('is_aca_ptc_eligible', period=2026) -filing1 = sim1.calculate('filing_status', period=2026) -magi1 = sim1.calculate('aca_magi', period=2026) -ptc1 = sim1.calculate('aca_ptc', period=2026) - -print(f" Person 1 eligible: {eligible1[0]}") -print(f" Person 2 eligible: {eligible1[1]}") -print(f" Filing status: {filing1[0]}") -print(f" MAGI: ${magi1[0]:,.0f}") -print(f" PTC: ${ptc1[0]:,.0f}") - -# Test 2: Setting employment_income -print("\n=== Setting employment_income ===") -sit2 = { - 'people': { - 'p1': {'age': {2026: 60}, 'employment_income': {2026: 42500}}, - 'p2': {'age': {2026: 60}, 'employment_income': {2026: 42500}} - }, - 'families': {'f1': {'members': ['p1', 'p2']}}, - 'marital_units': {'mu1': {'members': ['p1', 'p2']}}, - 'spm_units': {'spm1': {'members': ['p1', 'p2']}}, - 'tax_units': {'tu1': {'members': ['p1', 'p2']}}, - 'households': {'h1': {'members': ['p1', 'p2'], 'state_name': {2026: 'WV'}}} -} - -sim2 = Simulation(situation=sit2, reform=reform) -eligible2 = sim2.calculate('is_aca_ptc_eligible', period=2026) -filing2 = sim2.calculate('filing_status', period=2026) -magi2 = sim2.calculate('aca_magi', period=2026) -ptc2 = sim2.calculate('aca_ptc', period=2026) - -print(f" Person 1 eligible: {eligible2[0]}") -print(f" Person 2 eligible: {eligible2[1]}") -print(f" Filing status: {filing2[0]}") -print(f" MAGI: ${magi2[0]:,.0f}") -print(f" PTC: ${ptc2[0]:,.0f}") diff --git a/tests/test_employment_vs_magi.py b/tests/test_employment_vs_magi.py deleted file mode 100644 index 5fa8ad4..0000000 --- a/tests/test_employment_vs_magi.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Test employment_income vs aca_magi input.""" -import sys -sys.path.insert(0, '.') - -from policyengine_us import Simulation -from policyengine_core.reforms import Reform -from app import get_fpl - -fpl_2 = get_fpl(2) -income = int(fpl_2 * 4.05) - -print(f"Testing 60yo couple at 405% FPL (${income:,})") - -reform = Reform.from_dict({ - "gov.aca.ptc_income_eligibility[2].amount": {"2026-01-01.2100-12-31": True} -}, country_id="us") - -# Test 1: Setting aca_magi directly -print("\n=== Setting aca_magi directly ===") -sit1 = { - 'people': {'p1': {'age': {2026: 60}}, 'p2': {'age': {2026: 60}}}, - 'families': {'f1': {'members': ['p1', 'p2']}}, - 'marital_units': {'mu1': {'members': ['p1', 'p2']}}, - 'spm_units': {'spm1': {'members': ['p1', 'p2']}}, - 'tax_units': {'tu1': {'members': ['p1', 'p2'], 'aca_magi': {2026: income}}}, - 'households': {'h1': {'members': ['p1', 'p2'], 'state_name': {2026: 'WV'}}} -} - -sim1 = Simulation(situation=sit1, reform=reform) -ptc1 = sim1.calculate('aca_ptc', period=2026)[0] -print(f"PTC with reform: ${ptc1:,.0f}") - -# Test 2: Setting employment_income -print("\n=== Setting employment_income ===") -sit2 = { - 'people': { - 'p1': {'age': {2026: 60}, 'employment_income': {2026: income/2}}, - 'p2': {'age': {2026: 60}, 'employment_income': {2026: income/2}} - }, - 'families': {'f1': {'members': ['p1', 'p2']}}, - 'marital_units': {'mu1': {'members': ['p1', 'p2']}}, - 'spm_units': {'spm1': {'members': ['p1', 'p2']}}, - 'tax_units': {'tu1': {'members': ['p1', 'p2']}}, - 'households': {'h1': {'members': ['p1', 'p2'], 'state_name': {2026: 'WV'}}} -} - -sim2 = Simulation(situation=sit2, reform=reform) -ptc2 = sim2.calculate('aca_ptc', period=2026)[0] -magi2 = sim2.calculate('aca_magi', period=2026)[0] -print(f"Calculated MAGI: ${magi2:,.0f}") -print(f"PTC with reform: ${ptc2:,.0f}") - -print("\n" + "="*70) -if ptc2 > 0: - print(f"✓ employment_income approach works: PTC = ${ptc2:,.0f}") - print("✗ aca_magi direct setting doesn't work for reforms") -else: - print("✗ Neither approach works!") diff --git a/tests/test_household.py b/tests/test_household.py index 48abbce..b3a9e5b 100644 --- a/tests/test_household.py +++ b/tests/test_household.py @@ -92,4 +92,4 @@ def test_with_axes(): assert "axes" in situation assert situation["axes"][0][0]["name"] == "employment_income" - assert situation["axes"][0][0]["count"] == 10_001 + assert situation["axes"][0][0]["count"] == 1_001 diff --git a/tests/test_labels.py b/tests/test_labels.py deleted file mode 100644 index 7f52256..0000000 --- a/tests/test_labels.py +++ /dev/null @@ -1,56 +0,0 @@ -from policyengine_us import Simulation -from policyengine_core.reforms import Reform - -# Test household at 300% FPL (should get credits in both scenarios) -household = { - 'people': {'you': {'age': {2026: 30}, 'employment_income': {2026: 31650}}}, - 'families': {'your family': {'members': ['you']}}, - 'tax_units': {'your tax unit': {'members': ['you']}}, - 'households': {'your household': {'members': ['you'], 'state_name': {2026: 'TX'}}} -} - -# Baseline (current law - IRA still in effect in 2026) -sim_baseline = Simulation(situation=household) -ptc_baseline = sim_baseline.calculate('aca_ptc', map_to='household', period=2026)[0] - -# Reform that reinstates 400% cap (original ACA) -reform = Reform.from_dict({ - 'gov.aca.ptc_phase_out_rate[0].amount': {'2026-01-01.2100-12-31': 0}, - 'gov.aca.ptc_phase_out_rate[1].amount': {'2026-01-01.2100-12-31': 0}, - 'gov.aca.ptc_phase_out_rate[2].amount': {'2026-01-01.2100-12-31': 0}, - 'gov.aca.ptc_phase_out_rate[3].amount': {'2026-01-01.2100-12-31': 0.02}, - 'gov.aca.ptc_phase_out_rate[4].amount': {'2026-01-01.2100-12-31': 0.04}, - 'gov.aca.ptc_phase_out_rate[5].amount': {'2026-01-01.2100-12-31': 0.06}, - 'gov.aca.ptc_phase_out_rate[6].amount': {'2026-01-01.2100-12-31': 0.085}, - 'gov.aca.ptc_income_eligibility[2].amount': {'2026-01-01.2100-12-31': False} # Reinstates 400% cap -}, country_id='us') - -sim_reform = Simulation(situation=household, reform=reform) -ptc_reform = sim_reform.calculate('aca_ptc', map_to='household', period=2026)[0] - -print('Single person at 300% FPL in TX:') -print(f' Current law (IRA enhanced): ${ptc_baseline:,.2f}') -print(f' After expiration (original ACA): ${ptc_reform:,.2f}') -print(f' Person LOSES: ${ptc_baseline - ptc_reform:,.2f} when IRA expires') - -# Test at 450% FPL (above the cliff) -household_450 = household.copy() -household_450['people']['you']['employment_income'] = {2026: 70000} - -sim_450_base = Simulation(situation=household_450) -sim_450_reform = Simulation(situation=household_450, reform=reform) - -ptc_450_base = sim_450_base.calculate('aca_ptc', map_to='household', period=2026)[0] -ptc_450_reform = sim_450_reform.calculate('aca_ptc', map_to='household', period=2026)[0] - -print('\nSingle person at ~450% FPL in TX:') -print(f' Current law (IRA enhanced): ${ptc_450_base:,.2f}') -print(f' After expiration (original ACA): ${ptc_450_reform:,.2f}') -print(f' Person LOSES: ${ptc_450_base:,.2f} when IRA expires (the cliff!)') - -print('\n' + '='*60) -print('LABEL CHECK:') -print('- Baseline = Current law with IRA enhancements (NO cap)') -print('- Reform = Original ACA rules (400% FPL cap)') -print('- Our app shows what people LOSE when IRA expires') -print('='*60) \ No newline at end of file diff --git a/tests/test_nj.py b/tests/test_nj.py deleted file mode 100644 index 5ca601d..0000000 --- a/tests/test_nj.py +++ /dev/null @@ -1,86 +0,0 @@ -from policyengine_us import Simulation - -# New Jersey, Essex County, 35 year old, $50k income -household = { - "people": { - "you": { - "age": { - 2025: 35, - 2026: 36 # Will be 36 in 2026 - }, - "employment_income": { - 2025: 50000, - 2026: 50000 - } - } - }, - "families": { - "your family": { - "members": ["you"] - } - }, - "tax_units": { - "your tax unit": { - "members": ["you"] - } - }, - "households": { - "your household": { - "members": ["you"], - "state_name": { - 2025: "NJ", - 2026: "NJ" - } - } - } -} - -# Calculate for 2025 (with IRA enhancements) -sim_2025 = Simulation(situation=household) -ptc_2025 = sim_2025.calculate("aca_ptc", map_to="household", period=2025)[0] -slcsp_2025 = sim_2025.calculate("slcsp", map_to="household", period=2025)[0] - -# Calculate for 2026 (after IRA expires) -sim_2026 = Simulation(situation=household) -ptc_2026 = sim_2026.calculate("aca_ptc", map_to="household", period=2026)[0] -slcsp_2026 = sim_2026.calculate("slcsp", map_to="household", period=2026)[0] - -# Calculate FPL percentage -fpl_2026 = 15570 # Single person FPL -fpl_pct = (50000 / fpl_2026) * 100 - -print("="*60) -print("NEW JERSEY - ESSEX COUNTY") -print("35 year old, single, $50,000 income") -print("="*60) -print(f"\nIncome as % of FPL: {fpl_pct:.0f}%") -print(f"\nBenchmark Plan (SLCSP):") -print(f" 2025: ${slcsp_2025:,.2f}/year") -print(f" 2026: ${slcsp_2026:,.2f}/year") - -print(f"\nPremium Tax Credit:") -print(f" 2025 (with IRA): ${ptc_2025:,.2f}/year (${ptc_2025/12:,.2f}/month)") -print(f" 2026 (after expire): ${ptc_2026:,.2f}/year (${ptc_2026/12:,.2f}/month)") - -difference = ptc_2025 - ptc_2026 -print(f"\nIMPACT OF IRA EXPIRATION:") -if difference > 0: - print(f" Loss: ${difference:,.2f}/year (${difference/12:,.2f}/month)") - print(f" This person will pay ${difference/12:,.2f} more per month for health insurance") -elif difference < 0: - print(f" Gain: ${abs(difference):,.2f}/year (${abs(difference)/12:,.2f}/month)") -else: - print(f" No change") - -# Calculate what percentage of income they pay -if ptc_2025 > 0: - contrib_2025 = slcsp_2025 - ptc_2025 - contrib_2025_pct = (contrib_2025 / 50000) * 100 - print(f"\nYour contribution in 2025: ${contrib_2025:,.2f}/year ({contrib_2025_pct:.1f}% of income)") - -if ptc_2026 > 0: - contrib_2026 = slcsp_2026 - ptc_2026 - contrib_2026_pct = (contrib_2026 / 50000) * 100 - print(f"Your contribution in 2026: ${contrib_2026:,.2f}/year ({contrib_2026_pct:.1f}% of income)") -else: - print(f"Your contribution in 2026: Full cost of insurance (no subsidy)") \ No newline at end of file diff --git a/tests/test_reform_verification.py b/tests/test_reform_verification.py deleted file mode 100644 index 66f4774..0000000 --- a/tests/test_reform_verification.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -Verify that the reform is actually being applied in the app's calculate_ptc function -""" -from policyengine_us import Simulation -from policyengine_core.reforms import Reform - -# Texas couple at 300% FPL - from notebook -household = { - "people": { - "you": { - "age": {2026: 25}, - "employment_income": {2026: 31725} # Split $63,450 - }, - "your partner": { - "age": {2026: 28}, - "employment_income": {2026: 31725} - } - }, - "families": {"your family": {"members": ["you", "your partner"]}}, - "spm_units": {"your household": {"members": ["you", "your partner"]}}, - "tax_units": {"your tax unit": {"members": ["you", "your partner"]}}, - "households": { - "your household": { - "members": ["you", "your partner"], - "state_name": {2026: "TX"}, - "county_fips": {2026: "48015"} - } - }, - "marital_units": {"your marital unit": {"members": ["you", "your partner"]}} -} - -print("="*60) -print("VERIFYING REFORM APPLICATION") -print("Texas couple at 300% FPL ($63,450)") -print("="*60) - -# Baseline (no reform) -sim_baseline = Simulation(situation=household) -ptc_baseline = sim_baseline.calculate("aca_ptc", map_to="household", period=2026)[0] -slcsp = sim_baseline.calculate("slcsp", map_to="household", period=2026)[0] - -print(f"\n1. BASELINE (Original ACA for 2026):") -print(f" PTC: ${ptc_baseline:,.2f}") -print(f" SLCSP: ${slcsp:,.2f}") - -# Reform (IRA extension) -reform = Reform.from_dict({ - "gov.aca.ptc_phase_out_rate[0].amount": {"2026-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[1].amount": {"2025-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[2].amount": {"2026-01-01.2100-12-31": 0}, - "gov.aca.ptc_phase_out_rate[3].amount": {"2026-01-01.2100-12-31": 0.02}, - "gov.aca.ptc_phase_out_rate[4].amount": {"2026-01-01.2100-12-31": 0.04}, - "gov.aca.ptc_phase_out_rate[5].amount": {"2026-01-01.2100-12-31": 0.06}, - "gov.aca.ptc_phase_out_rate[6].amount": {"2026-01-01.2100-12-31": 0.085}, - "gov.aca.ptc_income_eligibility[2].amount": {"2026-01-01.2100-12-31": True} -}, country_id="us") - -sim_reform = Simulation(situation=household, reform=reform) -ptc_reform = sim_reform.calculate("aca_ptc", map_to="household", period=2026)[0] - -print(f"\n2. WITH REFORM (IRA extension to 2026):") -print(f" PTC: ${ptc_reform:,.2f}") -print(f" SLCSP: ${slcsp:,.2f}") - -print(f"\n3. DIFFERENCE:") -print(f" Reform PTC - Baseline PTC = ${ptc_reform - ptc_baseline:,.2f}") -print(f" (Reform should be HIGHER)") - -print(f"\n4. EXPECTED FROM NOTEBOOK:") -print(f" Baseline: $4,062") -print(f" Reform: $6,283") -print(f" Difference: $2,221") - -print(f"\n5. MATCH CHECK:") -baseline_match = abs(ptc_baseline - 4062) < 50 -reform_match = abs(ptc_reform - 6283) < 50 -print(f" Baseline matches: {'✓' if baseline_match else '✗'} (${ptc_baseline:,.0f} vs $4,062)") -print(f" Reform matches: {'✓' if reform_match else '✗'} (${ptc_reform:,.0f} vs $6,283)") - -if baseline_match and reform_match: - print(f"\n✓ SUCCESS: Reform is working correctly!") -else: - print(f"\n✗ ISSUE: Values don't match expected") - -# Now test with 400% FPL - where the cliff happens -print("\n" + "="*60) -print("TESTING 400% FPL ($84,600) - THE CLIFF") -print("="*60) - -household_400 = household.copy() -household_400["people"]["you"]["employment_income"] = {2026: 42300} -household_400["people"]["your partner"]["employment_income"] = {2026: 42300} - -sim_baseline_400 = Simulation(situation=household_400) -ptc_baseline_400 = sim_baseline_400.calculate("aca_ptc", map_to="household", period=2026)[0] - -sim_reform_400 = Simulation(situation=household_400, reform=reform) -ptc_reform_400 = sim_reform_400.calculate("aca_ptc", map_to="household", period=2026)[0] - -print(f"\nBaseline PTC: ${ptc_baseline_400:,.2f} (should be $0 - above cliff)") -print(f"Reform PTC: ${ptc_reform_400:,.2f} (should be ~$2,899 - no cliff)") -print(f"\nExpected from notebook: Baseline=$0, Reform=$2,899") - -cliff_test = ptc_baseline_400 == 0 and abs(ptc_reform_400 - 2899) < 50 -print(f"\n✓ Cliff test: {'PASS' if cliff_test else 'FAIL'}") \ No newline at end of file diff --git a/tests/test_show_errors.py b/tests/test_show_errors.py deleted file mode 100644 index 42c5388..0000000 --- a/tests/test_show_errors.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Show actual errors in the app.""" -import sys -sys.path.insert(0, '.') - -from streamlit.testing.v1 import AppTest - - -def show_errors(): - """Show errors in the app.""" - at = AppTest.from_file("app.py") - at.run() - - print("=== ERRORS ===") - for element in at.main: - if hasattr(element, 'value') and 'Error' in str(type(element).__name__): - print(f"Error: {element.value}") - if hasattr(element, 'body'): - print(f"Body: {element.body}") - - # Try to access error blocks differently - errors = [e for e in at.main if 'Error' in str(type(e).__name__)] - print(f"\nFound {len(errors)} errors") - - for i, error in enumerate(errors): - print(f"\nError {i+1}:") - print(dir(error)) - if hasattr(error, 'value'): - print(f" Value: {error.value}") - if hasattr(error, 'message'): - print(f" Message: {error.message}") - if hasattr(error, 'icon'): - print(f" Icon: {error.icon}") - -if __name__ == "__main__": - show_errors() diff --git a/tests/test_streamlit_app.py b/tests/test_streamlit_app.py deleted file mode 100644 index 2ea82da..0000000 --- a/tests/test_streamlit_app.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Test Streamlit app execution.""" -import sys -sys.path.insert(0, '.') - -from streamlit.testing.v1 import AppTest - - -def test_app_runs(): - """Test that the app runs without errors.""" - at = AppTest.from_file("app.py") - - # Run the app - at.run() - - # Check that there are no exceptions - assert not at.exception, f"App raised exception: {at.exception}" - - print("✓ App loads without errors") - - -def test_sidebar_exists(): - """Test that sidebar is rendered.""" - at = AppTest.from_file("app.py") - at.run() - - # Check sidebar exists - assert len(at.sidebar) > 0, "Sidebar should exist" - - print("✓ Sidebar exists") - - -def test_basic_calculation(): - """Test basic calculation flow.""" - at = AppTest.from_file("app.py") - at.run() - - # Set values in sidebar - at.sidebar.selectbox[0].select("Single") # Filing status - at.sidebar.number_input[0].set_value(35) # Age - at.sidebar.number_input[1].set_value(0) # Number of dependents - at.sidebar.number_input[2].set_value(50000) # Income - at.sidebar.selectbox[1].select("TX") # State - - # Click calculate button - at.sidebar.button[0].click() - at.run() - - # Check that results are displayed - assert not at.exception, f"Calculation raised exception: {at.exception}" - - print("✓ Basic calculation works") - - -if __name__ == "__main__": - test_app_runs() - test_sidebar_exists() - test_basic_calculation() - print("\n✅ All Streamlit tests passed!") diff --git a/tests/test_texas.py b/tests/test_texas.py deleted file mode 100644 index ee57501..0000000 --- a/tests/test_texas.py +++ /dev/null @@ -1,69 +0,0 @@ -from policyengine_us import Simulation -from policyengine_core.reforms import Reform - -# Texas couple example from notebook - at 300% FPL ($63,450) -income = 63450 -year = 2026 - -# Baseline household -household = { - 'people': { - 'you': {'age': {year: 25}, 'employment_income': {year: income/2}}, - 'your partner': {'age': {year: 28}, 'employment_income': {year: income/2}} - }, - 'families': {'your family': {'members': ['you', 'your partner']}}, - 'tax_units': {'your tax unit': {'members': ['you', 'your partner']}}, - 'households': { - 'your household': { - 'members': ['you', 'your partner'], - 'state_name': {year: 'TX'} - } - }, - 'marital_units': {'your marital unit': {'members': ['you', 'your partner']}} -} - -# Create reform (IRA expires) - NOTE the key difference! -# The notebook has ptc_income_eligibility[2] = True which KEEPS eligibility above 400% -# We had it as False which REMOVES eligibility above 400% -reform = Reform.from_dict({ - 'gov.aca.ptc_phase_out_rate[0].amount': {'2026-01-01.2100-12-31': 0}, - 'gov.aca.ptc_phase_out_rate[1].amount': {'2026-01-01.2100-12-31': 0}, - 'gov.aca.ptc_phase_out_rate[2].amount': {'2026-01-01.2100-12-31': 0}, - 'gov.aca.ptc_phase_out_rate[3].amount': {'2026-01-01.2100-12-31': 0.02}, - 'gov.aca.ptc_phase_out_rate[4].amount': {'2026-01-01.2100-12-31': 0.04}, - 'gov.aca.ptc_phase_out_rate[5].amount': {'2026-01-01.2100-12-31': 0.06}, - 'gov.aca.ptc_phase_out_rate[6].amount': {'2026-01-01.2100-12-31': 0.085}, - 'gov.aca.ptc_income_eligibility[2].amount': {'2026-01-01.2100-12-31': True} # THIS IS THE KEY! -}, country_id='us') - -# Run simulations -sim_baseline = Simulation(situation=household) -sim_reform = Simulation(situation=household, reform=reform) - -ptc_baseline = sim_baseline.calculate('aca_ptc', map_to='household', period=year)[0] -ptc_reform = sim_reform.calculate('aca_ptc', map_to='household', period=year)[0] - -print(f'Texas couple at 300% FPL ($63,450):') -print(f' PTC with IRA (baseline): ${ptc_baseline:,.2f}') -print(f' PTC without IRA (reform): ${ptc_reform:,.2f}') -print(f' Difference: ${ptc_baseline - ptc_reform:,.2f}') -print(f'\nNotebook expected: baseline=$4,062, reform=$6,283') -print(f'Match baseline: {abs(ptc_baseline - 4062) < 10}') -print(f'Match reform: {abs(ptc_reform - 6283) < 10}') - -# Also test at 400% FPL -income_400 = 84600 -household_400 = household.copy() -household_400['people']['you']['employment_income'] = {year: income_400/2} -household_400['people']['your partner']['employment_income'] = {year: income_400/2} - -sim_400_baseline = Simulation(situation=household_400) -sim_400_reform = Simulation(situation=household_400, reform=reform) - -ptc_400_baseline = sim_400_baseline.calculate('aca_ptc', map_to='household', period=year)[0] -ptc_400_reform = sim_400_reform.calculate('aca_ptc', map_to='household', period=year)[0] - -print(f'\nTexas couple at 400% FPL ($84,600):') -print(f' PTC with IRA (baseline): ${ptc_400_baseline:,.2f}') -print(f' PTC without IRA (reform): ${ptc_400_reform:,.2f}') -print(f' Notebook expected: baseline=$0, reform=$2,899') \ No newline at end of file diff --git a/tests/test_unique_chart_keys.py b/tests/test_unique_chart_keys.py deleted file mode 100644 index f6895aa..0000000 --- a/tests/test_unique_chart_keys.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Test that all plotly_chart elements have unique keys.""" - -import re - - -def test_all_plotly_charts_have_unique_keys(): - """Verify all st.plotly_chart calls have unique key parameters.""" - with open("app.py", "r") as f: - content = f.read() - - # Find all st.plotly_chart calls - # Pattern matches: st.plotly_chart(...) including multiline - pattern = r'st\.plotly_chart\([^)]+(?:\n[^)]+)*\)' - matches = re.findall(pattern, content) - - print(f"\nFound {len(matches)} st.plotly_chart calls") - - keys = [] - missing_keys = [] - - for i, match in enumerate(matches): - # Look for key= parameter - key_match = re.search(r'key\s*=\s*["\']([^"\']+)["\']', match) - if key_match: - key = key_match.group(1) - keys.append(key) - print(f" Chart {i+1}: key='{key}'") - else: - missing_keys.append(i+1) - print(f" Chart {i+1}: ⚠️ NO KEY") - - # Assert all charts have keys - assert len(missing_keys) == 0, f"Charts missing keys: {missing_keys}" - - # Assert all keys are unique - duplicate_keys = [k for k in keys if keys.count(k) > 1] - assert len(duplicate_keys) == 0, f"Duplicate keys found: {set(duplicate_keys)}" - - print(f"\n✓ All {len(matches)} charts have unique keys") - - -if __name__ == "__main__": - test_all_plotly_charts_have_unique_keys()