Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,90 +7,90 @@ from Gradio_UI import GradioUI
|
|
| 7 |
@tool
|
| 8 |
def investment_advisor(amount: int, risk_profile: str, age: int) -> str:
|
| 9 |
"""
|
| 10 |
-
|
| 11 |
|
| 12 |
Args:
|
| 13 |
-
amount (int):
|
| 14 |
-
risk_profile (str):
|
| 15 |
-
age (int):
|
| 16 |
|
| 17 |
Returns:
|
| 18 |
-
str:
|
| 19 |
"""
|
| 20 |
if amount <= 0:
|
| 21 |
-
return "
|
| 22 |
|
| 23 |
if age <= 0 or age > 120:
|
| 24 |
-
return "
|
| 25 |
|
| 26 |
-
#
|
| 27 |
risk_profile = risk_profile.lower().strip()
|
| 28 |
-
valid_profiles = ["
|
| 29 |
|
| 30 |
if risk_profile not in valid_profiles:
|
| 31 |
-
return "
|
| 32 |
|
| 33 |
-
#
|
| 34 |
israeli_funds = {
|
| 35 |
-
"
|
| 36 |
-
{"name": "KSM
|
| 37 |
-
{"name": "
|
| 38 |
-
{"name": "
|
| 39 |
-
{"name": "
|
| 40 |
],
|
| 41 |
-
"
|
| 42 |
-
{"name": "
|
| 43 |
-
{"name": "
|
| 44 |
-
{"name": "
|
| 45 |
-
{"name": "
|
| 46 |
],
|
| 47 |
-
"
|
| 48 |
-
{"name": "
|
| 49 |
-
{"name": "
|
| 50 |
-
{"name": "
|
| 51 |
-
{"name": "
|
| 52 |
]
|
| 53 |
}
|
| 54 |
|
| 55 |
-
#
|
| 56 |
def get_allocation(age, risk):
|
| 57 |
-
#
|
| 58 |
base_stocks = max(0, min(100, 120 - age))
|
| 59 |
|
| 60 |
-
if risk == "
|
| 61 |
stocks = max(0, base_stocks - 20)
|
| 62 |
-
elif risk == "
|
| 63 |
stocks = min(100, base_stocks + 20)
|
| 64 |
-
else: #
|
| 65 |
stocks = base_stocks
|
| 66 |
|
| 67 |
bonds = min(100 - stocks, 80)
|
| 68 |
cash = 100 - stocks - bonds
|
| 69 |
|
| 70 |
return {
|
| 71 |
-
"
|
| 72 |
-
"
|
| 73 |
-
"
|
| 74 |
}
|
| 75 |
|
| 76 |
-
#
|
| 77 |
allocation = get_allocation(age, risk_profile)
|
| 78 |
|
| 79 |
-
#
|
| 80 |
suitable_funds = []
|
| 81 |
funds_for_profile = israeli_funds[risk_profile]
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
stock_amount = amount * allocation["
|
| 85 |
-
bond_amount = amount * allocation["
|
| 86 |
-
cash_amount = amount * allocation["
|
| 87 |
|
| 88 |
-
#
|
| 89 |
-
stock_funds = [f for f in funds_for_profile if f["type"] in ["
|
| 90 |
-
bond_funds = [f for f in funds_for_profile if f["type"] in ["
|
| 91 |
-
cash_funds = [f for f in funds_for_profile if f["type"] in ["
|
| 92 |
|
| 93 |
-
#
|
| 94 |
recommendations = []
|
| 95 |
|
| 96 |
if stock_amount >= 1000 and stock_funds:
|
|
@@ -100,7 +100,7 @@ def investment_advisor(amount: int, risk_profile: str, age: int) -> str:
|
|
| 100 |
recommendations.append({
|
| 101 |
"fund": fund,
|
| 102 |
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 103 |
-
"asset_class": "
|
| 104 |
})
|
| 105 |
break
|
| 106 |
|
|
@@ -111,7 +111,7 @@ def investment_advisor(amount: int, risk_profile: str, age: int) -> str:
|
|
| 111 |
recommendations.append({
|
| 112 |
"fund": fund,
|
| 113 |
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 114 |
-
"asset_class": "
|
| 115 |
})
|
| 116 |
break
|
| 117 |
|
|
@@ -122,23 +122,23 @@ def investment_advisor(amount: int, risk_profile: str, age: int) -> str:
|
|
| 122 |
recommendations.append({
|
| 123 |
"fund": fund,
|
| 124 |
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 125 |
-
"asset_class": "
|
| 126 |
})
|
| 127 |
break
|
| 128 |
|
| 129 |
-
#
|
| 130 |
-
response = f"##
|
| 131 |
-
response += f"**
|
| 132 |
-
response += f"**
|
| 133 |
-
response += f"**
|
| 134 |
|
| 135 |
-
response += "###
|
| 136 |
-
response += f"-
|
| 137 |
-
response += f"-
|
| 138 |
-
response += f"-
|
| 139 |
|
| 140 |
if recommendations:
|
| 141 |
-
response += "###
|
| 142 |
total_invested = 0
|
| 143 |
|
| 144 |
for rec in recommendations:
|
|
@@ -147,22 +147,22 @@ def investment_advisor(amount: int, risk_profile: str, age: int) -> str:
|
|
| 147 |
total_invested += amount_to_invest
|
| 148 |
|
| 149 |
response += f"**{fund['name']}** ({fund['ticker']})\n"
|
| 150 |
-
response += f"-
|
| 151 |
-
response += f"-
|
| 152 |
-
response += f"-
|
| 153 |
-
response += f"-
|
| 154 |
|
| 155 |
remaining = amount - total_invested
|
| 156 |
if remaining > 0:
|
| 157 |
-
response += f"**
|
| 158 |
else:
|
| 159 |
-
response += "
|
| 160 |
|
| 161 |
-
response += "###
|
| 162 |
-
response += "-
|
| 163 |
-
response += "-
|
| 164 |
-
response += "-
|
| 165 |
-
response += "-
|
| 166 |
|
| 167 |
return response
|
| 168 |
|
|
@@ -175,32 +175,32 @@ model = HfApiModel(
|
|
| 175 |
model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
|
| 176 |
)
|
| 177 |
|
| 178 |
-
#
|
| 179 |
investment_prompt_templates = {
|
| 180 |
-
"react-system": """
|
| 181 |
-
|
| 182 |
|
| 183 |
{tools_string}
|
| 184 |
|
| 185 |
-
|
| 186 |
-
1.
|
| 187 |
-
2.
|
| 188 |
-
3.
|
| 189 |
|
| 190 |
-
|
| 191 |
|
| 192 |
-
|
| 193 |
```py
|
| 194 |
action = tool_name(arg1=value1, arg2=value2, ...)
|
| 195 |
```
|
| 196 |
|
| 197 |
-
|
| 198 |
""",
|
| 199 |
"react-human": "{input_string}",
|
| 200 |
"react-assistant": "{agent_response}",
|
| 201 |
}
|
| 202 |
|
| 203 |
-
#
|
| 204 |
try:
|
| 205 |
with open("prompts.yaml", 'r') as stream:
|
| 206 |
prompt_templates = yaml.safe_load(stream)
|
|
@@ -208,7 +208,7 @@ try:
|
|
| 208 |
except:
|
| 209 |
prompt_templates = investment_prompt_templates
|
| 210 |
|
| 211 |
-
#
|
| 212 |
agent = CodeAgent(
|
| 213 |
model=model,
|
| 214 |
tools=[final_answer, investment_advisor],
|
|
@@ -217,43 +217,43 @@ agent = CodeAgent(
|
|
| 217 |
prompt_templates=prompt_templates
|
| 218 |
)
|
| 219 |
|
| 220 |
-
#
|
| 221 |
class InvestmentAdvisorUI(GradioUI):
|
| 222 |
def launch(self, **kwargs):
|
| 223 |
import gradio as gr
|
| 224 |
|
| 225 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 226 |
-
gr.Markdown("#
|
| 227 |
-
gr.Markdown("
|
| 228 |
|
| 229 |
with gr.Row():
|
| 230 |
with gr.Column():
|
| 231 |
-
amount_input = gr.Number(label="
|
| 232 |
-
risk_input = gr.Radio(["
|
| 233 |
-
age_input = gr.Slider(minimum=18, maximum=100, step=1, label="
|
| 234 |
-
submit_btn = gr.Button("
|
| 235 |
|
| 236 |
with gr.Row():
|
| 237 |
with gr.Column():
|
| 238 |
-
recommendation_output = gr.Markdown(label="
|
| 239 |
|
| 240 |
def get_recommendations(amount, risk, age):
|
| 241 |
if not amount or amount < 100:
|
| 242 |
-
return "
|
| 243 |
if not risk:
|
| 244 |
-
return "
|
| 245 |
if not age or age < 18:
|
| 246 |
-
return "
|
| 247 |
|
| 248 |
try:
|
| 249 |
recommendations = investment_advisor(int(amount), risk.lower(), int(age))
|
| 250 |
return recommendations
|
| 251 |
except Exception as e:
|
| 252 |
-
return f"
|
| 253 |
|
| 254 |
submit_btn.click(get_recommendations, inputs=[amount_input, risk_input, age_input], outputs=recommendation_output)
|
| 255 |
|
| 256 |
demo.launch(**kwargs)
|
| 257 |
|
| 258 |
-
#
|
| 259 |
InvestmentAdvisorUI(agent).launch()
|
|
|
|
| 7 |
@tool
|
| 8 |
def investment_advisor(amount: int, risk_profile: str, age: int) -> str:
|
| 9 |
"""
|
| 10 |
+
Provides investment recommendations based on the amount in shekels, risk profile, and age.
|
| 11 |
|
| 12 |
Args:
|
| 13 |
+
amount (int): Amount to invest in shekels
|
| 14 |
+
risk_profile (str): Risk profile (low, medium, high)
|
| 15 |
+
age (int): Age of the investor
|
| 16 |
|
| 17 |
Returns:
|
| 18 |
+
str: Investment recommendations
|
| 19 |
"""
|
| 20 |
if amount <= 0:
|
| 21 |
+
return "Error: Investment amount must be a positive number."
|
| 22 |
|
| 23 |
if age <= 0 or age > 120:
|
| 24 |
+
return "Error: Please provide a valid age."
|
| 25 |
|
| 26 |
+
# Normalize risk profile
|
| 27 |
risk_profile = risk_profile.lower().strip()
|
| 28 |
+
valid_profiles = ["low", "medium", "high"]
|
| 29 |
|
| 30 |
if risk_profile not in valid_profiles:
|
| 31 |
+
return "Error: Risk profile must be 'low', 'medium', or 'high'."
|
| 32 |
|
| 33 |
+
# Database of Israeli funds (ETFs and mutual funds)
|
| 34 |
israeli_funds = {
|
| 35 |
+
"low": [
|
| 36 |
+
{"name": "KSM Tel Bond 20", "ticker": "TELBOND20", "type": "Bonds", "risk": "Low", "min_investment": 1000, "description": "ETF tracking Tel Aviv corporate bond index"},
|
| 37 |
+
{"name": "Psagot Government Shekel Bonds", "ticker": "PSAGOT-GOV", "type": "Gov Bonds", "risk": "Low", "min_investment": 500, "description": "Israeli government bonds fund"},
|
| 38 |
+
{"name": "Migdal Foreign Currency", "ticker": "MIGDAL-FOREX", "type": "Currency", "risk": "Low-medium", "min_investment": 1000, "description": "Fund investing in foreign currency and money market instruments"},
|
| 39 |
+
{"name": "Harel Deposits Basket", "ticker": "HAREL-PIKADON", "type": "Deposits", "risk": "Very low", "min_investment": 500, "description": "Fixed income bank deposits fund"}
|
| 40 |
],
|
| 41 |
+
"medium": [
|
| 42 |
+
{"name": "Tachlit Tel Aviv 35", "ticker": "TA35ETF", "type": "Index", "risk": "Medium", "min_investment": 1000, "description": "ETF tracking the 35 largest companies on the Tel Aviv Stock Exchange"},
|
| 43 |
+
{"name": "Meitav Dash 50/50", "ticker": "MEITAV-50", "type": "Mixed", "risk": "Medium", "min_investment": 2000, "description": "Balanced fund with 50% stocks and 50% bonds"},
|
| 44 |
+
{"name": "Altshuler Shaham Global", "ticker": "ALTSHULER-GLOBAL", "type": "Global", "risk": "Medium", "min_investment": 5000, "description": "Fund with diversified global investments"},
|
| 45 |
+
{"name": "Analyst Corporate AA and Above", "ticker": "ANALYST-AA", "type": "Corp Bonds", "risk": "Medium", "min_investment": 2000, "description": "High-quality corporate bonds fund with AA rating and above"}
|
| 46 |
],
|
| 47 |
+
"high": [
|
| 48 |
+
{"name": "Tachlit NASDAQ 100", "ticker": "TACHLIT-NDX", "type": "Technology", "risk": "High", "min_investment": 3000, "description": "ETF tracking the NASDAQ 100 index of largest non-financial companies"},
|
| 49 |
+
{"name": "KSM S&P 500", "ticker": "KSM-SP500", "type": "US", "risk": "High", "min_investment": 3000, "description": "ETF tracking the S&P 500 index"},
|
| 50 |
+
{"name": "Mor Technologies", "ticker": "MOR-TECH", "type": "Sector", "risk": "Very high", "min_investment": 5000, "description": "Fund of Israeli technology companies"},
|
| 51 |
+
{"name": "Harel Foreign Stocks", "ticker": "HAREL-GLOBAL", "type": "International", "risk": "High", "min_investment": 5000, "description": "Fund of international stocks with high growth potential"}
|
| 52 |
]
|
| 53 |
}
|
| 54 |
|
| 55 |
+
# Asset allocation based on age and risk
|
| 56 |
def get_allocation(age, risk):
|
| 57 |
+
# Basic rule: 120 - age = % stocks (for medium risk)
|
| 58 |
base_stocks = max(0, min(100, 120 - age))
|
| 59 |
|
| 60 |
+
if risk == "low":
|
| 61 |
stocks = max(0, base_stocks - 20)
|
| 62 |
+
elif risk == "high":
|
| 63 |
stocks = min(100, base_stocks + 20)
|
| 64 |
+
else: # medium risk
|
| 65 |
stocks = base_stocks
|
| 66 |
|
| 67 |
bonds = min(100 - stocks, 80)
|
| 68 |
cash = 100 - stocks - bonds
|
| 69 |
|
| 70 |
return {
|
| 71 |
+
"stocks": stocks,
|
| 72 |
+
"bonds": bonds,
|
| 73 |
+
"cash": cash
|
| 74 |
}
|
| 75 |
|
| 76 |
+
# Get asset allocation
|
| 77 |
allocation = get_allocation(age, risk_profile)
|
| 78 |
|
| 79 |
+
# Find suitable funds based on available amount and allocation
|
| 80 |
suitable_funds = []
|
| 81 |
funds_for_profile = israeli_funds[risk_profile]
|
| 82 |
|
| 83 |
+
# Distribute amount by asset class
|
| 84 |
+
stock_amount = amount * allocation["stocks"] / 100
|
| 85 |
+
bond_amount = amount * allocation["bonds"] / 100
|
| 86 |
+
cash_amount = amount * allocation["cash"] / 100
|
| 87 |
|
| 88 |
+
# Fund recommendations
|
| 89 |
+
stock_funds = [f for f in funds_for_profile if f["type"] in ["Index", "Technology", "US", "International", "Sector"]]
|
| 90 |
+
bond_funds = [f for f in funds_for_profile if f["type"] in ["Bonds", "Gov Bonds", "Corp Bonds"]]
|
| 91 |
+
cash_funds = [f for f in funds_for_profile if f["type"] in ["Deposits", "Currency"]]
|
| 92 |
|
| 93 |
+
# Build recommendations
|
| 94 |
recommendations = []
|
| 95 |
|
| 96 |
if stock_amount >= 1000 and stock_funds:
|
|
|
|
| 100 |
recommendations.append({
|
| 101 |
"fund": fund,
|
| 102 |
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 103 |
+
"asset_class": "Stocks"
|
| 104 |
})
|
| 105 |
break
|
| 106 |
|
|
|
|
| 111 |
recommendations.append({
|
| 112 |
"fund": fund,
|
| 113 |
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 114 |
+
"asset_class": "Bonds"
|
| 115 |
})
|
| 116 |
break
|
| 117 |
|
|
|
|
| 122 |
recommendations.append({
|
| 123 |
"fund": fund,
|
| 124 |
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 125 |
+
"asset_class": "Cash"
|
| 126 |
})
|
| 127 |
break
|
| 128 |
|
| 129 |
+
# Format response
|
| 130 |
+
response = f"## Investment Recommendations\n\n"
|
| 131 |
+
response += f"**Amount:** {amount:,} ₪\n"
|
| 132 |
+
response += f"**Age:** {age} years\n"
|
| 133 |
+
response += f"**Risk Profile:** {risk_profile.capitalize()}\n\n"
|
| 134 |
|
| 135 |
+
response += "### Recommended Asset Allocation\n"
|
| 136 |
+
response += f"- Stocks: {allocation['stocks']}% ({int(stock_amount):,} ₪)\n"
|
| 137 |
+
response += f"- Bonds: {allocation['bonds']}% ({int(bond_amount):,} ₪)\n"
|
| 138 |
+
response += f"- Cash: {allocation['cash']}% ({int(cash_amount):,} ₪)\n\n"
|
| 139 |
|
| 140 |
if recommendations:
|
| 141 |
+
response += "### Recommended Investments\n\n"
|
| 142 |
total_invested = 0
|
| 143 |
|
| 144 |
for rec in recommendations:
|
|
|
|
| 147 |
total_invested += amount_to_invest
|
| 148 |
|
| 149 |
response += f"**{fund['name']}** ({fund['ticker']})\n"
|
| 150 |
+
response += f"- Type: {fund['type']} ({rec['asset_class']})\n"
|
| 151 |
+
response += f"- Risk: {fund['risk']}\n"
|
| 152 |
+
response += f"- Recommended amount: {amount_to_invest:,} ₪\n"
|
| 153 |
+
response += f"- Description: {fund['description']}\n\n"
|
| 154 |
|
| 155 |
remaining = amount - total_invested
|
| 156 |
if remaining > 0:
|
| 157 |
+
response += f"**Remaining funds:** {remaining:,} ₪ recommended to keep in a savings account for unexpected expenses.\n\n"
|
| 158 |
else:
|
| 159 |
+
response += "Unfortunately, we cannot provide specific fund recommendations for the specified amount. Consider savings accounts or increasing your investment amount.\n\n"
|
| 160 |
|
| 161 |
+
response += "### Important Information\n"
|
| 162 |
+
response += "- These are general recommendations based on the information provided.\n"
|
| 163 |
+
response += "- Before investing, it is recommended to consult with a licensed financial advisor.\n"
|
| 164 |
+
response += "- Past performance does not guarantee future returns.\n"
|
| 165 |
+
response += "- Investments involve risks, including possible loss of principal.\n"
|
| 166 |
|
| 167 |
return response
|
| 168 |
|
|
|
|
| 175 |
model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
|
| 176 |
)
|
| 177 |
|
| 178 |
+
# Configure templates for the investment advisor
|
| 179 |
investment_prompt_templates = {
|
| 180 |
+
"react-system": """You are an investment advisor who helps users make informed investment decisions in the Israeli market.
|
| 181 |
+
You have access to the following tools:
|
| 182 |
|
| 183 |
{tools_string}
|
| 184 |
|
| 185 |
+
You should help the user determine where to invest their funds in shekels based on:
|
| 186 |
+
1. The amount in shekels the user is willing to invest
|
| 187 |
+
2. The user's risk profile (low, medium, or high)
|
| 188 |
+
3. The user's age
|
| 189 |
|
| 190 |
+
Use the investment_advisor tool to analyze these factors and formulate investment recommendations.
|
| 191 |
|
| 192 |
+
To use a tool, output an action in this format:
|
| 193 |
```py
|
| 194 |
action = tool_name(arg1=value1, arg2=value2, ...)
|
| 195 |
```
|
| 196 |
|
| 197 |
+
Always use Python syntax for calling tools. After using a tool, analyze the result to determine what to do next. Use final_answer to return your final answer.
|
| 198 |
""",
|
| 199 |
"react-human": "{input_string}",
|
| 200 |
"react-assistant": "{agent_response}",
|
| 201 |
}
|
| 202 |
|
| 203 |
+
# Load prompt templates from file or use our templates
|
| 204 |
try:
|
| 205 |
with open("prompts.yaml", 'r') as stream:
|
| 206 |
prompt_templates = yaml.safe_load(stream)
|
|
|
|
| 208 |
except:
|
| 209 |
prompt_templates = investment_prompt_templates
|
| 210 |
|
| 211 |
+
# Create the agent
|
| 212 |
agent = CodeAgent(
|
| 213 |
model=model,
|
| 214 |
tools=[final_answer, investment_advisor],
|
|
|
|
| 217 |
prompt_templates=prompt_templates
|
| 218 |
)
|
| 219 |
|
| 220 |
+
# Create a custom Gradio UI
|
| 221 |
class InvestmentAdvisorUI(GradioUI):
|
| 222 |
def launch(self, **kwargs):
|
| 223 |
import gradio as gr
|
| 224 |
|
| 225 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 226 |
+
gr.Markdown("# Investment Advisor for the Israeli Market")
|
| 227 |
+
gr.Markdown("Get personalized investment recommendations based on your profile")
|
| 228 |
|
| 229 |
with gr.Row():
|
| 230 |
with gr.Column():
|
| 231 |
+
amount_input = gr.Number(label="Amount to invest (in shekels)", minimum=100)
|
| 232 |
+
risk_input = gr.Radio(["Low", "Medium", "High"], label="Risk Profile")
|
| 233 |
+
age_input = gr.Slider(minimum=18, maximum=100, step=1, label="Your Age")
|
| 234 |
+
submit_btn = gr.Button("Get Recommendations", variant="primary")
|
| 235 |
|
| 236 |
with gr.Row():
|
| 237 |
with gr.Column():
|
| 238 |
+
recommendation_output = gr.Markdown(label="Investment Recommendations")
|
| 239 |
|
| 240 |
def get_recommendations(amount, risk, age):
|
| 241 |
if not amount or amount < 100:
|
| 242 |
+
return "Please enter an amount of at least 100 shekels."
|
| 243 |
if not risk:
|
| 244 |
+
return "Please select a risk profile."
|
| 245 |
if not age or age < 18:
|
| 246 |
+
return "Please provide a valid age (18 years or older)."
|
| 247 |
|
| 248 |
try:
|
| 249 |
recommendations = investment_advisor(int(amount), risk.lower(), int(age))
|
| 250 |
return recommendations
|
| 251 |
except Exception as e:
|
| 252 |
+
return f"Error generating recommendations: {str(e)}"
|
| 253 |
|
| 254 |
submit_btn.click(get_recommendations, inputs=[amount_input, risk_input, age_input], outputs=recommendation_output)
|
| 255 |
|
| 256 |
demo.launch(**kwargs)
|
| 257 |
|
| 258 |
+
# Launch the interface
|
| 259 |
InvestmentAdvisorUI(agent).launch()
|