""" CRE Default Cascade Simulation Interactive visualization of how CRE defaults affect U.S. bank capitalization. Run locally: pip install dash plotly pandas python app.py Open http://localhost:8050 Deploy to Hugging Face Spaces: Uses Docker SDK — see Dockerfile and README.md """ import io import os import pandas as pd import dash from dash import dcc, html, Input, Output, State, callback, clientside_callback import plotly.graph_objects as go # ── App init ────────────────────────────────────────────────────────────────── app = dash.Dash(__name__, title="Default Cascade Simulation of Banks 2026 — Signalpha") server = app.server # ── Load data ───────────────────────────────────────────────────────────────── DATA_PATH = os.path.join(os.path.dirname(__file__), "data.csv") df = pd.read_csv(DATA_PATH) # Clean numeric columns for col in ["Total Assets ($M)", "Total Equity ($M)", "CRE Total ($M)", "CET1 Capital ($M)", "Total Unrealized Loss ($M)"]: df[col] = pd.to_numeric(df[col].astype(str).str.replace(",", ""), errors="coerce") df["Total Unrealized Loss ($M)"] = df["Total Unrealized Loss ($M)"].fillna(0) df["_has_ticker"] = df["Ticker"].notna() & (df["Ticker"].astype(str).str.strip() != "") N_BANKS = len(df) # ── Colour palette (light theme) ───────────────────────────────────────────── CLR_BG = "#F3F4F6" CLR_CARD_BG = "#FFFFFF" CLR_TEXT = "#111827" CLR_MUTED = "#6B7280" CLR_BORDER = "rgba(0,0,0,0.10)" CLR_LINK = "#2563EB" # Red shades for PCA (Viz 1) — lightest to darkest RED_WELL_CAP = "#FDCECE" RED_ADEQ_CAP = "#F87171" RED_UNDERCAP = "#DC2626" RED_CRIT_UNDCAP = "#991B1B" RED_INSOLVENT = "#450A0A" # Bar dimensions (explicit width keeps thickness stable across renders) BAR_WIDTH = 1.0 # fraction of y-axis category width BAR_HEIGHT = 48 # px — total chart height # Purple shades for CET1 (Viz 2) — lightest to darkest PUR_WELL_CAP = "#E9D5FF" PUR_UNDERCAP = "#A855F7" PUR_BELOW_MIN = "#7E22CE" PUR_INSOLVENT = "#3B0764" # ── Helpers ─────────────────────────────────────────────────────────────────── def classify_pca(equity_to_assets): """Classify banks by Prompt Corrective Action category based on equity-to-assets ratio.""" well = adequately = under = critical = insolvent = 0 for ratio in equity_to_assets: if ratio >= 0.08: well += 1 elif ratio >= 0.04: adequately += 1 elif ratio >= 0.02: under += 1 elif ratio >= 0: critical += 1 else: insolvent += 1 return well, adequately, under, critical, insolvent def classify_cet1(cet1_ratios): """Classify banks by Basel III CET1 thresholds.""" well = under = below = insolvent = 0 for ratio in cet1_ratios: if ratio >= 0.065: well += 1 elif ratio >= 0.045: under += 1 elif ratio >= 0: below += 1 else: insolvent += 1 return well, under, below, insolvent def compute_scenario(default_rate, lgd, rwa_ratio, include_unrealized=False, data=None): """Compute adjusted ratios for all banks given scenario parameters.""" d = data if data is not None else df cre = d["CRE Total ($M)"].values equity = d["Total Equity ($M)"].values assets = d["Total Assets ($M)"].values cet1 = d["CET1 Capital ($M)"].values unrealized = d["Total Unrealized Loss ($M)"].values if include_unrealized else 0 cre_losses = cre * default_rate * lgd adj_equity_to_assets = (equity - cre_losses - unrealized) / assets estimated_rwa = assets * rwa_ratio adj_cet1_ratio = (cet1 - cre_losses - unrealized) / estimated_rwa total_cre_losses = cre_losses.sum() # PCA-based metrics (use adjusted ratios so masks match classify_pca) insolvent_mask_pca = adj_equity_to_assets < 0 insolvent_assets_pca = assets[insolvent_mask_pca].sum() undercap_mask_pca = adj_equity_to_assets < 0.04 undercap_assets_pca = assets[undercap_mask_pca].sum() # CET1-based metrics (use adjusted ratios so masks match classify_cet1) # Insolvent: ratio < 0 insolvent_mask_cet1 = adj_cet1_ratio < 0 insolvent_assets_cet1 = assets[insolvent_mask_cet1].sum() # Below Basel III Minimum: ratio < 4.5% (matches c_below + c_insolvent) undercap_mask_cet1 = adj_cet1_ratio < 0.045 undercap_assets_cet1 = assets[undercap_mask_cet1].sum() return (adj_equity_to_assets, adj_cet1_ratio, total_cre_losses, insolvent_assets_pca, undercap_assets_pca, insolvent_assets_cet1, undercap_assets_cet1) # ── Slider factory ──────────────────────────────────────────────────────────── def make_slider(slider_id, label, min_, max_, step, value, suffix="%"): return html.Div([ html.Div([ html.Label(label, style={ "fontSize": "13px", "color": CLR_MUTED, "minWidth": "155px", "marginRight": "12px", "fontWeight": "500", }), dcc.Slider( id=slider_id, min=min_, max=max_, step=step, value=value, marks=None, tooltip={"always_visible": False}, className="cre-slider", ), html.Span(id=f"{slider_id}-out", style={ "fontSize": "14px", "fontWeight": "600", "minWidth": "70px", "textAlign": "right", "color": CLR_TEXT, }), ], style={"display": "flex", "alignItems": "center", "gap": "12px"}), ], style={"marginBottom": "14px"}) # ── Metric card ─────────────────────────────────────────────────────────────── def metric_card(card_id, label, sub_id=None): children = [ html.Div(label, style={"fontSize": "11px", "color": CLR_MUTED, "marginBottom": "4px", "textTransform": "uppercase", "letterSpacing": "0.5px"}), html.Div(id=card_id, style={"fontSize": "20px", "fontWeight": "600", "color": CLR_TEXT}), ] if sub_id: children.append(html.Div(id=sub_id, style={"fontSize": "11px", "color": CLR_MUTED, "marginTop": "2px"})) return html.Div(children, style={ "background": CLR_CARD_BG, "borderRadius": "8px", "padding": "14px 16px", "flex": "1", "minWidth": "140px", "border": f"1px solid {CLR_BORDER}", }) def fmt_assets(value): """Format asset values in $B or $T.""" if value > 1e6: return f"${value / 1e6:.2f}T in assets" return f"${value / 1000:.1f}B in assets" # ── Layout ──────────────────────────────────────────────────────────────────── app.layout = html.Div([ # Capturable content area with clear boundary html.Div([ # Header + Banner html.Div([ html.Div([ html.H1("Default Cascade Simulation of Banks 2026", style={ "fontSize": "24px", "fontWeight": "600", "margin": "0 0 6px", "color": CLR_TEXT, }), html.P( f"Impact of CRE defaults and unrealized losses on {N_BANKS} U.S. largest banks (more than $10 billion in assets)", style={"fontSize": "14px", "color": CLR_MUTED, "margin": "0 0 4px"}, ), html.P([ "Source: ", html.A("Signalpha", href="https://signalpha.substack.com/", target="_blank", style={"color": CLR_LINK, "textDecoration": "none"}), ], style={"fontSize": "12px", "margin": "0 0 2px", "color": CLR_MUTED}), html.P([ "Data: ", html.A("The Banking Initiative at Florida Atlantic University", href="https://business.fau.edu/departments/finance/banking-initiative/", target="_blank", style={"color": CLR_LINK, "textDecoration": "none"}), ], style={"fontSize": "12px", "margin": 0, "color": CLR_MUTED}), ], style={"flex": "1"}), html.Img(src="/assets/signalpha-banner.png", style={ "height": "80px", "borderRadius": "6px", "alignSelf": "center", }), ], style={"display": "flex", "alignItems": "flex-start", "gap": "20px", "marginBottom": "28px"}), # Controls html.Div([ html.Div("Scenario Parameters", style={ "fontSize": "13px", "fontWeight": "600", "color": CLR_TEXT, "marginBottom": "14px", "textTransform": "uppercase", "letterSpacing": "0.5px", }), make_slider("default-rate", "CRE Default Rate", 0, 50, 0.5, 10, "%"), make_slider("lgd", "Loss Given Default", 0, 100, 1, 50, "%"), make_slider("rwa-ratio", "Average RWA Ratio", 50, 75, 0.5, 65, "%"), make_slider("min-assets", "Total Assets", 10, 100, 1, 10, "$B"), # Unrealized losses toggle html.Div([ html.Label("Unrealized Losses", style={ "fontSize": "13px", "color": CLR_MUTED, "minWidth": "155px", "marginRight": "12px", "fontWeight": "500", }), dcc.Checklist( id="unrealized-toggle", options=[{"label": " Include Total Unrealized Losses on Investment Securities", "value": "on"}], value=[], style={"fontSize": "13px", "color": CLR_TEXT}, inputStyle={"marginRight": "6px"}, ), ], style={"display": "flex", "alignItems": "center", "gap": "12px", "marginTop": "4px"}), # Has CRE Losses toggle html.Div([ html.Label("Has CRE Losses", style={ "fontSize": "13px", "color": CLR_MUTED, "minWidth": "155px", "marginRight": "12px", "fontWeight": "500", }), dcc.Checklist( id="cre-losses-toggle", options=[{"label": " Exclude Banks Without CRE Losses", "value": "on"}], value=[], style={"fontSize": "13px", "color": CLR_TEXT}, inputStyle={"marginRight": "6px"}, ), ], style={"display": "flex", "alignItems": "center", "gap": "12px", "marginTop": "8px"}), # Publicly traded only toggle html.Div([ html.Label("Publicly Traded Only", style={ "fontSize": "13px", "color": CLR_MUTED, "minWidth": "155px", "marginRight": "12px", "fontWeight": "500", }), dcc.Checklist( id="public-toggle", options=[{"label": " Exclude Non-Publicly Traded Banks", "value": "on"}], value=[], style={"fontSize": "13px", "color": CLR_TEXT}, inputStyle={"marginRight": "6px"}, ), ], style={"display": "flex", "alignItems": "center", "gap": "12px", "marginTop": "8px"}), ], style={ "background": CLR_CARD_BG, "borderRadius": "10px", "padding": "20px 24px", "marginBottom": "20px", "border": f"1px solid {CLR_BORDER}", }), # ── Visualization 1: Tangible Equity Ratio ──────────────────────── html.Div([ html.Div([ html.Span("Tangible Equity Ratio", style={ "fontSize": "15px", "fontWeight": "600", "color": CLR_TEXT, }), html.Span(" — Prompt Corrective Action Categories", style={ "fontSize": "13px", "color": CLR_MUTED, }), ], style={"marginBottom": "4px"}), html.P(id="formula-pca", style={ "fontSize": "11px", "color": CLR_MUTED, "margin": "0 0 8px", "fontFamily": "monospace", }), # Legend html.Div([ html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": RED_WELL_CAP, "display": "inline-block", "marginRight": "4px"}), "Well Capitalized (\u22658%)"], style={"fontSize": "11px", "color": CLR_MUTED, "marginRight": "12px"}), html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": RED_ADEQ_CAP, "display": "inline-block", "marginRight": "4px"}), "Adequately Capitalized (\u22654%)"], style={"fontSize": "11px", "color": CLR_MUTED, "marginRight": "12px"}), html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": RED_UNDERCAP, "display": "inline-block", "marginRight": "4px"}), "Undercapitalized (\u22652%)"], style={"fontSize": "11px", "color": CLR_MUTED, "marginRight": "12px"}), html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": RED_CRIT_UNDCAP, "display": "inline-block", "marginRight": "4px"}), "Critically Undercapitalized (<2%)"], style={"fontSize": "11px", "color": CLR_MUTED, "marginRight": "12px"}), html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": RED_INSOLVENT, "display": "inline-block", "marginRight": "4px"}), "Insolvent (<0%)"], style={"fontSize": "11px", "color": CLR_MUTED}), ], style={"marginBottom": "8px", "display": "flex", "flexWrap": "wrap", "gap": "4px"}), dcc.Graph(id="chart-pca", config={"displayModeBar": False}, style={"height": "48px"}), # PCA metric cards html.Div([ metric_card("pca-total-losses", "Total Losses"), metric_card("pca-banks-undercap", "Banks Undercapitalized", sub_id="pca-undercap-assets"), metric_card("pca-banks-insolvent", "Banks Insolvent", sub_id="pca-insolvent-assets"), ], style={ "display": "flex", "gap": "10px", "flexWrap": "wrap", "marginTop": "12px", }), ], style={ "background": CLR_CARD_BG, "borderRadius": "10px", "padding": "18px 24px", "marginBottom": "16px", "border": f"1px solid {CLR_BORDER}", }), # ── Visualization 2: Estimated CET1 Ratio ──────────────────────── html.Div([ html.Div([ html.Span("Estimated CET1 Ratio", style={ "fontSize": "15px", "fontWeight": "600", "color": CLR_TEXT, }), html.Span(" — Basel III Capital Thresholds", style={ "fontSize": "13px", "color": CLR_MUTED, }), ], style={"marginBottom": "4px"}), html.P(id="formula-cet1", style={ "fontSize": "11px", "color": CLR_MUTED, "margin": "0 0 8px", "fontFamily": "monospace", }), # Legend html.Div([ html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": PUR_WELL_CAP, "display": "inline-block", "marginRight": "4px"}), "Well Capitalized (\u22656.5%)"], style={"fontSize": "11px", "color": CLR_MUTED, "marginRight": "12px"}), html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": PUR_UNDERCAP, "display": "inline-block", "marginRight": "4px"}), "Undercapitalized (\u22654.5%)"], style={"fontSize": "11px", "color": CLR_MUTED, "marginRight": "12px"}), html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": PUR_BELOW_MIN, "display": "inline-block", "marginRight": "4px"}), "Below Basel III Minimum (<4.5%)"], style={"fontSize": "11px", "color": CLR_MUTED, "marginRight": "12px"}), html.Span([html.Span(style={"width": "10px", "height": "10px", "borderRadius": "2px", "background": PUR_INSOLVENT, "display": "inline-block", "marginRight": "4px"}), "Insolvent (<0%)"], style={"fontSize": "11px", "color": CLR_MUTED}), ], style={"marginBottom": "8px", "display": "flex", "flexWrap": "wrap", "gap": "4px"}), dcc.Graph(id="chart-cet1", config={"displayModeBar": False}, style={"height": "48px"}), # CET1 metric cards html.Div([ metric_card("cet1-total-losses", "Total Losses"), metric_card("cet1-banks-undercap", "Banks Below Minimum", sub_id="cet1-undercap-assets"), metric_card("cet1-banks-insolvent", "Banks Insolvent", sub_id="cet1-insolvent-assets"), ], style={ "display": "flex", "gap": "10px", "flexWrap": "wrap", "marginTop": "12px", }), ], style={ "background": CLR_CARD_BG, "borderRadius": "10px", "padding": "18px 24px", "marginBottom": "16px", "border": f"1px solid {CLR_BORDER}", }), ], id="capture-area", style={ "maxWidth": "860px", "margin": "0 auto", "padding": "40px 28px", "background": "#FFFFFF", "border": f"1px solid {CLR_BORDER}", "borderRadius": "12px", }), # Download buttons (outside capture area) html.Div([ html.Button( "Download Figure", id="btn-download", style={ "fontSize": "13px", "fontWeight": "500", "padding": "10px 24px", "borderRadius": "8px", "border": f"1px solid {CLR_BORDER}", "background": CLR_CARD_BG, "color": CLR_TEXT, "cursor": "pointer", "marginRight": "10px", }, ), html.Button( "Download Data (CSV)", id="btn-download-csv", style={ "fontSize": "13px", "fontWeight": "500", "padding": "10px 24px", "borderRadius": "8px", "border": f"1px solid {CLR_BORDER}", "background": CLR_CARD_BG, "color": CLR_TEXT, "cursor": "pointer", "marginRight": "10px", }, ), html.A( html.Button( "Signalpha on Substack", style={ "fontSize": "13px", "fontWeight": "500", "padding": "10px 24px", "borderRadius": "8px", "border": "none", "background": "#7C3AED", "color": "#FFFFFF", "cursor": "pointer", }, ), href="https://signalpha.substack.com/", target="_blank", style={"textDecoration": "none"}, ), ], style={"maxWidth": "860px", "margin": "0 auto", "textAlign": "center", "padding": "16px 28px 0"}), # Disclaimer html.Div([ html.P( "Disclaimer: The information provided in this application is for educational and informational purposes only and does not constitute financial, investment, legal, or tax advice. While every effort is made to ensure the accuracy of the data and analysis presented, all content is provided \"as is\" and without warranty of any kind. Investing in financial markets involves significant risk, including the potential loss of principal. The author is not a registered investment advisor or broker-dealer, and the views expressed are personal opinions that may change without notice. You should consult with a qualified professional before making any financial decisions, and you agree that the author shall not be held liable for any losses or damages resulting from the use of this information.", style={"fontSize": "11px", "lineHeight": "1.6", "color": CLR_MUTED, "margin": "0"}, ), ], style={ "maxWidth": "860px", "margin": "20px auto 0", "padding": "16px 28px", "background": CLR_CARD_BG, "borderRadius": "10px", "border": f"1px solid {CLR_BORDER}", }), # Hidden download components dcc.Download(id="download-csv"), # Documentation html.Div([ html.Details([ html.Summary("Documentation", style={ "fontSize": "15px", "fontWeight": "600", "color": CLR_TEXT, "cursor": "pointer", "padding": "12px 0", }), dcc.Markdown( open(os.path.join(os.path.dirname(__file__), "documentation.md")).read(), style={"fontSize": "13px", "lineHeight": "1.7", "color": CLR_TEXT}, ), ], open=False), ], style={ "maxWidth": "860px", "margin": "24px auto 0", "background": CLR_CARD_BG, "borderRadius": "10px", "padding": "8px 28px 20px", "border": f"1px solid {CLR_BORDER}", }), ], style={ "padding": "40px 20px", "fontFamily": "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Inter', sans-serif", "background": CLR_BG, "minHeight": "100vh", "color": CLR_TEXT, }) # ── Client-side callback for image download via html2canvas ─────────────────── app.index_string = ''' {%metas%} {%title%} {%favicon%} {%css%} {%app_entry%} ''' clientside_callback( """ function(n_clicks) { if (!n_clicks) return window.dash_clientside.no_update; var el = document.getElementById('capture-area'); if (!el) return window.dash_clientside.no_update; html2canvas(el, { backgroundColor: '#FFFFFF', scale: 2, useCORS: true, logging: false, }).then(function(canvas) { var link = document.createElement('a'); link.download = 'default-cascade-simulation.png'; link.href = canvas.toDataURL('image/png'); link.click(); }); return window.dash_clientside.no_update; } """, Output("btn-download", "n_clicks"), Input("btn-download", "n_clicks"), prevent_initial_call=True, ) # ── Callbacks ───────────────────────────────────────────────────────────────── @callback( Output("default-rate-out", "children"), Output("lgd-out", "children"), Output("rwa-ratio-out", "children"), Output("min-assets-out", "children"), # Formulas Output("formula-pca", "children"), Output("formula-cet1", "children"), # PCA metrics Output("pca-total-losses", "children"), Output("pca-banks-undercap", "children"), Output("pca-undercap-assets", "children"), Output("pca-banks-insolvent", "children"), Output("pca-insolvent-assets", "children"), # CET1 metrics Output("cet1-total-losses", "children"), Output("cet1-banks-undercap", "children"), Output("cet1-undercap-assets", "children"), Output("cet1-banks-insolvent", "children"), Output("cet1-insolvent-assets", "children"), # Charts Output("chart-pca", "figure"), Output("chart-cet1", "figure"), Input("default-rate", "value"), Input("lgd", "value"), Input("rwa-ratio", "value"), Input("min-assets", "value"), Input("unrealized-toggle", "value"), Input("cre-losses-toggle", "value"), Input("public-toggle", "value"), ) def update(default_rate, lgd, rwa_ratio, min_assets, unrealized_toggle, cre_losses_toggle, public_toggle): default_rate = (default_rate or 10) / 100 lgd = (lgd or 50) / 100 rwa_ratio = (rwa_ratio or 65) / 100 min_assets_b = min_assets or 10 # in $B include_unrealized = "on" in (unrealized_toggle or []) has_cre_only = "on" in (cre_losses_toggle or []) public_only = "on" in (public_toggle or []) # Filter data data = df.copy() data = data[data["Total Assets ($M)"] >= min_assets_b * 1000] if public_only: data = data[data["_has_ticker"]] if has_cre_only: data = data[data["CRE Total ($M)"] > 0] n_banks = len(data) (adj_eq, adj_cet1, total_losses, insolv_assets_pca, undercap_assets_pca, insolv_assets_cet1, undercap_assets_cet1) = compute_scenario( default_rate, lgd, rwa_ratio, include_unrealized, data=data ) # Total losses displayed in metric cards (CRE losses + unrealized if toggled) if include_unrealized: display_total_losses = total_losses + data["Total Unrealized Loss ($M)"].values.sum() else: display_total_losses = total_losses # Dynamic formula labels if include_unrealized: formula_pca = "Adjusted Equity-to-Assets = (Total Equity \u2212 CRE Losses \u2212 Unrealized Losses) / Total Assets" formula_cet1 = "Adjusted CET1 = (CET1 Capital \u2212 CRE Losses \u2212 Unrealized Losses) / (Total Assets \u00d7 RWA Ratio)" else: formula_pca = "Adjusted Equity-to-Assets = (Total Equity \u2212 CRE Losses) / Total Assets" formula_cet1 = "Adjusted CET1 = (CET1 Capital \u2212 CRE Losses) / (Total Assets \u00d7 RWA Ratio)" # PCA classification well, adequately, under, critical, insolvent = classify_pca(adj_eq) # CET1 classification c_well, c_under, c_below, c_insolvent = classify_cet1(adj_cet1) # PCA counts n_undercap_pca = under + critical + insolvent n_insolvent_pca = insolvent # CET1 counts n_undercap_cet1 = c_below + c_insolvent n_insolvent_cet1 = c_insolvent # ── PCA bar chart ───────────────────────────────────────────────────── fig_pca = go.Figure() pca_data = [ ("Well Capitalized", well, RED_WELL_CAP, "#1A1A1A"), ("Adequately Capitalized", adequately, RED_ADEQ_CAP, "#1A1A1A"), ("Undercapitalized", under, RED_UNDERCAP, "#FFFFFF"), ("Critically Undercapitalized", critical, RED_CRIT_UNDCAP, "#FFFFFF"), ("Insolvent", insolvent, RED_INSOLVENT, "#FFFFFF"), ] for name, count, color, text_color in pca_data: fig_pca.add_trace(go.Bar( name=name, y=["Banks"], x=[count], width=[BAR_WIDTH], orientation="h", marker_color=color, text=[str(count) if count > 0 else ""], textposition="inside", textfont={"size": 13, "color": text_color, "family": "Inter, sans-serif"}, insidetextanchor="middle", hovertemplate=f"{name}: %{{x}} banks", showlegend=False, )) fig_pca.update_layout( barmode="stack", paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", margin={"l": 0, "r": 0, "t": 0, "b": 0}, xaxis={"visible": False, "range": [0, n_banks]}, yaxis={"visible": False, "range": [-0.5, 0.5]}, height=BAR_HEIGHT, hoverlabel={"bgcolor": "#FFFFFF", "bordercolor": CLR_BORDER, "font": {"color": CLR_TEXT}}, ) # ── CET1 bar chart ──────────────────────────────────────────────────── fig_cet1 = go.Figure() cet1_data = [ ("Well Capitalized", c_well, PUR_WELL_CAP, "#1A1A1A"), ("Undercapitalized", c_under, PUR_UNDERCAP, "#FFFFFF"), ("Below Basel III Minimum", c_below, PUR_BELOW_MIN, "#FFFFFF"), ("Insolvent", c_insolvent, PUR_INSOLVENT, "#FFFFFF"), ] for name, count, color, text_color in cet1_data: fig_cet1.add_trace(go.Bar( name=name, y=["Banks"], x=[count], width=[BAR_WIDTH], orientation="h", marker_color=color, text=[str(count) if count > 0 else ""], textposition="inside", textfont={"size": 13, "color": text_color, "family": "Inter, sans-serif"}, insidetextanchor="middle", hovertemplate=f"{name}: %{{x}} banks", showlegend=False, )) fig_cet1.update_layout( barmode="stack", paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", margin={"l": 0, "r": 0, "t": 0, "b": 0}, xaxis={"visible": False, "range": [0, n_banks]}, yaxis={"visible": False, "range": [-0.5, 0.5]}, height=BAR_HEIGHT, hoverlabel={"bgcolor": "#FFFFFF", "bordercolor": CLR_BORDER, "font": {"color": CLR_TEXT}}, ) return ( f"{default_rate * 100:.1f}%", f"{lgd * 100:.1f}%", f"{rwa_ratio * 100:.1f}%", f"${min_assets_b:.0f}B", # Formulas formula_pca, formula_cet1, # PCA metrics f"${display_total_losses / 1000:.1f}B", str(n_undercap_pca), fmt_assets(undercap_assets_pca), str(n_insolvent_pca), fmt_assets(insolv_assets_pca), # CET1 metrics f"${display_total_losses / 1000:.1f}B", str(n_undercap_cet1), fmt_assets(undercap_assets_cet1), str(n_insolvent_cet1), fmt_assets(insolv_assets_cet1), # Charts fig_pca, fig_cet1, ) # ── CSV download callback ───────────────────────────────────────────────────── def classify_pca_label(ratio): if ratio >= 0.08: return "Well Capitalized" elif ratio >= 0.04: return "Adequately Capitalized" elif ratio >= 0.02: return "Undercapitalized" elif ratio >= 0: return "Critically Undercapitalized" return "Insolvent" def classify_cet1_label(ratio): if ratio >= 0.065: return "Well Capitalized" elif ratio >= 0.045: return "Undercapitalized" elif ratio >= 0: return "Below Basel III Minimum" return "Insolvent" @callback( Output("download-csv", "data"), Input("btn-download-csv", "n_clicks"), State("default-rate", "value"), State("lgd", "value"), State("rwa-ratio", "value"), State("min-assets", "value"), State("unrealized-toggle", "value"), State("cre-losses-toggle", "value"), State("public-toggle", "value"), prevent_initial_call=True, ) def download_csv(n_clicks, default_rate, lgd_val, rwa_ratio, min_assets, unrealized_toggle, cre_losses_toggle, public_toggle): if not n_clicks: return dash.no_update dr = (default_rate or 10) / 100 lgd_v = (lgd_val or 50) / 100 rwa_r = (rwa_ratio or 65) / 100 min_assets_b = min_assets or 10 include_unrealized = "on" in (unrealized_toggle or []) has_cre_only = "on" in (cre_losses_toggle or []) public_only = "on" in (public_toggle or []) data = df.copy() data = data[data["Total Assets ($M)"] >= min_assets_b * 1000] if public_only: data = data[data["_has_ticker"]] if has_cre_only: data = data[data["CRE Total ($M)"] > 0] cre = data["CRE Total ($M)"].values equity = data["Total Equity ($M)"].values assets = data["Total Assets ($M)"].values cet1 = data["CET1 Capital ($M)"].values unrealized = data["Total Unrealized Loss ($M)"].values if include_unrealized else 0 cre_losses = cre * dr * lgd_v adj_eq = (equity - cre_losses - unrealized) / assets estimated_rwa = assets * rwa_r adj_cet1 = (cet1 - cre_losses - unrealized) / estimated_rwa out = pd.DataFrame({ "Bank Name": data["Name"].values, "State": data["ST"].values, "Total Assets ($M)": assets, "Total Equity ($M)": equity, "CRE Total ($M)": cre, "CET1 Capital ($M)": cet1, "Total Unrealized Loss ($M)": data["Total Unrealized Loss ($M)"].values, "CRE Losses ($M)": cre_losses.round(1), "Adjusted Equity-to-Assets (%)": (adj_eq * 100).round(2), "PCA Classification": [classify_pca_label(r) for r in adj_eq], "Adjusted CET1 Ratio (%)": (adj_cet1 * 100).round(2), "CET1 Classification": [classify_cet1_label(r) for r in adj_cet1], }) buf = io.StringIO() out.to_csv(buf, index=False) unr_tag = "_UL" if include_unrealized else "" pub_tag = "_PUB" if public_only else "" filename = f"cre-simulation_DR{default_rate:.0f}_LGD{lgd_val:.0f}_RWA{rwa_ratio:.0f}{unr_tag}{pub_tag}.csv" return dcc.send_string(buf.getvalue(), filename=filename) # ── Entry point ─────────────────────────────────────────────────────────────── if __name__ == "__main__": app.run(debug=False, host="0.0.0.0", port=8050)