Spaces:
Runtime error
Runtime error
import yfinance as yf | |
import pandas as pd | |
class YFinanceClient: | |
def __init__(self, ticker): | |
""" | |
Initializes the YFinanceClient with a stock ticker. | |
Args: | |
ticker (str): The stock ticker symbol. | |
""" | |
self.ticker = ticker | |
self.stock = yf.Ticker(ticker) | |
def fetch_historical_prices(self, period='1mo', interval='1h'): | |
""" | |
Fetches historical stock prices for the specified period and interval. | |
Args: | |
period (str): The period over which to fetch historical data (e.g., '1mo' for one month). | |
interval (str): The data interval (e.g., '1h' for hourly data). | |
Returns: | |
pd.DataFrame: A DataFrame containing the historical stock prices. | |
""" | |
hist = self.stock.history(period=period, interval=interval) | |
hist.reset_index(inplace=True) | |
# Ensure the DataFrame is in a consistent format with expected column names | |
hist.rename(columns={'Datetime': 'date', 'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume': 'volume'}, inplace=True) | |
return hist | |
# Example usage: | |
# client = YFinanceClient('AAPL') | |
# data = client.fetch_historical_prices(period='1mo', interval='1h') |