Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Welcome to Streamlit!Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).In the meantime, below is an example of what you can do with just a few lines of code:"""num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indicesx = radius * np.cos(theta)y = radius * np.sin(theta)df = pd.DataFrame({"x": x,"y": y,"idx": indices,"rand": np.random.randn(num_points),})st.altair_chart(alt.Chart(df, height=700, width=700).mark_point(filled=True).encode(x=alt.X("x", axis=None),y=alt.Y("y", axis=None),color=alt.Color("idx", legend=None, scale=alt.Scale()),size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398import streamlit as stimport pandas as pdimport joblibfrom catboost import Poolimport plotly.graph_objects as goimport plotly.express as pxfrom datetime import datetimeimport time# Page configurationst.set_page_config(page_title="Credit Score Predictor",page_icon="๐ณ",layout="wide",initial_sidebar_state="expanded")# Custom CSS for better stylingst.markdown("""<style>.card{font-size: 3rem;}.main-header {font-size: 3rem;font-weight: bold;text-align: center;background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);-webkit-background-clip: text;-webkit-text-fill-color: transparent;margin-bottom: 1rem;}.sub-header {text-align: center;color: #666;font-size: 1.2rem;margin-bottom: 2rem;}.metric-card {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);padding: 1rem;border-radius: 10px;color: white;text-align: center;margin: 0.5rem 0;}.stButton > button {background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);color: white;border: none;border-radius: 20px;padding: 0.5rem 2rem;font-weight: bold;width: 100%;}.prediction-good {background: linear-gradient(135deg, #4CAF50, #45a049);padding: 1rem;border-radius: 10px;color: white;text-align: center;font-size: 1.5rem;font-weight: bold;}.prediction-standard {background: linear-gradient(135deg, #FF9800, #F57C00);padding: 1rem;border-radius: 10px;color: white;text-align: center;font-size: 1.5rem;font-weight: bold;}.prediction-poor {background: linear-gradient(135deg, #F44336, #D32F2F);padding: 1rem;border-radius: 10px;color: white;text-align: center;font-size: 1.5rem;font-weight: bold;}</style>""", unsafe_allow_html=True)# Load the model (with error handling)@st.cache_resourcedef load_model():try:return joblib.load("best_catboost_model.pkl")except FileNotFoundError:st.error("โ ๏ธ Model file not found. Please ensure 'best_catboost_model.pkl' is in the correct directory.")return Nonemodel = load_model()# Categorical feature listcat_features = ['Occupation', 'Credit_Mix', 'Payment_of_Min_Amount','Payment_Behaviour', 'Type_of_Loan']# Headerst.markdown('<h1 class="main-header">Credit Score Predictor</h1>', unsafe_allow_html=True)st.markdown('<p class="sub-header">Get instant insights into your creditworthiness with our AI-powered predictor</p>', unsafe_allow_html=True)# Sidebar for quick infowith st.sidebar:st.markdown("### ๐ About Credit Scores")st.info("""**Good Credit (750+)**โ Best loan rates \nโ Easy approvals \nโ Premium credit cards \n**Standard Credit (650-749)**โ ๏ธ Moderate rates \nโ ๏ธ Standard approvals \n**Poor Credit (<650)**โ High interest rates \nโ Limited options \n""")st.markdown("### ๐ฏ Tips for Better Credit")st.success("""โข Pay bills on time \nโข Keep credit utilization low \nโข Maintain old accounts \nโข Monitor credit report \nโข Diversify credit types \n""")# Main content in tabstab1, tab2, tab3= st.tabs(["๐ Predict Credit Score", "๐ Factors Affecting Credit Score", "๐ก Recommendations"])with tab1:if model is None:st.stop()# Personal Information Sectionst.markdown("### ๐ค Personal Information")col1, col2, col3 = st.columns(3)with col1:name = st.text_input("๐ Full Name", placeholder="Enter your full name")age = st.slider("๐ Age", min_value=18, max_value=100, value=30)with col2:month = st.selectbox("๐ Month", range(1, 13), index=0)occupation = st.selectbox("๐ผ Occupation", ["Scientist", "Teacher", "Engineer", "Manager", "Doctor","Lawyer", "Architect", "Developer", "Accountant", "Other"])with col3:annual_income = st.number_input("๐ฐ Annual Income ($)", min_value=0.0, value=50000.0, step=1000.0)monthly_inhand_salary = st.number_input("๐ต Monthly Salary ($)", min_value=0.0, value=4000.0, step=100.0)st.divider()# Banking Information Sectionst.markdown("### ๐ฆ Banking & Credit Information")col4, col5, col6 = st.columns(3)with col4:num_bank_accounts = st.slider("๐ฆ Bank Accounts", min_value=0, max_value=20, value=3)num_credit_card = st.slider("๐ณ Credit Cards", min_value=0, max_value=20, value=2)interest_rate = st.slider("๐ Interest Rate (%)", min_value=0.0, max_value=50.0, value=12.0, step=0.1)with col5:num_of_loan = st.slider("๐ Number of Loans", min_value=0, max_value=20, value=2)type_of_loan = st.multiselect("๐ท๏ธ Loan Types", ["Auto Loan", "Personal Loan", "Home Loan", "Student Loan","Credit Card Loan", "Business Loan"], default=["Auto Loan", "Personal Loan"])# Convert multiselect to stringtype_of_loan_str = ", ".join(type_of_loan) if type_of_loan else "No Loan"with col6:credit_mix = st.selectbox("๐ฏ Credit Mix", ["Good", "Standard", "Poor"], index=0)payment_of_min_amount = st.selectbox("๐ธ Pay Minimum Amount", ["Yes", "No"], index=0)payment_behaviour = st.selectbox("๐ Payment Behaviour", ["High_spent_Small_value_payments","Low_spent_Large_value_payments","High_spent_Medium_value_payments","Low_spent_Medium_value_payments","High_spent_Large_value_payments","Low_spent_Small_value_payments"])st.divider()# Financial Details Sectionst.markdown("### ๐น Financial Details")col7, col8, col9 = st.columns(3)with col7:delay_from_due_date = st.slider("โฐ Days Late on Payments", min_value=0, max_value=60, value=5)num_of_delayed_payment = st.slider("โ ๏ธ Delayed Payments Count", min_value=0, max_value=50, value=3)changed_credit_limit = st.number_input("๐ Credit Limit Changes", value=500.0, step=100.0)with col8:num_credit_inquiries = st.slider("๐ Credit Inquiries", min_value=0, max_value=20, value=2)outstanding_debt = st.number_input("๐ณ Outstanding Debt ($)", min_value=0.0, value=1500.0, step=100.0)credit_utilization_ratio = st.slider("๐ Credit Utilization (%)", min_value=0.0, max_value=100.0, value=25.0, step=0.1)with col9:credit_history_age = st.slider("๐ Credit History (months)", min_value=0, max_value=600, value=200)total_emi_per_month = st.number_input("๐ฐ Monthly EMI ($)", min_value=0.0, value=200.0, step=50.0)amount_invested_monthly = st.number_input("๐ Monthly Investment ($)", min_value=0.0, value=100.0, step=25.0)monthly_balance = st.number_input("๐ต Monthly Balance ($)", value=800.0, step=100.0)st.divider()# Prediction Sectioncol_pred1, col_pred2, col_pred3 = st.columns([1, 2, 1])with col_pred2:if st.button("๐ฎ Predict My Credit Score", type="primary"):if not name:st.warning("โ ๏ธ Please enter your name to continue.")else:# Show loading animationwith st.spinner('๐ Analyzing your credit profile...'):time.sleep(2) # Simulate processing time# Prepare input DataFramedata = pd.DataFrame([{'Month': month,'Age': age,'Occupation': occupation,'Annual_Income': annual_income,'Monthly_Inhand_Salary': monthly_inhand_salary,'Num_Bank_Accounts': num_bank_accounts,'Num_Credit_Card': num_credit_card,'Interest_Rate': interest_rate,'Num_of_Loan': num_of_loan,'Type_of_Loan': type_of_loan_str,'Delay_from_due_date': delay_from_due_date,'Num_of_Delayed_Payment': num_of_delayed_payment,'Changed_Credit_Limit': changed_credit_limit,'Num_Credit_Inquiries': num_credit_inquiries,'Credit_Mix': credit_mix,'Outstanding_Debt': outstanding_debt,'Credit_Utilization_Ratio': credit_utilization_ratio,'Credit_History_Age': credit_history_age,'Payment_of_Min_Amount': payment_of_min_amount,'Total_EMI_per_month': total_emi_per_month,'Amount_invested_monthly': amount_invested_monthly,'Payment_Behaviour': payment_behaviour,'Monthly_Balance': monthly_balance}])# Make predictiontry:pool = Pool(data, cat_features=cat_features)prediction = model.predict(pool)result = prediction[0]# Display result with appropriate stylingif result == "Good":st.markdown(f'<div class="prediction-good">๐ Congratulations {name}!<br>Your Credit Score is: <strong>{result}</strong></div>', unsafe_allow_html=True)st.balloons()elif result == "Standard":st.markdown(f'<div class="prediction-standard">๐ Hi {name}!<br>Your Credit Score is: <strong>{result}</strong></div>', unsafe_allow_html=True)st.snow()else:st.markdown(f'<div class="prediction-poor">โก Hi {name}!<br>Your Credit Score is: <strong>{result}</strong><br>There\'s room for improvement!</div>', unsafe_allow_html=True)# Store result in session state for other tabsst.session_state.prediction = resultst.session_state.user_data = dataexcept Exception as e:st.error(f"โ An error occurred during prediction: {str(e)}")with tab2:# Credit factors impact# st.markdown("### ๐ฏ Factors Affecting Credit Score")factors = {'Type_of_Loan': 9.6518,'Occupation':8.4725,'Month ':6.2643,'Outstanding_Debt':5.8894,'Credit_Mix': 5.3340,'Changed_Credit_Limit':4.9477 ,'Delay_from_due_date':4.8124,'Credit_History_Age' :4.6812,'Age':4.6376,'Interest_Rate':4.5192}fig_bar = go.Figure([go.Bar(x=list(factors.keys()),y=list(factors.values()),marker_color=['#3a1c71', # darkest'#4a00e0','#6a11cb','#8e2de2','#764ba2','#764ba2','#2575fc','#667eea','#667eea','#667eea' # lightest])])fig_bar.update_layout(title="Credit Score Impact Factors",xaxis_title="Factors",yaxis_title="Impact Score",height=400)st.plotly_chart(fig_bar, use_container_width=True)with tab3:st.markdown("### ๐ก Personalized Recommendations")if 'prediction' in st.session_state:result = st.session_state.predictionif result == "Good":st.success("๐ **Excellent Credit Score!** Keep up the great work!")st.markdown("""**To maintain your excellent score:**- Continue paying all bills on time- Keep credit utilization below 30%- Don't close old credit accounts- Monitor your credit report regularly- Consider becoming an authorized user on family accounts""")elif result == "Standard":st.warning("๐ **Good Credit Score!** Here's how to improve:")st.markdown("""**Steps to reach 'Good' status:**- Set up automatic payments to avoid late fees- Pay down existing debt to improve utilization ratio- Don't apply for new credit cards frequently- Keep old accounts open to maintain credit history- Consider a secured credit card if needed""")else:st.error("โก **Credit Score Needs Improvement!** Don't worry, here's your action plan:")st.markdown("""**Priority actions to improve your score:**1. **Pay all bills on time** - This is the most important factor2. **Reduce credit card balances** - Aim for under 30% utilization3. **Don't close old accounts** - They help your credit history length4. **Check your credit report** - Look for errors and dispute them5. **Consider a secured credit card** - To build positive payment history6. **Pay more than the minimum** - Reduces debt faster""")else:st.info("๐ **Get your credit score prediction first to see personalized recommendations!**")st.markdown("""### General Credit Improvement Tips:**๐ฏ Quick Wins:**- Set up automatic bill payments- Pay credit cards twice per month- Request credit limit increases- Become an authorized user on family accounts**๐ Long-term Strategies:**- Diversify your credit mix (cards, loans, mortgage)- Keep old accounts open- Monitor credit reports monthly- Avoid hard inquiries when possible**๐จ Red Flags to Avoid:**- Missing payments (even by a day)- Maxing out credit cards- Closing old accounts- Co-signing loans carelessly""")# Footerst.divider()st.markdown("""<div style='text-align: center; color: #666; padding: 1rem;'><p>๐ณ <strong>Credit Score Predictor</strong> | Built with โค๏ธ using Streamlit & CatBoost</p><p><small>โ ๏ธ This is a predictive tool and should not be considered as financial advice.Consult with financial professionals for important credit decisions.</small></p></div>""", unsafe_allow_html=True)
src/streamlit_app.py+396-38