# yfinance_data/fetcher.py import yfinance as yf import pandas as pd def fetch_stock_data(symbol, start_date, end_date, interval='1h'): """ Fetches historical stock data for a given symbol from Yahoo Finance. Parameters: - symbol: The ticker symbol for the stock (str). - start_date: The start date for the data fetching in 'YYYY-MM-DD' format (str). - end_date: The end date for the data fetching in 'YYYY-MM-DD' format (str). - interval: The data interval. Valid intervals: '1m', '2m', '5m', '15m', '30m', '1h', '1d', '5d', '1wk', '1mo', '3mo' (str). Returns: - DataFrame: Historical stock data including date, open, high, low, close, volume. """ # Fetch the data data = yf.download(symbol, start=start_date, end=end_date, interval=interval) # Drop any NaNs (usually in case of missing data) data.dropna(inplace=True) return data def fetch_data_for_indicators(symbol, days=30): """ Fetches historical stock data for the past 30 days for both 4-hour and 1-hour intervals. Parameters: - symbol: The ticker symbol for the stock (str). - days: Number of days in the past to fetch data for (int). Returns: - Tuple of DataFrames: (data_4h, data_1h) """ # Calculate start and end dates end_date = pd.Timestamp.now() start_date = end_date - pd.Timedelta(days=days) # Convert dates to string format for the API call start_date_str = start_date.strftime('%Y-%m-%d') end_date_str = end_date.strftime('%Y-%m-%d') # Fetch data for both intervals data_4h = fetch_stock_data(symbol, start_date_str, end_date_str, interval='4h') data_1h = fetch_stock_data(symbol, start_date_str, end_date_str, interval='1h') return data_4h, data_1h # Example usage if __name__ == "__main__": symbol = "AAPL" # Example stock symbol data_4h, data_1h = fetch_data_for_indicators(symbol) print("4-Hour Data:") print(data_4h.head()) # Display the first few rows print("\n1-Hour Data:") print(data_1h.head()) # Display the first few rows