-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamlit_app_European_bank.py
More file actions
650 lines (479 loc) Β· 18 KB
/
Streamlit_app_European_bank.py
File metadata and controls
650 lines (479 loc) Β· 18 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
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import joblib
import os
st.set_page_config(page_title="Customer Churn Dashboard", layout="wide")
#Loading the model
#model=joblib.load("churn_model.pkl'")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
model_path = os.path.join(BASE_DIR, "churn_model.pkl")
model = joblib.load(model_path)
#Load dataset at once
df=pd.read_csv("European_Bank.csv")
# ---------------- DASHBOARD FILTERS ----------------
st.sidebar.header("π Course Configuration")
selected_geo = st.sidebar.selectbox(
"Select Geography",
["All"] + list(df["Geography"].unique())
)
age_filter = st.sidebar.slider(
"Select Age Range",
int(df["Age"].min()),
int(df["Age"].max()),
(18, 60)
)
active_only = st.sidebar.checkbox("Active Members Only")
product_filter = st.sidebar.slider(
"Number of Products",
int(df["NumOfProducts"].min()),
int(df["NumOfProducts"].max()),
(1,4)
)
balance_filter = st.sidebar.slider(
"Balance Range",
int(df["Balance"].min()),
int(df["Balance"].max()),
(0,200000)
)
salary_filter = st.sidebar.slider(
"Salary Range",
int(df["EstimatedSalary"].min()),
int(df["EstimatedSalary"].max()),
(0,200000)
)
filtered_df = df.copy()
if selected_geo != "All":
filtered_df = filtered_df[filtered_df["Geography"] == selected_geo]
filtered_df = filtered_df[
(filtered_df["Age"] >= age_filter[0]) &
(filtered_df["Age"] <= age_filter[1])
]
if active_only:
filtered_df = filtered_df[filtered_df["IsActiveMember"] == 1]
filtered_df = filtered_df[
(filtered_df["NumOfProducts"] >= product_filter[0]) &
(filtered_df["NumOfProducts"] <= product_filter[1])
]
filtered_df = filtered_df[
(filtered_df["Balance"] >= balance_filter[0]) &
(filtered_df["Balance"] <= balance_filter[1])
]
filtered_df = filtered_df[
(filtered_df["EstimatedSalary"] >= salary_filter[0]) &
(filtered_df["EstimatedSalary"] <= salary_filter[1])
]
#Page config
#st.set_page_config(page_title="Customer Churn Dashboard", layout="wide")
col1,col2,col3=st.columns([1,3,1])
with col1:
st.image("Logo_ecb.png",width=200)
with col2:
st.title(" π¦ Customer Engagement & Product Utilization Analytics ")
st.caption("Customer churn prediction,retention analytics using XGBoost model and provides predictive insights to help banks reduce customer atttrition.")
with col3:
st.image("Logo_unified.png",width=180)
# ===================================
# π KEY PERFORMANCE INDICATORS (PROJECT BASED)
# ===================================
# ===== KPI CALCULATIONS =====
total_customers = len(filtered_df)
churn_rate = filtered_df["Exited"].mean() * 100
engagement_retention_ratio = (
filtered_df[filtered_df["IsActiveMember"] == 1].shape[0]
/ total_customers
) * 100
product_depth_index = filtered_df["NumOfProducts"].mean()
high_balance_disengagement_rate = (
filtered_df[filtered_df["Balance"] > 100000]["Exited"].mean()
) * 100
credit_card_stickiness = (
filtered_df[filtered_df["HasCrCard"] == 1]["Exited"].mean()
) * 100
relationship_strength_index = (
(engagement_retention_ratio / 100)
* product_depth_index
* (1 - churn_rate / 100)
)
st.subheader(" π Key Performance Indicators")
#left, center, right = st.columns([1, 5, 1])
#with center:
col1, col2, col3, col4, col5, col6 = st.columns(6)
col1.metric("Engagement", f"{engagement_retention_ratio:.1f}%")
col2.metric("Product Depth", f"{product_depth_index:.2f}")
col3.metric("High Balance Risk", f"{high_balance_disengagement_rate:.1f}%")
col4.metric("Credit Card Stickiness", f"{credit_card_stickiness:.1f}%")
col5.metric("Relationship Index", f"{relationship_strength_index:.2f}")
col6.metric("Churn Rate", f"{churn_rate:.1f}%")
st.divider()
#st.divider()
#Sidebar
page = st.sidebar.radio(
"Select Module",
["π Overview",
"π¦ Product Analysis",
"π° High Value Risk",
"π Retention Score",
"π€ Churn Prediction",
"π§ Model Insights"]
)
# OVERVIEW PAGE
if page == "π Overview":
#st.header("π Key Performance Indicators (KPIs)")
#kpi_data = pd.DataFrame({
# "KPI Name": [
# "Engagement Retention Ratio",
# "Product Depth Index",
# "High-Balance Disengagement Rate",
# "Credit Card Stickiness Score",
# "Relationship Strength Index"
# ],
# "Description": [
# "Active vs inactive churn comparison",
# "Products used vs loyalty",
# "Premium churn risk",
# "Card ownership retention impact",
# "Combined engagement & product score"
# ]
#})
#st.table(kpi_data)
#st.divider()
#pie chart
st.subheader("Customer Churn Distribution")
churn_counts=filtered_df["Exited"].value_counts()
left,center,right=st.columns([1.5,2,1.5])
with center:
fig, ax =plt.subplots(figsize=(5,4))
colors=sns.color_palette("Set2")
wedges,texts,autotexts=ax.pie(
churn_counts,
labels=["Active","Churned"],
autopct=lambda p:f"{p:.1f}%",
startangle=90,
colors=colors,
textprops={'fontsize':15} , #label size
wedgeprops={"edgecolor":"white"}
)
#percentages font size
for autotext in autotexts:
autotext.set_fontsize(15)
ax.set_title("Churn vs Active Customers",fontsize=15)
st.pyplot(fig)
st.divider()
st.subheader(" Customer Churn Patterns by Geography and Product Usage")
col1, col2 = st.columns(2)
# -------- Geography Churn --------
with col1:
geo_churn = filtered_df.groupby("Geography")["Exited"].mean() * 100
fig2, ax2 = plt.subplots(figsize=(6,3))
sns.barplot(
x=geo_churn.index,
y=geo_churn.values,
palette="viridis",
ax=ax2
)
ax2.set_title("Churn Rate by Geography", fontsize=10)
ax2.set_ylabel("%")
ax2.tick_params(labelsize=8)
st.pyplot(fig2)
# -------- Product Churn --------
with col2:
product_churn = filtered_df.groupby("NumOfProducts")["Exited"].mean() * 100
fig3, ax3 = plt.subplots(figsize=(6,3))
sns.barplot(
x=product_churn.index,
y=product_churn.values,
palette="coolwarm",
ax=ax3
)
ax3.set_title("Churn by Products", fontsize=10)
ax3.set_ylabel("%")
ax3.tick_params(labelsize=8)
st.pyplot(fig3)
#KPI-2:Product Utilization Impact Analysis
elif page == "π¦ Product Analysis":
st.header("π¦ Product Utilization Impact Analysis")
# Churn by number of products
#churn_by_products = filtered_df.groupby("NumOfProducts")["Exited"].mean()
st.subheader("Churn Rate by Number of Products")
#'''st.line_chart(churn_by_products)
#st.markdown("---")
# Average balance by product count
#avg_balance = filtered_df.groupby("NumOfProducts")["Balance"].mean()
#st.subheader("Average Balance by Product Count")
#st.bar_chart(avg_balance)'''
churn_by_products = (
filtered_df.groupby("NumOfProducts")["Exited"].mean().reset_index()
)
left1,center1,right1=st.columns([1,2,1])
with center1:
fig1, ax1 = plt.subplots(figsize=(6,3))
sns.barplot(
data=churn_by_products,
x="NumOfProducts",
y="Exited",
palette="Blues"
)
ax1.set_ylabel("Churn Rate")
ax1.set_xlabel("Number of Products")
ax1.set_title("Product Usage vs Churn")
st.pyplot(fig1)
st.divider()
avg_balance = (
filtered_df.groupby("NumOfProducts")["Balance"].mean().reset_index()
)
st.subheader("Average Balance by Product Count")
left2,center2,right2=st.columns([1,2,1])
with center2:
fig2, ax2 = plt.subplots(figsize=(6,3))
sns.barplot(
data=avg_balance,
x="NumOfProducts",
y="Balance",
palette="Greens",
)
ax2.set_title("Balance Distribution by Product Count",fontsize=10)
ax2.set_ylabel("Churn Rate")
ax2.set_xlabel("Num of Products")
ax2.tick_params(labelsize=8)
st.pyplot(fig2)
#KPI-3: High-value Disengaged Customer Detector
elif page == "π° High Value Risk":
st.header(" High-Value Disengaged Customers")
# Define threshold
balance_threshold = st.slider("Select Minimum Balance", 0, 300000, 100000)
# High value customers
high_value = filtered_df[filtered_df["Balance"] > balance_threshold]
# Among them, churned customers
high_risk = high_value[high_value["Exited"] == 1]
total_high_value = len(high_value)
total_high_risk = len(high_risk)
risk_percentage=(total_high_risk/total_high_value)*100 if total_high_value >0 else 0
col1, col2,col3 = st.columns(3)
col1.metric("π° High Value Customers", total_high_value)
col2.metric("β High Value At Risk", total_high_risk)
col3.metric("π Risk Percentage",f"{risk_percentage:.1f}%")
st.markdown("---")
if total_high_risk > 0:
st.error("π΄ These premium customers are at churn risk!")
st.dataframe(high_risk.head(20))
else:
st.success("π’ No high-value churn risk detected.")
#KPI-4:Retention Strength Scoring Panel
elif page == "π Retention Score":
st.header("π Retention Strength Scoring Panel")
# ---- Create Retention Score ----
filtered_df["RetentionScore"] = (
filtered_df["IsActiveMember"] * 30 +
filtered_df["NumOfProducts"] * 20 +
filtered_df["HasCrCard"] * 10 +
filtered_df["Tenure"] * 2
)
# Scale to 0-100
filtered_df["RetentionScore"] = (filtered_df["RetentionScore"] / filtered_df["RetentionScore"].max()) * 100
avg_score = filtered_df["RetentionScore"].mean()
high_retention = len(filtered_df[filtered_df["RetentionScore"] > 60])
low_retention = len(filtered_df[filtered_df["RetentionScore"] < 30])
# ---- KPI Cards ----
col1, col2, col3 = st.columns(3)
col1.metric("β Average Retention Score", f"{avg_score:.2f}")
col2.metric("π High Retention Customers", high_retention)
col3.metric("π΄ Low Retention Customers", low_retention)
st.markdown("---")
# ---- Color Based Status ----
if avg_score > 70:
st.success("π’ Strong Customer Loyalty Overall")
elif avg_score > 40:
st.warning("π‘ Moderate Retention Strength")
else:
st.error("π΄ Weak Retention β Attention Needed")
st.markdown("---")
# ---- Histogram Chart ----
st.subheader("π Retention Score Distribution")
#fig, ax = plt.subplots(figsize=(8,4))
#sns.histplot(data=filtered_df,x="RetentionScore",bins=20,kde=True,color="#1ABC9C",alpha=0.8)
#ax.set_hist(filtered_df["RetentionScore"], bins=20)
#ax.set_xlabel("Retention Score")
#ax.set_ylabel("Number of Customers")
#ax.set_title("Retention Score Distribution")
#st.pyplot(fig)'''
fig, ax = plt.subplots(figsize=(3.5,2.5))
sns.set_style("whitegrid")
sns.histplot(
data=filtered_df,
x="RetentionScore",
hue="Exited",
bins=15,
kde=True,
palette=["#4CAF50","#E53935"],
alpha=0.6,
multiple="layer",
edgecolor="white",
ax=ax
)
#remove default legend
ax.legend_.remove()
#add custom legend
from matplotlib.patches import Patch
legend_elements=[Patch(facecolor="#4CAF50",label="Retained"),
Patch(facecolor="#E53935",label="Churned")
]
ax.legend(
handles=legend_elements,
fontsize=7,
loc="upper right"
)
#ax.set_title("Retention Score vs Churn",fontsize=8)
ax.set_xlabel("Retention Score",fontsize=8)
ax.set_ylabel("Number of Customers",fontsize=8)
ax.tick_params(labelsize=7)
left,center,right=st.columns([1,2,1])
with center:
st.pyplot(fig)
## Model insights heatmap
elif page == "π§ Model Insights":
st.header("π§ Model Performance & Feature Importance")
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import seaborn as sns
import matplotlib.pyplot as plt
# -------- Prepare Data --------
X = pd.get_dummies(df.drop("Exited", axis=1), drop_first=True)
X = X[[
"CreditScore", "Age", "Tenure", "Balance",
"NumOfProducts", "HasCrCard", "IsActiveMember",
"EstimatedSalary", "Geography_Germany",
"Geography_Spain", "Gender_Male"
]]
y = df["Exited"]
# -------- Train-Test Split (IMPORTANT for correct accuracy) --------
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# -------- Model Prediction --------
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
st.metric("π― Model Accuracy (Test Data)", f"{accuracy*100:.2f}%")
st.markdown("---")
# -------- Confusion Matrix --------
st.subheader("Confusion Matrix")
cm = confusion_matrix(y_test, y_pred)
#create small centered layout
left,center,right=st.columns([1,2,1])
with center:
fig_cm, ax_cm = plt.subplots(figsize=(4,3))
sns.heatmap(
cm,
annot=True,
fmt="d",
cmap="Blues",
ax=ax_cm,
annot_kws={"fontsize":8})
ax_cm.set_xlabel("Predicted",fontsize=9)
ax_cm.set_ylabel("Actual",fontsize=9)
ax_cm.set_title("Confusion Matrix",fontsize=8)
ax_cm.tick_params(labelsize=7)
plt.tight_layout()
st.pyplot(fig_cm)
st.markdown("---")
# -------- Feature Importance --------
st.subheader("Top Features Driving Churn")
#sort importance
importance = model.feature_importances_
feature_names = [
"CreditScore", "Age", "Tenure", "Balance",
"NumOfProducts", "HasCrCard", "IsActiveMember",
"EstimatedSalary", "Geography_Germany",
"Geography_Spain", "Gender_Male"
]
importance_df = pd.DataFrame({
"Feature": feature_names,
"Importance": importance
}).sort_values(by="Importance", ascending=False)
#center layout
left,center,right=st.columns([1,2,1])
with center:
fig_imp, ax_imp = plt.subplots(figsize=(5,4))
sns.barplot(
x="Importance",
y="Feature",
data=importance_df,
palette="viridis"
)
ax_imp.set_title("Feature Importance (XGBoost)",fontsize=9)
ax_imp.tick_params(labelsize=8)
plt.tight_layout()
st.pyplot(fig_imp)
st.markdown("---")
st.dataframe(importance_df, use_container_width=True)
st.markdown("---")
st.subheader("π Key Insights from Customer Data")
st.success("""
- Customers with higher balances but inactive accounts show increased churn probability.
- Customers owning only one banking product are more likely to churn.
- Active members demonstrate significantly better retention rates.
- Customer age and account balance strongly influence churn behavior.
""")
st.markdown("---")
st.subheader("π’ Business Recommendations")
st.info("""
β’ Implement targeted retention campaigns for high-value inactive customers.
β’ Encourage cross-selling of banking products to improve customer engagement.
β’ Strengthen loyalty programs for long-term customers.
β’ Provide personalized financial offers based on customer profile and behavior.
""")
#adding user inputs
if page == "π€ Churn Prediction":
st.header("Enter Customer Details")
credit_score = st.number_input("Credit Score", 300, 900, 650)
age = st.number_input("Age", 18, 100, 35)
tenure = st.number_input("Tenure (Years)", 0, 20, 5)
balance = st.number_input("Balance", 0.0, 300000.0, 50000.0)
num_products = st.selectbox("Number of Products", [1,2,3,4])
has_card = st.selectbox("Has Credit Card", [0,1])
is_active = st.selectbox("Is Active Member", [0,1])
salary = st.number_input("Estimated Salary", 0.0, 200000.0, 50000.0)
geography = st.selectbox("Geography", ["France", "Germany", "Spain"])
gender = st.selectbox("Gender", ["Female", "Male"])
#converting categorical to model format
geo_germany = 1 if geography == "Germany" else 0
geo_spain = 1 if geography == "Spain" else 0
gender_male = 1 if gender == "Male" else 0
#create input DataFrame
#year = 2025
#input_data = np.array([[year,credit_score, age, tenure, balance,
# num_products, has_card, is_active,
# salary, geo_germany, geo_spain,
# gender_male]])
#prediction button
if st.button("Predict Churn"):
input_df=pd.DataFrame({
"CreditScore":[credit_score],
"Age":[age],
"Tenure":[tenure],
"Balance":[balance],
"NumOfProducts":[num_products],
"HasCrCard":[has_card],
"IsActiveMember":[is_active],
"EstimatedSalary":[salary],
"Geography_Germany":[geo_germany],
"Geography_Spain":[geo_spain],
"Gender_Male":[gender_male]
})
prediction = model.predict(input_df)
probability = model.predict_proba(input_df)[0][1]
st.subheader("Prediction Result")
st.metric(label="Churn Probability",
value=f"{probability*100:.2f}%",
delta=f"{(probability-0.5)*100:.2f}% vs baseline"
)
if probability >= 0.7:
st.error("π΄ High Risk of Churn")
elif probability >= 0.4:
st.warning("π Medium Risk of Churn")
else:
st.success("π’ Low Risk of Churn")
st.markdown("---")
st.caption("Developed by Jayanthi Varri")