Arcpolar commited on
Commit
0cd59d5
·
verified ·
1 Parent(s): 05e2dfb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -16
app.py CHANGED
@@ -52,34 +52,37 @@ import re
52
 
53
  @tool
54
  def stock_price(symbol: str) -> str:
55
- """A tool that retrieves the current stock price for a given stock symbol using DuckDuckGo search.
56
  Args:
57
  symbol: The ticker symbol of the stock (e.g., AAPL for Apple Inc.).
58
  Returns:
59
  A summary indicating the current price of the stock or an error message if unavailable.
60
  """
61
  try:
62
- # Instantiate the DuckDuckGo search tool (ensure it's implemented or installed in your environment)
63
- search_tool = DuckDuckGoSearchTool(max_results=5)
64
- query = f"{symbol} current stock price"
 
65
 
66
- # Fetch search results for the query
67
- results = search_tool.forward(query)
68
 
69
- # Use a simple regex to attempt extraction of a stock price (e.g., $123.45)
70
- # Note: This regex is basic and may need adjustments for more robust extraction.
71
- match = re.search(r"\$?(\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)", results)
72
- if match:
73
- # Clean the extracted string and convert to a float
74
- price_str = match.group(1).replace(",", "")
75
- price = float(price_str)
76
- return f"The current price for {symbol} is ${price:.2f}."
77
- else:
78
- return f"Could not extract the current price for {symbol} from search results."
 
79
  except Exception as e:
80
  return f"An error occurred while retrieving the stock price for {symbol}: {e}"
81
 
82
 
 
83
  @tool
84
  def get_current_time_in_timezone(timezone: str) -> str:
85
  """A tool that fetches the current local time in a specified timezone.
 
52
 
53
  @tool
54
  def stock_price(symbol: str) -> str:
55
+ """A tool that retrieves the current stock price for a given stock symbol.
56
  Args:
57
  symbol: The ticker symbol of the stock (e.g., AAPL for Apple Inc.).
58
  Returns:
59
  A summary indicating the current price of the stock or an error message if unavailable.
60
  """
61
  try:
62
+ import yfinance as yf
63
+
64
+ # Initialize the ticker for the given symbol
65
+ ticker = yf.Ticker(symbol)
66
 
67
+ # Try to get the current price from the ticker info
68
+ price = ticker.info.get("currentPrice")
69
 
70
+ # Fallback: if 'currentPrice' is not available, get the last closing price
71
+ if price is None:
72
+ history = ticker.history(period="1d")
73
+ if not history.empty:
74
+ price = history["Close"].iloc[-1]
75
+ else:
76
+ return f"Could not retrieve the current price for {symbol}. Please verify the ticker symbol."
77
+
78
+ # Return the current price in a formatted string
79
+ return f"The current price for {symbol} is ${price:.2f}."
80
+
81
  except Exception as e:
82
  return f"An error occurred while retrieving the stock price for {symbol}: {e}"
83
 
84
 
85
+
86
  @tool
87
  def get_current_time_in_timezone(timezone: str) -> str:
88
  """A tool that fetches the current local time in a specified timezone.