vvaibhav's picture
Update app.py
1d5b76a verified
# app.py
import gradio as gr
import openai
import os
# Ensure you have set your OpenAI API key as an environment variable
# Example: export OPENAI_API_KEY='your-api-key-here'
openai.api_key = os.getenv("API_KEY")
openai.api_base = "https://openai.vocareum.com/v1"
def generate_investment_recommendation(age, income, investment_amount, risk_tolerance, investment_horizon, financial_goals):
"""
Generates personalized investment recommendations based on user inputs.
Args:
age (int): User's age.
income (float): Annual income in USD.
investment_amount (float): Amount to invest in USD.
risk_tolerance (str): User's risk tolerance ('Low', 'Medium', 'High').
investment_horizon (str): Investment horizon ('Short-term', 'Mid-term', 'Long-term').
financial_goals (str): User's financial goals (e.g., 'Retirement', 'Education').
Returns:
str: AI-generated investment recommendations.
"""
try:
# Construct the prompt for the AI model
prompt = f"""
I am {age} years old with an annual income of ${income}. I want to invest ${investment_amount}.
My risk tolerance is {risk_tolerance}, and my investment horizon is {investment_horizon}.
My primary financial goals are: {financial_goals}.
Based on this information, please provide a personalized investment recommendation, including:
1. Portfolio Allocation (percentage in stocks, bonds, ETFs, etc.)
2. Suggested Investment Vehicles
3. Risk Management Strategies
4. Expected Returns
5. Diversification Tips
"""
# Call OpenAI's GPT model to generate the recommendation
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a financial advisor."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7,
n=1,
stop=None
)
recommendation = response.choices[0].message['content'].strip()
return recommendation
except Exception as e:
return f"An error occurred while generating the recommendation: {str(e)}"
# Define Gradio interface
def app_interface():
with gr.Blocks() as demo:
gr.Markdown("# Personalized Investment Recommendation Engine")
gr.Markdown(
"""
**Enter your financial details below to receive personalized investment recommendations.**
"""
)
with gr.Row():
with gr.Column():
age = gr.Number(label="Age", value=30, precision=0)
income = gr.Number(label="Annual Income (USD)", value=60000)
investment_amount = gr.Number(label="Investment Amount (USD)", value=10000)
risk_tolerance = gr.Radio(
label="Risk Tolerance",
choices=["Low", "Medium", "High"],
value="Medium"
)
investment_horizon = gr.Radio(
label="Investment Horizon",
choices=["Short-term (1-3 years)", "Mid-term (3-7 years)", "Long-term (7+ years)"],
value="Long-term (7+ years)"
)
financial_goals = gr.Textbox(
label="Financial Goals",
placeholder="e.g., Retirement, Education, Wealth Accumulation",
lines=2
)
submit = gr.Button("Get Recommendation")
with gr.Column():
output = gr.Textbox(label="Investment Recommendation", lines=20)
submit.click(
fn=generate_investment_recommendation,
inputs=[age, income, investment_amount, risk_tolerance, investment_horizon, financial_goals],
outputs=output
)
gr.Markdown(
"""
**Instructions:**
1. **Age:** Enter your current age.
2. **Annual Income:** Enter your total annual income in USD.
3. **Investment Amount:** Specify the amount you wish to invest.
4. **Risk Tolerance:** Select your comfort level with investment risks.
5. **Investment Horizon:** Choose the timeframe for your investments.
6. **Financial Goals:** Describe your primary financial objectives.
Click on the "Get Recommendation" button to receive tailored investment strategies.
"""
)
demo.launch()
if __name__ == "__main__":
app_interface()