Bshraman commited on
Commit
cd89fc0
·
verified ·
1 Parent(s): 649da4a

Update app.py

Browse files

Tool added get_current_stock_price

Files changed (1) hide show
  1. app.py +43 -4
app.py CHANGED
@@ -3,7 +3,6 @@ import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
- from tools.final_answer import FinalAnswerTool
7
  from tools.stock_price_tool import StockPriceTool
8
  import yfinance as yf
9
  from typing import Any, Optional
@@ -40,8 +39,49 @@ def get_current_time_in_timezone(timezone: str) -> str:
40
  except Exception as e:
41
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  final_answer = FinalAnswerTool()
44
- stock_price_tool = StockPriceTool()
45
 
46
  # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
47
  # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
@@ -53,7 +93,6 @@ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may
53
  custom_role_conversions=None,
54
  )
55
 
56
-
57
  # Import tool from Hub
58
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
59
 
@@ -62,7 +101,7 @@ with open("prompts.yaml", 'r') as stream:
62
 
63
  agent = CodeAgent(
64
  model=model,
65
- tools=[stock_price_tool], ## add your tools here (don't remove final answer)
66
  max_steps=6,
67
  verbosity_level=1,
68
  grammar=None,
 
3
  import requests
4
  import pytz
5
  import yaml
 
6
  from tools.stock_price_tool import StockPriceTool
7
  import yfinance as yf
8
  from typing import Any, Optional
 
39
  except Exception as e:
40
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
41
 
42
+ @tool
43
+ def get_current_stock_price(ticker_symbol: str) -> Optional[dict]:
44
+ """
45
+ Fetches the latest stock price for the given ticker symbol and calculates
46
+ the price change over the last 5 days.
47
+
48
+ Args:
49
+ ticker_symbol: The stock ticker symbol to fetch the price for.
50
+
51
+ Returns:
52
+ dict: A dictionary containing the current stock price, the price change
53
+ over the last 5 days, and the percentage change.
54
+ Returns None if there's an error or no data is available.
55
+ """
56
+ try:
57
+ # Fetch stock data
58
+ stock = yf.Ticker(ticker_symbol)
59
+ stock_data = stock.history(period="5d") # Fetch data for the last 5 days
60
+
61
+ if stock_data.empty:
62
+ return {"error": f"No historical data available for {ticker_symbol}"}
63
+
64
+ # Get the current price (last close price)
65
+ current_price = stock_data['Close'].iloc[-1]
66
+
67
+ # Calculate the price change over the last 5 days
68
+ price_change = current_price - stock_data['Close'].iloc[0]
69
+ price_change_percent = (price_change / stock_data['Close'].iloc[0]) * 100
70
+
71
+ # Round all values to 2 decimal places
72
+ return {
73
+ "price": round(current_price, 2),
74
+ "price_change": round(price_change, 2),
75
+ "price_change_percent": round(price_change_percent, 2)
76
+ }
77
+
78
+ except yf.exceptions.YFinanceException as yf_err:
79
+ logger.error(f"YFinance error for {ticker_symbol}: {str(yf_err)}")
80
+ except Exception as e:
81
+ logger.error(f"Unexpected error fetching price for {ticker_symbol}: {str(e)}")
82
+ return None
83
+
84
  final_answer = FinalAnswerTool()
 
85
 
86
  # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
87
  # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
 
93
  custom_role_conversions=None,
94
  )
95
 
 
96
  # Import tool from Hub
97
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
98
 
 
101
 
102
  agent = CodeAgent(
103
  model=model,
104
+ tools=[get_current_stock_price], ## add your tools here (don't remove final answer)
105
  max_steps=6,
106
  verbosity_level=1,
107
  grammar=None,