AKKI-AFK commited on
Commit
f66c462
·
verified ·
1 Parent(s): 4363d38

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +115 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,121 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ import google.generativeai as genai
5
+ import json
6
+ import os
7
+ from datetime import datetime
8
 
9
+ # ====== CONFIG ======
10
+ st.set_page_config(page_title="ECL Risk Analyzer", layout="wide")
11
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
12
 
13
+ # ====== FUNCTIONS ======
14
+ @st.cache_data
15
+ def process_loan_data(df: pd.DataFrame):
16
+ """Compute PD, LGD, EAD, and ECL by loan_intent."""
17
+ df = df.dropna(subset=["loan_intent", "credit_score", "loan_amnt", "loan_status"])
18
+ df["loan_status"] = df["loan_status"].astype(int)
19
+ group = df.groupby("loan_intent")
20
+ pd_seg = group["loan_status"].mean()
21
+ lgd_seg = (1 - group["credit_score"].mean() / 850)
22
+ ead_seg = group["loan_amnt"].sum()
23
+ ecl_seg = pd_seg * lgd_seg * ead_seg
24
+ ecl_df = pd.concat([pd_seg, lgd_seg, ead_seg, ecl_seg], axis=1)
25
+ ecl_df.columns = ["PD", "LGD", "EAD", "ECL"]
26
+ ecl_df = ecl_df.reset_index()
27
+ return ecl_df
28
 
29
+ def get_gemini_decision(segment, pd_val, lgd_val, ead_val, ecl_val):
30
+ """Ask Gemini to decide the recommended action for a segment."""
31
+ model = genai.GenerativeModel("gemini-1.5-pro")
32
+ system_prompt = """You are a financial risk advisor.
33
+ Return only JSON: {"action":"increase_interest"|"reduce_disbursement"|"maintain","rationale":"string","confidence":float}"""
34
+ user_prompt = f"""
35
+ Segment: {segment}
36
+ PD: {pd_val:.3f}
37
+ LGD: {lgd_val:.3f}
38
+ EAD: {ead_val:,.0f}
39
+ ECL: {ecl_val:,.0f}
40
+ Rules:
41
+ - PD > 0.25 ⇒ increase_interest
42
+ - PD > 0.20 and ECL rising ⇒ reduce_disbursement
43
+ - PD < 0.15 ⇒ maintain
44
  """
45
+ try:
46
+ response = model.generate_content(
47
+ [{"role": "system", "parts": [system_prompt]},
48
+ {"role": "user", "parts": [user_prompt]}],
49
+ generation_config={"temperature": 0.2}
50
+ )
51
+ result = json.loads(response.text)
52
+ except Exception:
53
+ result = {"action": "maintain", "rationale": "Fallback - invalid JSON", "confidence": 0.0}
54
+ return result
55
+
56
+ # ====== UI ======
57
+ st.title("📊 Expected Credit Loss (ECL) Risk Dashboard")
58
+ st.write("Upload your **bank loan dataset** to compute segment-level Expected Credit Loss (ECL) and get AI-driven recommendations.")
59
+
60
+ uploaded = st.file_uploader("Upload CSV dataset", type=["csv"])
61
+
62
+ if uploaded:
63
+ df = pd.read_csv(uploaded)
64
+ st.success("Dataset loaded successfully.")
65
+ st.dataframe(df.head())
66
+
67
+ ecl_df = process_loan_data(df)
68
+ st.subheader("Segment-level ECL Summary")
69
+ st.dataframe(ecl_df, use_container_width=True, hide_index=True)
70
+
71
+ # --- Visualization: ECL by segment ---
72
+ st.subheader("ECL by Segment")
73
+ fig, ax = plt.subplots(figsize=(8, 4))
74
+ ax.bar(ecl_df["loan_intent"], ecl_df["ECL"])
75
+ ax.set_xlabel("Segment")
76
+ ax.set_ylabel("ECL")
77
+ ax.set_title("Expected Credit Loss per Segment")
78
+ plt.xticks(rotation=45)
79
+ st.pyplot(fig)
80
+
81
+ # --- Visualization: PD by segment ---
82
+ st.subheader("PD by Segment")
83
+ fig2, ax2 = plt.subplots(figsize=(8, 4))
84
+ ax2.bar(ecl_df["loan_intent"], ecl_df["PD"], color="gray")
85
+ ax2.set_xlabel("Segment")
86
+ ax2.set_ylabel("PD")
87
+ ax2.set_title("Probability of Default (PD) per Segment")
88
+ plt.xticks(rotation=45)
89
+ st.pyplot(fig2)
90
+
91
+ # --- AI Decision Section ---
92
+ st.subheader("AI Recommendations (Gemini)")
93
+ decisions = []
94
+ for _, row in ecl_df.iterrows():
95
+ decision = get_gemini_decision(row["loan_intent"], row["PD"], row["LGD"], row["EAD"], row["ECL"])
96
+ decisions.append({
97
+ "Segment": row["loan_intent"],
98
+ "Action": decision["action"],
99
+ "Rationale": decision["rationale"],
100
+ "Confidence": decision["confidence"],
101
+ "ECL": row["ECL"],
102
+ "PD": row["PD"]
103
+ })
104
+ result_df = pd.DataFrame(decisions)
105
+ result_df["Timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
106
+ st.dataframe(result_df, use_container_width=True, hide_index=True)
107
+
108
+ # --- Plot action summary ---
109
+ st.subheader("Recommended Actions Distribution")
110
+ fig3, ax3 = plt.subplots(figsize=(6, 4))
111
+ action_counts = result_df["Action"].value_counts()
112
+ ax3.pie(action_counts, labels=action_counts.index, autopct="%1.1f%%", startangle=140)
113
+ ax3.set_title("Recommended Actions per Segment")
114
+ st.pyplot(fig3)
115
+
116
+ # Option to export report
117
+ csv_out = result_df.to_csv(index=False).encode("utf-8")
118
+ st.download_button("Download ECL + Decision Report", csv_out, "ECL_Decisions.csv", "text/csv")
119
 
120
+ else:
121
+ st.info("Upload your CSV file to begin analysis.")