Commit
•
61e7b60
1
Parent(s):
eaa63af
Upload get_stock_price.py with huggingface_hub
Browse files- get_stock_price.py +55 -0
get_stock_price.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Stock price lookup tool for financial analysis."""
|
2 |
+
|
3 |
+
from datetime import datetime
|
4 |
+
from typing import Dict, Union
|
5 |
+
|
6 |
+
import yfinance as yf
|
7 |
+
|
8 |
+
|
9 |
+
def get_stock_price(ticker: str, days: str = "1d") -> Dict[str, Union[float, str, list, datetime]]:
|
10 |
+
"""Retrieve stock price data for a given ticker symbol.
|
11 |
+
|
12 |
+
Args:
|
13 |
+
ticker (str): The stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
|
14 |
+
days (str): Number of days of historical data to fetch (default: 1d).
|
15 |
+
Must be one of: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
|
16 |
+
|
17 |
+
Returns:
|
18 |
+
Dict[str, Union[float, str, list, datetime]]: Dictionary containing:
|
19 |
+
- prices (list): List of closing prices for requested days
|
20 |
+
- currency (str): The currency of the price (e.g., 'USD')
|
21 |
+
- timestamps (list): List of timestamps for each price
|
22 |
+
|
23 |
+
Raises:
|
24 |
+
ValueError: If the ticker symbol is invalid or data cannot be retrieved
|
25 |
+
ValueError: If days parameter is not one of the allowed values
|
26 |
+
|
27 |
+
Metadata:
|
28 |
+
- version: 0.0.1
|
29 |
+
- author: John Doe
|
30 |
+
- requires_gpu: False
|
31 |
+
- requires_api_key: False
|
32 |
+
"""
|
33 |
+
# Validate days parameter
|
34 |
+
valid_days = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"]
|
35 |
+
if days not in valid_days:
|
36 |
+
raise ValueError(f"'days' must be one of: {valid_days}")
|
37 |
+
|
38 |
+
try:
|
39 |
+
# Get stock data
|
40 |
+
stock = yf.Ticker(ticker)
|
41 |
+
|
42 |
+
# Get historical data using valid period format
|
43 |
+
hist = stock.history(period=days)
|
44 |
+
|
45 |
+
if hist.empty:
|
46 |
+
raise ValueError(f"No data returned for ticker {ticker}")
|
47 |
+
|
48 |
+
return {
|
49 |
+
"prices": hist["Close"].tolist(),
|
50 |
+
"currency": stock.info.get("currency", "USD"),
|
51 |
+
"timestamps": [ts.to_pydatetime() for ts in hist.index],
|
52 |
+
}
|
53 |
+
|
54 |
+
except Exception as e:
|
55 |
+
raise ValueError(f"Failed to retrieve stock price for {ticker}: {str(e)}") from e
|