Spaces:
Sleeping
Sleeping
Create stock_price_tool.py
Browse files- tools/stock_price_tool.py +45 -0
tools/stock_price_tool.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from smolagents.tools import Tool
|
| 3 |
+
import yfinance as yf
|
| 4 |
+
|
| 5 |
+
class StockPriceTool(Tool):
|
| 6 |
+
"""
|
| 7 |
+
A tool that fetches the latest stock price for a given stock ticker.
|
| 8 |
+
This class extends the Tool base class from smolagents.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
name = "stock_price_tool"
|
| 12 |
+
description = "Fetches the latest stock price for a given stock ticker using yfinance."
|
| 13 |
+
inputs = {'ticker_symbol': {'type': 'any', 'description': 'Stock Ticker Symbol'}}
|
| 14 |
+
output_type = "Any"
|
| 15 |
+
|
| 16 |
+
def _call(self, ticker_symbol: str) -> Any:
|
| 17 |
+
"""
|
| 18 |
+
Fetches the latest stock price for the given ticker symbol.
|
| 19 |
+
Args:
|
| 20 |
+
ticker_symbol (str): The stock ticker symbol (e.g., "AAPL" for Apple, "GOOGL" for Google).
|
| 21 |
+
Returns:
|
| 22 |
+
float: The current stock price of the given ticker symbol.
|
| 23 |
+
None: If an error occurs or data is unavailable.
|
| 24 |
+
Example:
|
| 25 |
+
>>> StockPriceTool()._call("AAPL")
|
| 26 |
+
150.25
|
| 27 |
+
"""
|
| 28 |
+
try:
|
| 29 |
+
# Fetch the stock data using yfinance
|
| 30 |
+
stock = yf.Ticker(ticker_symbol)
|
| 31 |
+
|
| 32 |
+
# Get the current price (the last close price)
|
| 33 |
+
stock_data = stock.history(period="1d")
|
| 34 |
+
if stock_data.empty:
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
current_price = stock_data['Close'].iloc[0]
|
| 38 |
+
return float(current_price)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
# If there's an error, log it and return None
|
| 41 |
+
print(f"Error fetching price for {ticker_symbol}: {str(e)}")
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
def __init__(self, *args, **kwargs):
|
| 45 |
+
self.is_initialized = False
|