File size: 35,058 Bytes
0afdb9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
"""
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 = '''
<!DOCTYPE html>
<html>
    <head>
        {%metas%}
        <title>{%title%}</title>
        {%favicon%}
        {%css%}
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    </head>
    <body>
        {%app_entry%}
        <footer>
            {%config%}
            {%scripts%}
            {%renderer%}
        </footer>
    </body>
</html>
'''

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<extra></extra>",
            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<extra></extra>",
            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)