File size: 1,216 Bytes
ff96802
 
ac7b430
ff96802
ac7b430
 
ff96802
ac7b430
 
 
 
 
ff96802
ac7b430
ff96802
ac7b430
 
 
 
 
 
 
 
ff96802
 
ac7b430
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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