hagar-sayed/risk_tolerance
0
1'''from flask import Flask, request, render_template, jsonify2import numpy as np3import pandas as pd4import joblib5 6# Thresholds for categorizing risk tolerance7threshold_low = 33.38threshold_high = 66.69 10# Function to categorize risk11def categorize(value):12 if value <= threshold_low:13 return 'Low'14 elif value > threshold_low and value <= threshold_high:15 return 'Medium'16 else:17 return 'High'18 19app = Flask(__name__)20 21# Load your trained model22model = joblib.load("risk_tolerance.joblib")23# Feature names based on your training data24feature_names = [25 'age', 'education_level', 'married_state', 'no_of_kids', 'life_statge',26 'occupational_category', 'income', 'risk', 'eager'27]28 29@app.route('/')30def home():31 return render_template("index.html")32 33@app.route('/predict', methods=['POST'])34def predict():35 try:36 # Extract features from form37 features = [float(request.form[feature]) for feature in feature_names]38 # Convert features to a DataFrame with proper feature names39 features_df = pd.DataFrame([features], columns=feature_names)40 # Make prediction41 prediction = model.predict(features_df)42 # Render the prediction result on the web page43 return render_template("index.html", prediction_text=f'Your Risk Tolerance is {categorize(prediction[0])}')44 except Exception as e:45 return jsonify({'error': str(e)})46 47@app.route('/api/predict', methods=['GET','POST'])48def api_predict():49 try:50 # Extract features from JSON request51 data = request.json52 features = [float(data[feature]) for feature in feature_names]53 # Convert features to a DataFrame with proper feature names54 features_df = pd.DataFrame([features], columns=feature_names)55 # Make prediction56 prediction = model.predict(features_df)57 # Return prediction as JSON58 return jsonify({'Your risk tolerance is ': categorize(prediction[0])})59 except Exception as e:60 return jsonify({'error': str(e)})61 62if __name__ == '__main__':63 app.run(debug=True)64'''65import streamlit as st66import requests67 68st.title("The first step to start your $park 💰")69 70st.markdown('''**Description**71 72- Identify your risk tolerance based on various personal and financial factors.\n73- This tool helps you determine your risk tolerance based on a variety of personal and financial factors.\n 74- By providing information such as your age, education level, marital status, number of kids, life stage, occupational category, income, and your risk and eagerness levels, you can receive an assessment of your risk tolerance.\n 75- This can help you make informed decisions about your financial investments and risk management strategies.76''')77 78# Input fields79age = st.number_input("Age", min_value=0, max_value=100, value=25)80education_level = st.slider("Education Level: 1 (Primary), 2 (Preparatory), 3 (High School), 4 (College Degree)", min_value=1, max_value=4, value=4)81married_state = st.slider("Marital Status: 1 (Married), 2 (Unmarried)", min_value=1, max_value=2, value=2)82no_of_kids = st.number_input("Number of Kids", min_value=0, max_value=10, value=0)83life_statge = st.slider("Life Stage: 1 (<=35), 2 (35-44), 3 (45-54), 4 (55-64), 5 (65-74), 6 (>=75)", min_value=1, max_value=6, value=1)84occupational_category = st.slider("Occupational Category: 1 (Managerial), 2 (Professional), 3 (Skilled), 4 (Unemployed)", min_value=1, max_value=4, value=1)85income = st.number_input("Income", min_value=0.0, max_value=1e6, value=50000.0)86risk = st.slider("Risk Level: 1 (Highest), 4 (Lowest)", min_value=1, max_value=4, value=2)87eager = st.slider("Eagerness: 0 (Not Eager), 1 (Eager)", min_value=0, max_value=1, value=1)88 89if st.button("Predict Risk Tolerance"):90 url = "http://127.0.0.1:5000"91 data = {92 "age": age,93 "education_level": education_level,94 "married_state": married_state,95 "no_of_kids": no_of_kids,96 "life_statge": life_statge,97 "occupational_category": occupational_category,98 "income": income,99 "risk": risk,100 "eager": eager101 }102 response = requests.post(url, json=data)103 if response.status_code == 200:104 result = response.json()105 st.success(f'Your risk tolerance is {result["risk_tolerance"]}')106 else:107 st.error("Error: Could not get the prediction.")108 109st.markdown('''**Definitions**:110 111- **Low Risk Tolerance**: You prefer to play it safe with your investments, opting for stability and lower risk options even if it means lower potential returns.\n112- **Medium Risk Tolerance**: You are willing to take on some risk in exchange for the potential of higher returns, balancing between conservative and aggressive investment strategies.\n113- **High Risk Tolerance**: You are comfortable with taking on higher levels of risk for the chance of significant returns, understanding that this comes with the possibility of greater losses.\n114''')115 