Fin_Agent_App.py

#1
by Iman1 - opened
Files changed (1) hide show
  1. app.py +76 -14
app.py CHANGED
@@ -1,11 +1,18 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
-
8
  from Gradio_UI import GradioUI
 
 
 
 
 
 
 
 
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
@@ -19,19 +26,66 @@ def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return
19
  return "What magic will you build ?"
20
 
21
  @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
 
 
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
  """
27
  try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
36
 
37
  final_answer = FinalAnswerTool()
@@ -46,6 +100,10 @@ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may
46
  custom_role_conversions=None,
47
  )
48
 
 
 
 
 
49
 
50
  # Import tool from Hub
51
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
@@ -53,15 +111,19 @@ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_co
53
  with open("prompts.yaml", 'r') as stream:
54
  prompt_templates = yaml.safe_load(stream)
55
 
 
 
 
 
56
  agent = CodeAgent(
57
  model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
  max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
62
  planning_interval=None,
63
- name=None,
64
- description=None,
65
  prompt_templates=prompt_templates
66
  )
67
 
 
1
+ from smolagents import CodeAgent, HfApiModel, tool, load_tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
 
7
  from Gradio_UI import GradioUI
8
+ from bs4 import BeautifulSoup
9
+
10
+ # ---------------------------------------------------------------------------
11
+ # Define a custom tool for investment advice.
12
+ # This tool fetches the top 5 headlines from Yahoo Finance,
13
+ # does a simple sentiment analysis by counting positive and negative words,
14
+ # and then provides advice based on the provided risk tolerance.
15
+ # ---------------------------------------------------------------------------
16
 
17
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
18
  @tool
 
26
  return "What magic will you build ?"
27
 
28
  @tool
29
+ def investment_advice_tool(risk_tolerance: str) -> str:
30
+ """
31
+ Provides investment advice based on current market sentiment and the investor's risk tolerance.
32
+
33
  Args:
34
+ risk_tolerance: A string representing risk tolerance ('low', 'medium', or 'high').
35
  """
36
  try:
37
+ # Fetch market news from Yahoo Finance
38
+ url = "https://finance.yahoo.com/"
39
+ response = requests.get(url)
40
+ if response.status_code != 200:
41
+ return f"Error fetching market news: HTTP {response.status_code}"
42
+
43
+ # Parse the top headlines using BeautifulSoup
44
+ soup = BeautifulSoup(response.text, "html.parser")
45
+ headlines = soup.find_all("h3", limit=5)
46
+ news = [headline.get_text() for headline in headlines]
47
+
48
+ # Perform a simple sentiment analysis based on keywords
49
+ positive_words = ["rise", "gain", "growth", "bullish", "record high"]
50
+ negative_words = ["fall", "loss", "drop", "bearish", "recession"]
51
+ sentiment_score = 0
52
+ for article in news:
53
+ for word in positive_words:
54
+ if word in article.lower():
55
+ sentiment_score += 1
56
+ for word in negative_words:
57
+ if word in article.lower():
58
+ sentiment_score -= 1
59
+ sentiment = "Bullish" if sentiment_score > 0 else "Bearish" if sentiment_score < 0 else "Neutral"
60
+
61
+ # Provide advice based on risk tolerance and market sentiment
62
+ if risk_tolerance.lower() == "low":
63
+ if sentiment == "Bullish":
64
+ advice = "Invest in stable index funds or blue-chip stocks for steady growth."
65
+ elif sentiment == "Bearish":
66
+ advice = "Consider bonds or fixed-income securities to minimize risk."
67
+ else:
68
+ advice = "Maintain a diversified portfolio focused on stability."
69
+ elif risk_tolerance.lower() == "medium":
70
+ if sentiment == "Bullish":
71
+ advice = "Consider a balanced mix of growth stocks and dividend-paying stocks."
72
+ elif sentiment == "Bearish":
73
+ advice = "Look for undervalued defensive stocks and ETFs."
74
+ else:
75
+ advice = "A balanced portfolio combining growth and value stocks would be wise."
76
+ elif risk_tolerance.lower() == "high":
77
+ if sentiment == "Bullish":
78
+ advice = "Explore high-growth sectors like tech or emerging markets for potentially high returns."
79
+ elif sentiment == "Bearish":
80
+ advice = "Adopt a cautious approach, perhaps allocating only a small portion to speculative investments."
81
+ else:
82
+ advice = "A portfolio with a mix of high-risk and stable investments might suit you."
83
+ else:
84
+ advice = "Invalid risk tolerance. Please choose 'low', 'medium', or 'high'."
85
+
86
+ return f"Market sentiment is {sentiment}. Based on your {risk_tolerance} risk tolerance, {advice}"
87
  except Exception as e:
88
+ return f"Error in investment advice tool: {str(e)}"
89
 
90
 
91
  final_answer = FinalAnswerTool()
 
100
  custom_role_conversions=None,
101
  )
102
 
103
+ # ---------------------------------------------------------------------------
104
+ # Load prompt templates from the prompts.yaml file.
105
+ # This file guides how the agent constructs prompts for the LLM.
106
+ # ---------------------------------------------------------------------------
107
 
108
  # Import tool from Hub
109
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
111
  with open("prompts.yaml", 'r') as stream:
112
  prompt_templates = yaml.safe_load(stream)
113
 
114
+ # ---------------------------------------------------------------------------
115
+ # Create the Financial Advisor Agent.
116
+ # We add our investment advice tool to the agent's tools list.
117
+ # ---------------------------------------------------------------------------
118
  agent = CodeAgent(
119
  model=model,
120
+ tools=[final_answer, investment_advice_tool], # Add your custom financial tool here
121
  max_steps=6,
122
  verbosity_level=1,
123
  grammar=None,
124
  planning_interval=None,
125
+ name="Financial Advisor Agent",
126
+ description="An agent that provides investment suggestions based on current market sentiment and your risk tolerance.",
127
  prompt_templates=prompt_templates
128
  )
129