import yfinance as yf def fetch_stock_data(symbol, start_date, end_date, interval='1d'): """ Fetch historical stock data for a given symbol from Yahoo Finance. Parameters: - symbol (str): Stock symbol to fetch the data for. - start_date (str): Start date in 'YYYY-MM-DD' format. - end_date (str): End date in 'YYYY-MM-DD' format. - interval (str): Data interval. Defaults to '1d'. Options: '1d', '1h', etc. Returns: - DataFrame: Historical stock data including date, open, high, low, close, and volume. """ # Fetch the stock data using the yfinance library stock_data = yf.download(symbol, start=start_date, end=end_date, interval=interval) # Check if the DataFrame is empty if stock_data.empty: raise ValueError(f"No data found for {symbol} using interval {interval}.") return stock_data if __name__ == "__main__": # Example usage symbol = "AAPL" start_date = "2023-01-01" end_date = "2023-04-01" interval = "1h" # For hourly data # Fetch and print the data for demonstration data = fetch_stock_data(symbol, start_date, end_date, interval) print(data.head()) # Print the first few rows