-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1392 lines (1182 loc) · 64.8 KB
/
Copy pathapp.py
File metadata and controls
1392 lines (1182 loc) · 64.8 KB
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DataQuest 2026 — Interactive Credit Risk EDA Platform
======================================================
Run with: streamlit run app.py
Tabs:
1. 🏠 Home & Data Quality
2. 📊 Univariate Explorer (distribution + WoE/IV)
3. 🔗 Bivariate Explorer (scatter + heatmaps)
4. 🧠 Research Reference (theory + metrics)
5. 🤖 Model Performance (plug in Task 2 results)
6. 💼 Business Dashboard (Bonus Task 3)
"""
import sys
import os
# Make utils importable regardless of working directory
sys.path.insert(0, os.path.dirname(__file__))
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.patches as mpatches
import seaborn as sns
from io import BytesIO
import warnings
warnings.filterwarnings("ignore")
from utils.data_cleaning import clean_loan_book, data_quality_report
from utils.woe_iv import compute_woe_iv, iv_all_features, compute_iv
# ══════════════════════════════════════════════════════════════════════════════
# CONFIG & STYLING
# ══════════════════════════════════════════════════════════════════════════════
st.set_page_config(
page_title="DataQuest 2026 | Credit Risk Intelligence Platform",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded"
)
# Colour palette — dark navy + electric teal accent
PALETTE = {
"bg": "#0D1117",
"card": "#161B22",
"border": "#30363D",
"accent": "#00D4AA", # teal
"accent2": "#F78166", # coral / bad risk
"accent3": "#79C0FF", # sky blue / good
"text": "#E6EDF3",
"muted": "#8B949E",
"good": "#3FB950",
"bad": "#F85149",
}
st.markdown(f"""
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;600;700&display=swap');
html, body, [class*="css"] {{
font-family: 'IBM Plex Sans', sans-serif;
background-color: {PALETTE['bg']};
color: {PALETTE['text']};
}}
.stApp {{ background-color: {PALETTE['bg']}; }}
/* Sidebar */
[data-testid="stSidebar"] {{
background-color: {PALETTE['card']};
border-right: 1px solid {PALETTE['border']};
}}
/* Metric cards */
[data-testid="metric-container"] {{
background: {PALETTE['card']};
border: 1px solid {PALETTE['border']};
border-radius: 8px;
padding: 16px;
}}
/* Dataframes */
[data-testid="stDataFrame"] {{ border-radius: 8px; }}
/* Tabs */
.stTabs [data-baseweb="tab-list"] {{
gap: 8px;
background-color: {PALETTE['card']};
border-radius: 8px;
padding: 4px;
}}
.stTabs [data-baseweb="tab"] {{
border-radius: 6px;
color: {PALETTE['muted']};
font-weight: 600;
font-family: 'IBM Plex Mono', monospace;
font-size: 13px;
}}
.stTabs [aria-selected="true"] {{
background-color: {PALETTE['accent']} !important;
color: {PALETTE['bg']} !important;
}}
/* Header banner */
.dq-header {{
background: linear-gradient(135deg, #0D1117 0%, #161B22 60%, #0f2027 100%);
border: 1px solid {PALETTE['border']};
border-left: 4px solid {PALETTE['accent']};
border-radius: 10px;
padding: 28px 36px;
margin-bottom: 24px;
}}
.dq-header h1 {{
font-size: 2rem;
font-weight: 700;
color: {PALETTE['accent']};
margin: 0 0 6px 0;
letter-spacing: -0.5px;
font-family: 'IBM Plex Mono', monospace;
}}
.dq-header p {{
color: {PALETTE['muted']};
margin: 0;
font-size: 0.95rem;
}}
/* Section headers */
.section-title {{
font-family: 'IBM Plex Mono', monospace;
font-size: 0.75rem;
font-weight: 600;
color: {PALETTE['accent']};
letter-spacing: 2px;
text-transform: uppercase;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid {PALETTE['border']};
}}
/* Insight cards */
.insight-card {{
background: {PALETTE['card']};
border: 1px solid {PALETTE['border']};
border-left: 3px solid {PALETTE['accent']};
border-radius: 8px;
padding: 16px 20px;
margin: 12px 0;
font-size: 0.9rem;
}}
.insight-card.warning {{
border-left-color: {PALETTE['accent2']};
}}
.insight-card.good {{
border-left-color: {PALETTE['good']};
}}
/* IV badge colours */
.iv-useless {{ color: {PALETTE['muted']}; }}
.iv-weak {{ color: #FFDF5D; }}
.iv-medium {{ color: {PALETTE['accent3']}; }}
.iv-strong {{ color: {PALETTE['accent']}; }}
.iv-suspicious{{ color: {PALETTE['bad']}; }}
/* Hide streamlit branding */
#MainMenu {{visibility:hidden;}}
footer {{visibility:hidden;}}
header {{visibility:hidden;}}
</style>
""", unsafe_allow_html=True)
# Matplotlib theme
plt.rcParams.update({
"figure.facecolor": PALETTE["bg"],
"axes.facecolor": PALETTE["card"],
"axes.edgecolor": PALETTE["border"],
"axes.labelcolor": PALETTE["muted"],
"axes.titlecolor": PALETTE["text"],
"xtick.color": PALETTE["muted"],
"ytick.color": PALETTE["muted"],
"text.color": PALETTE["text"],
"grid.color": PALETTE["border"],
"grid.alpha": 0.5,
"font.family": "monospace",
"figure.dpi": 120,
})
# ══════════════════════════════════════════════════════════════════════════════
# DATA LOADING — cached so the app stays fast
# ══════════════════════════════════════════════════════════════════════════════
@st.cache_data(show_spinner="Loading & cleaning data…")
def load_data(path: str = "data/loan_book.csv"):
raw = pd.read_csv(path)
clean = clean_loan_book(raw)
train = clean_loan_book(raw, split="train")
return raw, clean, train
@st.cache_data(show_spinner="Computing Information Values…")
def cached_iv_all(train_df_hash, features):
# We pass a hash to force cache invalidation if data changes
return iv_all_features(st.session_state["train"], features)
# ── Data path selection ───────────────────────────────────────────────────────
with st.sidebar:
st.markdown("## 📊 Credit Risk Intelligence")
st.caption("DataQuest 2026 Submission")
st.success("✅ Regulatory-Safe Logistic Regression Model")
st.markdown("---")
st.markdown(f"""
<div style="text-align:center; padding:12px 0 20px 0;">
<span style="font-family:'IBM Plex Mono';font-size:1.2rem;
font-weight:700;color:{PALETTE['accent']};">
📈 DataQuest 2026
</span><br>
<span style="color:{PALETTE['muted']};font-size:0.75rem;">
Credit Risk Intelligence Platform
</span>
</div>
""", unsafe_allow_html=True)
data_path = st.text_input("CSV path", value="data/loan_book.csv",
help="Relative or absolute path to loan_book.csv")
load_btn = st.button("⟳ Load / Reload Data", use_container_width=True)
if "data_loaded" not in st.session_state or load_btn:
try:
raw, clean, train = load_data(data_path)
st.session_state["raw"] = raw
st.session_state["clean"] = clean
st.session_state["train"] = train
st.session_state["data_loaded"] = True
st.session_state["load_error"] = None
except Exception as e:
st.session_state["load_error"] = str(e)
st.session_state["data_loaded"] = False
if not st.session_state.get("data_loaded"):
err = st.session_state.get("load_error", "Unknown error")
st.error(f"❌ Could not load data: {err}")
st.info("Please update the CSV path in the sidebar and click **Load / Reload Data**.")
st.stop()
raw = st.session_state["raw"]
clean = st.session_state["clean"]
train = st.session_state["train"]
# Feature lists
NUMERIC_FEATURES = [
"age", "annual_income", "employment_length_years", "num_open_accounts",
"total_revolving_balance", "credit_utilisation_pct",
"months_since_oldest_account", "num_hard_inquiries_6mo",
"loan_amount", "interest_rate", "dti_ratio",
"months_since_last_delinquency", "pct_accounts_current",
"months_at_current_address", "num_delinquencies_2yr",
]
CATEGORICAL_FEATURES = [
"home_ownership", "loan_purpose", "region",
"email_domain_type", "application_dow",
]
ALL_FEATURES = NUMERIC_FEATURES + CATEGORICAL_FEATURES
# ══════════════════════════════════════════════════════════════════════════════
# SIDEBAR — global controls
# ══════════════════════════════════════════════════════════════════════════════
with st.sidebar:
st.markdown("---")
st.markdown(f"<div class='section-title'>Dataset Info</div>", unsafe_allow_html=True)
st.metric("Total records", f"{len(raw):,}")
st.metric("Training set", f"{len(train):,}")
st.metric("Test set", f"{len(raw[raw['set']=='test']):,}")
st.metric("Default rate", f"{train['default_flag'].mean():.1%}")
st.markdown("---")
st.markdown(f"<div class='section-title'>Analysis Split</div>", unsafe_allow_html=True)
analysis_split = st.radio("Use data split:", ["Train only", "All data"],
index=0,
help="Best practice: do EDA on training data only to prevent leakage.")
df_analysis = train if analysis_split == "Train only" else clean
# ══════════════════════════════════════════════════════════════════════════════
# TABS
# ══════════════════════════════════════════════════════════════════════════════
# ══════════════════════════════════════════════════════════════════════════════
# EXECUTIVE KPI CARDS
# ══════════════════════════════════════════════════════════════════════════════
st.markdown("## 📌 Executive Model Summary")
kpi1, kpi2, kpi3, kpi4 = st.columns(4)
with kpi1:
st.metric(
label="Final Model AUC",
value="0.7822",
delta="+0.1022 vs baseline"
)
with kpi2:
st.metric(
label="Model Gini",
value="0.5644"
)
with kpi3:
st.metric(
label="Default Rate",
value=f"{train['default_flag'].mean():.1%}"
)
with kpi4:
st.metric(
label="Model Status",
value="5-fold cv"
)
st.markdown("---")
tabs = st.tabs([
"🏠 Home & Data Quality",
"📊 Univariate Explorer",
"🔗 Bivariate Explorer",
"🧠 Research Reference",
"🤖 Model Performance",
"💼 Business Dashboard",
])
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TAB 1 — HOME & DATA QUALITY
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
with tabs[0]:
st.markdown("""
## 🏠 Credit Risk Intelligence Platform
This platform was developed for the **DataQuest 2026 Credit Risk Challenge** and demonstrates an interpretable, regulator-aware credit-risk modelling framework using logistic regression and Weight of Evidence (WoE) methodologies.
### Key Capabilities
- Interactive exploratory data analysis (EDA)
- WoE & Information Value (IV) analysis
- Logistic regression scorecard modelling
- Regulatory-safe feature engineering
- Threshold optimisation & business strategy simulation
- Portfolio risk monitoring insights
### Final Model Performance
- **AUC:** 0.7822
- **Gini:** 0.5644
- **Validation:** 5-Fold Stratified Cross-Validation
- **Approach:** Interpretable L2-Regularised Logistic Regression
The final framework balances predictive performance, interpretability, and regulatory defensibility for realistic lending decision support.
""")
st.markdown(f"""
<div class='dq-header'>
<h1>Credit Risk Intelligence Platform</h1>
<p>DataQuest 2026 · Loan Default Prediction · Interactive EDA & Decision Support</p>
</div>
""", unsafe_allow_html=True)
# ── KPI row ──────────────────────────────────────────────────────────────
k1, k2, k3, k4, k5 = st.columns(5)
k1.metric("Records", f"{len(raw):,}")
k2.metric("Features", f"{raw.shape[1]}")
k3.metric("Default Rate", f"{raw['default_flag'].mean():.1%}")
k4.metric("Training rows", f"{len(train):,}")
k5.metric("Missing Cells", f"{raw.isna().sum().sum():,}")
st.markdown("---")
# ── Data quality report ───────────────────────────────────────────────────
st.markdown("<div class='section-title'>Data Quality Report</div>", unsafe_allow_html=True)
dq = data_quality_report(raw)
# Highlight rows with issues
def style_dq(row):
if row["Issue"]:
return ["background-color: rgba(247,129,102,0.1)"] * len(row)
return [""] * len(row)
styled_dq = dq.style.apply(style_dq, axis=1).format({"Missing %": "{:.2f}%"})
st.dataframe(styled_dq, use_container_width=True, height=500)
# ── Key issues callout boxes ──────────────────────────────────────────────
st.markdown("---")
st.markdown("<div class='section-title'>Critical Data Issues Found</div>", unsafe_allow_html=True)
col_a, col_b = st.columns(2)
with col_a:
st.markdown("""
<div class='insight-card warning'>
<strong>⚠️ Inconsistent Categorical Encoding</strong><br><br>
<code>home_ownership</code>: 14 raw variants for 4 categories
(MORTGAGE, RENT, OWN, OTHER). Examples: "mortgage", "Mortgage", "MORTGAGE"
all mean the same thing.<br><br>
<code>loan_purpose</code>: 21 raw variants for 7 categories.
"debt_consolidation", "Debt Consolidation", "DEBT_CONSOLIDATION" are identical.<br><br>
<em>→ Standardised in cleaning pipeline.</em>
</div>
<div class='insight-card warning'>
<strong>⚠️ Mixed Date Formats</strong><br><br>
<code>application_date</code> arrives in 3 different formats:
YYYY-MM-DD (~70%), MM/DD/YYYY (~20%), DD-Mon-YYYY (~10%).
Standard parsers fail silently on the minority formats.<br><br>
<em>→ Custom multi-format parser applied.</em>
</div>
""", unsafe_allow_html=True)
with col_b:
st.markdown("""
<div class='insight-card warning'>
<strong>⚠️ 50% Missing — months_since_last_delinquency</strong><br><br>
This column is missing for ~60,380 records. However, this is
<em>informative missingness</em>: applicants with no prior
delinquency have no value to record. Naive imputation would
destroy this signal.<br><br>
<em>→ Created binary flag <code>has_prior_delinquency</code>
and filled with sentinel 999.</em>
</div>
<div class='insight-card warning'>
<strong>⚠️ Extreme Outliers in annual_income</strong><br><br>
Max income = $2,000,000 vs median = $52,490.
The top 1% distorts means and damages model calibration.<br><br>
<em>→ Winsorised at 1st–99th percentile.</em>
</div>
""", unsafe_allow_html=True)
# ── Target distribution ───────────────────────────────────────────────────
st.markdown("---")
st.markdown("<div class='section-title'>Target Variable: Default Distribution</div>", unsafe_allow_html=True)
c1, c2 = st.columns([1, 2])
with c1:
n_def = int(raw["default_flag"].sum())
n_non = int(len(raw) - n_def)
st.metric("Non-Defaulters (0)", f"{n_non:,}", delta=f"{n_non/len(raw):.1%}")
st.metric("Defaulters (1)", f"{n_def:,}", delta=f"-{n_def/len(raw):.1%}", delta_color="inverse")
st.markdown("""
<div class='insight-card'>
<strong>Class Imbalance</strong><br>
85.6% non-default vs 15.4% default. Models trained
without addressing this will be biased toward predicting
no default. Use class weights or resampling in Task 2.
</div>
""", unsafe_allow_html=True)
with c2:
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
# Bar chart
vals = [n_non, n_def]
colors = [PALETTE["good"], PALETTE["bad"]]
bars = axes[0].bar(["Non-Default\n(0)", "Default\n(1)"], vals, color=colors,
width=0.5, edgecolor=PALETTE["border"])
for b in bars:
h = b.get_height()
axes[0].text(b.get_x() + b.get_width()/2, h + 500,
f"{h:,.0f}\n({h/len(raw):.1%})",
ha="center", va="bottom", fontsize=9, color=PALETTE["text"])
axes[0].set_ylabel("Count")
axes[0].set_title("Class Counts", fontweight="bold")
axes[0].yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f"{x/1000:.0f}K"))
# Default rate by year
clean_plot = clean.copy()
yr_rate = clean_plot.groupby("app_year")["default_flag"].mean().reset_index()
axes[1].plot(yr_rate["app_year"], yr_rate["default_flag"],
color=PALETTE["accent"], marker="o", linewidth=2.5, markersize=7)
axes[1].fill_between(yr_rate["app_year"], yr_rate["default_flag"],
alpha=0.15, color=PALETTE["accent"])
axes[1].set_ylabel("Default Rate")
axes[1].set_title("Default Rate by Year", fontweight="bold")
axes[1].yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1))
axes[1].set_xticks(yr_rate["app_year"])
for spine in axes[1].spines.values():
spine.set_color(PALETTE["border"])
plt.tight_layout(pad=2.0)
st.pyplot(fig)
plt.close()
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TAB 2 — UNIVARIATE EXPLORER
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
with tabs[1]:
st.markdown("<div class='section-title'>Univariate Feature Explorer</div>", unsafe_allow_html=True)
# ── Feature selector ─────────────────────────────────────────────────────
col_sel, col_bins = st.columns([3, 1])
with col_sel:
selected_feature = st.selectbox(
"Select a feature to explore:",
ALL_FEATURES,
index=ALL_FEATURES.index("interest_rate"),
)
with col_bins:
n_bins_uni = st.slider("Bins / Groups", 5, 20, 10,
help="Number of bins for numeric features; groups for categorical.")
is_numeric_feat = selected_feature in NUMERIC_FEATURES
# ── Compute WoE / IV ─────────────────────────────────────────────────────
try:
woe_table = compute_woe_iv(df_analysis, selected_feature,
bins=n_bins_uni)
iv_val = float(woe_table["IV_contribution"].sum())
except Exception as e:
woe_table = None
iv_val = np.nan
st.warning(f"WoE calculation issue: {e}")
# ── IV label ─────────────────────────────────────────────────────────────
def iv_label(iv):
if np.isnan(iv): return "N/A", "iv-useless"
if iv < 0.02: return "Useless", "iv-useless"
if iv < 0.10: return "Weak", "iv-weak"
if iv < 0.30: return "Medium", "iv-medium"
if iv < 0.50: return "Strong", "iv-strong"
return "Suspicious", "iv-suspicious"
label_txt, label_cls = iv_label(iv_val)
# KPIs
kp1, kp2, kp3, kp4 = st.columns(4)
kp1.metric("Feature", selected_feature)
kp2.metric("Type", "Numeric" if is_numeric_feat else "Categorical")
iv_display = f"{iv_val:.4f}" if not np.isnan(iv_val) else "N/A"
kp3.metric("Information Value (IV)", iv_display)
kp4.metric("Predictive Power", label_txt)
st.markdown("---")
# ── Plots ─────────────────────────────────────────────────────────────────
plot_col, table_col = st.columns([3, 2])
with plot_col:
fig, axes = plt.subplots(2, 2, figsize=(11, 8))
fig.suptitle(f"Univariate Analysis: {selected_feature}",
fontsize=13, fontweight="bold", color=PALETTE["text"], y=1.01)
non_def = df_analysis[df_analysis["default_flag"] == 0][selected_feature].dropna()
defaults = df_analysis[df_analysis["default_flag"] == 1][selected_feature].dropna()
all_vals = df_analysis[selected_feature].dropna()
# ── Plot 1: Overall distribution ─────────────────────────────────────
ax = axes[0, 0]
if is_numeric_feat:
ax.hist(all_vals, bins=40, color=PALETTE["accent3"], alpha=0.8, edgecolor=PALETTE["bg"])
ax.axvline(all_vals.median(), color=PALETTE["accent"], linewidth=2,
linestyle="--", label=f"Median: {all_vals.median():.2f}")
ax.legend(fontsize=8)
else:
vc = all_vals.value_counts().head(15)
ax.barh(range(len(vc)), vc.values, color=PALETTE["accent3"])
ax.set_yticks(range(len(vc)))
ax.set_yticklabels(vc.index, fontsize=8)
ax.invert_yaxis()
ax.set_title("Overall Distribution", fontweight="bold", fontsize=10)
ax.set_xlabel(selected_feature)
# ── Plot 2: Distribution by default status ───────────────────────────
ax = axes[0, 1]
if is_numeric_feat:
ax.hist(non_def, bins=40, color=PALETTE["good"], alpha=0.6,
label="Non-Default", density=True)
ax.hist(defaults, bins=40, color=PALETTE["bad"], alpha=0.6,
label="Default", density=True)
ax.legend(fontsize=8)
else:
dr = (df_analysis.groupby(selected_feature)["default_flag"]
.agg(["mean", "count"])
.rename(columns={"mean": "default_rate", "count": "n"})
.sort_values("default_rate", ascending=False)
.head(15))
colors_bar = [PALETTE["bad"] if r > df_analysis["default_flag"].mean()
else PALETTE["good"] for r in dr["default_rate"]]
ax.barh(range(len(dr)), dr["default_rate"], color=colors_bar)
ax.axvline(df_analysis["default_flag"].mean(),
color=PALETTE["accent"], linestyle="--", linewidth=1.5, label="Avg")
ax.set_yticks(range(len(dr)))
ax.set_yticklabels(dr.index, fontsize=8)
ax.invert_yaxis()
ax.xaxis.set_major_formatter(mticker.PercentFormatter(xmax=1))
ax.legend(fontsize=8)
ax.set_title("Distribution by Default Status", fontweight="bold", fontsize=10)
ax.set_xlabel("Density" if is_numeric_feat else "Default Rate")
# ── Plot 3: WoE bar chart ─────────────────────────────────────────────
ax = axes[1, 0]
if woe_table is not None:
woe_colors = [PALETTE["bad"] if w > 0 else PALETTE["good"]
for w in woe_table["WoE"]]
bins_str = [str(b)[:25] for b in woe_table["Bin"]]
y_pos = range(len(woe_table))
ax.barh(y_pos, woe_table["WoE"], color=woe_colors, alpha=0.85)
ax.axvline(0, color=PALETTE["text"], linewidth=1)
ax.set_yticks(y_pos)
ax.set_yticklabels(bins_str, fontsize=7)
ax.invert_yaxis()
ax.set_xlabel("Weight of Evidence (WoE)")
bad_patch = mpatches.Patch(color=PALETTE["bad"], label="Higher risk (WoE > 0)")
good_patch = mpatches.Patch(color=PALETTE["good"], label="Lower risk (WoE < 0)")
ax.legend(handles=[bad_patch, good_patch], fontsize=7)
ax.set_title("Weight of Evidence by Bin", fontweight="bold", fontsize=10)
# ── Plot 4: Bad rate by bin ───────────────────────────────────────────
ax = axes[1, 1]
if woe_table is not None:
bins_str = [str(b)[:25] for b in woe_table["Bin"]]
y_pos = range(len(woe_table))
bar_colors = [PALETTE["bad"] if r > df_analysis["default_flag"].mean()
else PALETTE["good"] for r in woe_table["Bad_Rate"]]
ax.barh(y_pos, woe_table["Bad_Rate"], color=bar_colors, alpha=0.85)
ax.axvline(df_analysis["default_flag"].mean(),
color=PALETTE["accent"], linestyle="--", linewidth=1.5,
label=f"Average: {df_analysis['default_flag'].mean():.1%}")
ax.set_yticks(y_pos)
ax.set_yticklabels(bins_str, fontsize=7)
ax.invert_yaxis()
ax.xaxis.set_major_formatter(mticker.PercentFormatter(xmax=1))
ax.set_xlabel("Default Rate within Bin")
ax.legend(fontsize=8)
ax.set_title("Default Rate by Bin", fontweight="bold", fontsize=10)
plt.tight_layout(pad=2.0)
st.pyplot(fig)
plt.close()
with table_col:
st.markdown(f"<div class='section-title'>WoE / IV Table</div>", unsafe_allow_html=True)
if woe_table is not None:
display_woe = woe_table.copy()
display_woe["Bin"] = display_woe["Bin"].astype(str).str[:30]
display_woe = display_woe.rename(columns={
"Count": "N", "Bad_Rate": "Bad Rate",
"Dist_Bads": "Dist Bads", "Dist_Goods": "Dist Goods",
"IV_contribution": "IV Contrib"
})
display_woe["Bad Rate"] = display_woe["Bad Rate"].map("{:.1%}".format)
display_woe["WoE"] = display_woe["WoE"].map("{:.4f}".format)
display_woe["IV Contrib"] = display_woe["IV Contrib"].map("{:.4f}".format)
display_woe = display_woe[["Bin", "N", "Bads", "Goods", "Bad Rate", "WoE", "IV Contrib"]]
st.dataframe(display_woe, use_container_width=True, hide_index=True)
iv_label_html = f"IV = {iv_display} — {label_txt}"
st.markdown(f"""
<div class='insight-card' style='margin-top:16px;'>
<strong>{iv_label_html}</strong><br><br>
{"WoE > 0 means that bin has a <em>higher proportion of defaulters</em> than the population average. "
"WoE < 0 means relatively more non-defaulters — a 'safer' segment." if woe_table is not None else ""}
</div>
""", unsafe_allow_html=True)
# ── Feature IV ranking ────────────────────────────────────────────────────
st.markdown("---")
st.markdown("<div class='section-title'>All Features — Information Value Ranking</div>",
unsafe_allow_html=True)
with st.spinner("Computing IVs for all features…"):
iv_df = iv_all_features(df_analysis, ALL_FEATURES)
# Plot IV bar chart
fig_iv, ax_iv = plt.subplots(figsize=(12, 5))
iv_colors = []
for iv in iv_df["IV"]:
if np.isnan(iv) or iv < 0.02: iv_colors.append(PALETTE["muted"])
elif iv < 0.10: iv_colors.append("#FFDF5D")
elif iv < 0.30: iv_colors.append(PALETTE["accent3"])
elif iv < 0.50: iv_colors.append(PALETTE["accent"])
else: iv_colors.append(PALETTE["bad"])
bars_iv = ax_iv.bar(range(len(iv_df)), iv_df["IV"].fillna(0), color=iv_colors, width=0.7)
ax_iv.set_xticks(range(len(iv_df)))
ax_iv.set_xticklabels(iv_df["Feature"], rotation=45, ha="right", fontsize=8)
ax_iv.set_ylabel("Information Value (IV)")
ax_iv.set_title("Feature Predictive Power — Information Value", fontweight="bold")
# Threshold lines
for thresh, lbl, col in [(0.02, "Useless <0.02", PALETTE["muted"]),
(0.10, "Weak <0.1", "#FFDF5D"),
(0.30, "Medium <0.3", PALETTE["accent3"])]:
ax_iv.axhline(thresh, color=col, linestyle="--", linewidth=1, alpha=0.7)
ax_iv.text(len(iv_df) - 0.5, thresh + 0.002, lbl, fontsize=7,
color=col, ha="right", va="bottom")
# Highlight selected feature
if selected_feature in iv_df["Feature"].values:
idx = iv_df[iv_df["Feature"] == selected_feature].index[0]
bars_iv[idx].set_edgecolor(PALETTE["text"])
bars_iv[idx].set_linewidth(2.5)
plt.tight_layout()
st.pyplot(fig_iv)
plt.close()
# Table
st.dataframe(iv_df, use_container_width=True, hide_index=True)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TAB 3 — BIVARIATE EXPLORER
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
with tabs[2]:
st.markdown("<div class='section-title'>Bivariate Relationship Explorer</div>", unsafe_allow_html=True)
biv_type = st.radio("Exploration type:",
["Numeric vs Numeric", "Numeric vs Target", "Correlation Heatmap",
"Categorical Breakdown"],
horizontal=True)
if biv_type == "Numeric vs Numeric":
col1, col2, col3 = st.columns(3)
with col1:
x_feat = st.selectbox("X axis", NUMERIC_FEATURES, index=9) # interest_rate
with col2:
y_feat = st.selectbox("Y axis", NUMERIC_FEATURES, index=3) # dti_ratio
with col3:
sample_n = st.slider("Sample size (for speed)", 500, 10000, 3000, 500)
plot_df = df_analysis.dropna(subset=[x_feat, y_feat]).sample(
min(sample_n, len(df_analysis)), random_state=42)
fig, ax = plt.subplots(figsize=(9, 6))
scatter = ax.scatter(
plot_df[x_feat], plot_df[y_feat],
c=plot_df["default_flag"].map({0: PALETTE["good"], 1: PALETTE["bad"]}),
alpha=0.4, s=12, edgecolors="none"
)
ax.set_xlabel(x_feat)
ax.set_ylabel(y_feat)
ax.set_title(f"{x_feat} vs {y_feat} (coloured by default)", fontweight="bold")
good_p = mpatches.Patch(color=PALETTE["good"], label="Non-Default")
bad_p = mpatches.Patch(color=PALETTE["bad"], label="Default")
ax.legend(handles=[good_p, bad_p], fontsize=9)
# Correlation annotation
corr = plot_df[[x_feat, y_feat]].corr().iloc[0, 1]
ax.text(0.02, 0.97, f"Pearson r = {corr:.3f}",
transform=ax.transAxes, fontsize=10, va="top",
color=PALETTE["accent"], fontfamily="monospace")
plt.tight_layout()
st.pyplot(fig)
plt.close()
elif biv_type == "Numeric vs Target":
feat_biv = st.selectbox("Select numeric feature:", NUMERIC_FEATURES,
index=NUMERIC_FEATURES.index("interest_rate"))
n_bins_biv = st.slider("Number of bins", 5, 20, 10)
bin_col = f"_bin_{feat_biv}"
plot_df = df_analysis.dropna(subset=[feat_biv]).copy()
plot_df[bin_col] = pd.qcut(plot_df[feat_biv], q=n_bins_biv, duplicates="drop")
grp = plot_df.groupby(bin_col, observed=True)["default_flag"].agg(["mean","count"]).reset_index()
grp.columns = ["Bin", "Default Rate", "Count"]
grp["Bin_mid"] = grp["Bin"].apply(lambda x: x.mid).astype(float)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 7), sharex=True)
# Default rate by bin
bar_colors = [PALETTE["bad"] if r > plot_df["default_flag"].mean() else PALETTE["good"]
for r in grp["Default Rate"]]
ax1.bar(range(len(grp)), grp["Default Rate"], color=bar_colors, alpha=0.85, width=0.7)
ax1.axhline(plot_df["default_flag"].mean(), color=PALETTE["accent"],
linestyle="--", linewidth=2, label=f"Overall avg: {plot_df['default_flag'].mean():.1%}")
ax1.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1))
ax1.set_ylabel("Default Rate")
ax1.set_title(f"Default Rate by {feat_biv} Bin", fontweight="bold")
ax1.legend()
# Count per bin
ax2.bar(range(len(grp)), grp["Count"], color=PALETTE["accent3"], alpha=0.7, width=0.7)
ax2.set_ylabel("Count")
ax2.set_xlabel("Bin")
ax2.set_xticks(range(len(grp)))
ax2.set_xticklabels([str(b)[:20] for b in grp["Bin"]], rotation=45, ha="right", fontsize=7)
ax2.set_title("Record Count per Bin", fontweight="bold")
plt.tight_layout()
st.pyplot(fig)
plt.close()
# Table
grp["Default Rate"] = grp["Default Rate"].map("{:.1%}".format)
grp["Count"] = grp["Count"].map("{:,.0f}".format)
st.dataframe(grp[["Bin", "Count", "Default Rate"]], use_container_width=True, hide_index=True)
elif biv_type == "Correlation Heatmap":
# Select numeric features for heatmap
corr_features = st.multiselect(
"Features to include:",
NUMERIC_FEATURES,
default=["interest_rate", "dti_ratio", "age", "annual_income",
"num_delinquencies_2yr", "credit_utilisation_pct",
"employment_length_years", "months_since_oldest_account",
"pct_accounts_current", "default_flag"]
)
if len(corr_features) >= 2:
corr_method = st.radio("Correlation method:", ["pearson", "spearman"], horizontal=True)
corr_matrix = df_analysis[corr_features].corr(method=corr_method)
fig, ax = plt.subplots(figsize=(max(8, len(corr_features)), max(6, len(corr_features) - 1)))
mask = np.zeros_like(corr_matrix, dtype=bool)
mask[np.triu_indices_from(mask, k=1)] = True
sns.heatmap(
corr_matrix, ax=ax, mask=mask,
cmap="RdYlGn", center=0, vmin=-1, vmax=1,
annot=True, fmt=".2f", annot_kws={"size": 8},
linewidths=0.5, linecolor=PALETTE["border"],
cbar_kws={"shrink": 0.8},
)
ax.set_title(f"Feature Correlation ({corr_method.title()})", fontweight="bold")
plt.tight_layout()
st.pyplot(fig)
plt.close()
# Highlight strong correlations with target
if "default_flag" in corr_features:
st.markdown("<div class='section-title'>Correlations with default_flag</div>",
unsafe_allow_html=True)
target_corr = (corr_matrix["default_flag"]
.drop("default_flag")
.sort_values(key=abs, ascending=False)
.reset_index())
target_corr.columns = ["Feature", f"{corr_method.title()} r"]
target_corr[f"{corr_method.title()} r"] = target_corr[f"{corr_method.title()} r"].round(4)
st.dataframe(target_corr, use_container_width=True, hide_index=True)
else:
st.info("Select at least 2 features.")
else: # Categorical Breakdown
cat_feat = st.selectbox("Select categorical feature:", CATEGORICAL_FEATURES)
grp = df_analysis.groupby(cat_feat)["default_flag"].agg(["mean","count"]).reset_index()
grp.columns = [cat_feat, "Default Rate", "Count"]
grp = grp.sort_values("Default Rate", ascending=False)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
avg_rate = df_analysis["default_flag"].mean()
bar_cols = [PALETTE["bad"] if r > avg_rate else PALETTE["good"] for r in grp["Default Rate"]]
ax1.barh(range(len(grp)), grp["Default Rate"], color=bar_cols, alpha=0.85)
ax1.axvline(avg_rate, color=PALETTE["accent"], linestyle="--", linewidth=2,
label=f"Avg: {avg_rate:.1%}")
ax1.set_yticks(range(len(grp)))
ax1.set_yticklabels(grp[cat_feat], fontsize=9)
ax1.invert_yaxis()
ax1.xaxis.set_major_formatter(mticker.PercentFormatter(xmax=1))
ax1.set_title(f"Default Rate by {cat_feat}", fontweight="bold")
ax1.legend()
ax2.barh(range(len(grp)), grp["Count"], color=PALETTE["accent3"], alpha=0.7)
ax2.set_yticks(range(len(grp)))
ax2.set_yticklabels(grp[cat_feat], fontsize=9)
ax2.invert_yaxis()
ax2.xaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f"{x/1000:.0f}K"))
ax2.set_title(f"Record Count by {cat_feat}", fontweight="bold")
plt.tight_layout()
st.pyplot(fig)
plt.close()
grp["Default Rate"] = grp["Default Rate"].map("{:.1%}".format)
grp["Count"] = grp["Count"].map("{:,.0f}".format)
st.dataframe(grp, use_container_width=True, hide_index=True)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TAB 4 — RESEARCH REFERENCE
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
with tabs[3]:
st.markdown("<div class='section-title'>Research Reference</div>", unsafe_allow_html=True)
res_sec = st.selectbox("Jump to section:", [
"1. GLM vs Non-Linear Models",
"2. Interpretability vs Complexity",
"3. Weight of Evidence & Information Value",
"4. Model Evaluation Metrics",
"5. Regulatory Considerations",
])
if "1." in res_sec:
st.markdown("""
## Generalised Linear Models vs Non-Linear Models
### Logistic Regression (GLM for Binary Classification)
Logistic regression models the **log-odds** of the positive class (default) as a linear
function of features:
$$\\eta = \\beta_0 + \\beta_1 x_1 + \\beta_2 x_2 + \\cdots + \\beta_p x_p$$
The probability of default is recovered via the **sigmoid (logistic) function**:
$$P(Y=1 \\mid X) = \\sigma(\\eta) = \\frac{1}{1 + e^{-\\eta}}$$
**Key properties:**
- Each coefficient $\\beta_j$ has a direct interpretation: a unit increase in $x_j$
changes the log-odds by $\\beta_j$, or equivalently multiplies the *odds* of default
by $e^{\\beta_j}$.
- Assumes a **linear relationship** between features and the log-odds.
- Fast to train, stable, easy to audit. Required in many regulated industries.
### Non-Linear Models
| Model | How it works | Interpretability |
|---|---|---|
| **Decision Tree** | Recursive feature splits | High (visual) |
| **Random Forest** | Ensemble of trees (bagging) | Low (black box) |
| **Gradient Boosting** (LightGBM, XGBoost) | Additive weak learners | Low–Medium |
| **Neural Network** | Layered non-linear transformations | Very Low |
Non-linear models can capture complex interactions and achieve higher AUC on the same data,
but at the cost of **interpretability** — which is unacceptable in regulated lending.
In this dataset, LightGBM achieves AUC ≈ 0.82 vs. baseline logistic regression ≈ 0.68.
Through **careful feature engineering** (WoE encoding, interaction terms, log-transforms),
we aim to narrow this gap while remaining fully interpretable.
""")
elif "2." in res_sec:
st.markdown("""
## The Interpretability–Complexity Trade-off
```
High ──────────────────────────── Low
Interpretability ◄──────────► Complexity / Performance
Logistic Regression Decision Tree Random Forest Neural Network
● ● ● ●
High ─────┼───────────────┼───────────────┼───────────────┼──── Low
```
### Why Interpretability Matters in Credit
1. **Regulation**: Credit bureaus and regulators (e.g. Basel, FCRA, GDPR) require that
lenders explain *why* a loan was declined.
2. **Fairness auditing**: Regulators must be able to check whether decisions are
discriminatory by examining model coefficients.
3. **Operational trust**: Risk managers, loan officers, and board members need to
understand and challenge the model's logic.
### Engineering Interpretability into Logistic Regression
The gap between logistic regression and black-box models is often **feature engineering**,
not model capacity. Techniques that close this gap:
- **WoE encoding**: Transforms features into their log-odds contribution → makes
non-linear relationships linear.
- **Binning + indicator variables**: Captures threshold effects (e.g. DTI > 40%).
- **Interaction terms**: Explicitly models feature combinations.
- **Scorecard transformation**: Converts coefficients into human-readable score points.
""")
elif "3." in res_sec:
st.markdown("""
## Weight of Evidence (WoE) & Information Value (IV)
Originally developed by credit scorecards practitioners. WoE transforms raw feature
values into their **log-odds contribution to default prediction**.
### WoE Formula
For bin $i$ of a feature:
$$WoE_i = \\ln\\left(\\frac{P(\\text{Bads in bin } i)}{P(\\text{Goods in bin } i)}\\right)
= \\ln\\left(\\frac{\\text{Bad}_i / \\text{Total Bads}}{\\text{Good}_i / \\text{Total Goods}}\\right)$$
**Interpretation:**
- $WoE > 0$: This bin has a *higher concentration of defaulters* than average → risky
- $WoE < 0$: This bin has a *higher concentration of non-defaulters* → safer
- $WoE = 0$: Bin default rate equals the population average → no signal
### Information Value (IV)
IV measures the *total* predictive power of a feature by aggregating WoE across all bins:
$$IV = \\sum_{i} \\left(P(\\text{Bads}_i) - P(\\text{Goods}_i)\\right) \\times WoE_i$$
| IV Range | Predictive Power |
|---|---|
| < 0.02 | Useless — exclude from model |
| 0.02 – 0.10 | Weak — marginal value |
| 0.10 – 0.30 | Medium — useful predictor |
| 0.30 – 0.50 | Strong — very useful |
| > 0.50 | Suspicious — check for data leakage |
### Why WoE is Valuable in Credit Modelling
1. **Handles non-linearity**: By binning and applying WoE, we can capture non-linear
relationships within a logistic regression framework.
2. **Handles categoricals naturally**: WoE replaces arbitrary dummy encoding.
3. **Automatic outlier dampening**: Extreme values fall into edge bins and receive a
single WoE value, preventing outlier distortion.