File size: 2,074 Bytes
ff96802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 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