netflypsb commited on
Commit
ff96802
·
verified ·
1 Parent(s): 9b59595

Create yfinance_data/fetcher.py

Browse files
Files changed (1) hide show
  1. yfinance_data/fetcher.py +59 -0
yfinance_data/fetcher.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # yfinance_data/fetcher.py
2
+
3
+ import yfinance as yf
4
+ import pandas as pd
5
+
6
+ def fetch_stock_data(symbol, start_date, end_date, interval='1h'):
7
+ """
8
+ Fetches historical stock data for a given symbol from Yahoo Finance.
9
+
10
+ Parameters:
11
+ - symbol: The ticker symbol for the stock (str).
12
+ - start_date: The start date for the data fetching in 'YYYY-MM-DD' format (str).
13
+ - end_date: The end date for the data fetching in 'YYYY-MM-DD' format (str).
14
+ - interval: The data interval. Valid intervals: '1m', '2m', '5m', '15m', '30m', '1h', '1d', '5d', '1wk', '1mo', '3mo' (str).
15
+
16
+ Returns:
17
+ - DataFrame: Historical stock data including date, open, high, low, close, volume.
18
+ """
19
+ # Fetch the data
20
+ data = yf.download(symbol, start=start_date, end=end_date, interval=interval)
21
+
22
+ # Drop any NaNs (usually in case of missing data)
23
+ data.dropna(inplace=True)
24
+
25
+ return data
26
+
27
+ def fetch_data_for_indicators(symbol, days=30):
28
+ """
29
+ Fetches historical stock data for the past 30 days for both 4-hour and 1-hour intervals.
30
+
31
+ Parameters:
32
+ - symbol: The ticker symbol for the stock (str).
33
+ - days: Number of days in the past to fetch data for (int).
34
+
35
+ Returns:
36
+ - Tuple of DataFrames: (data_4h, data_1h)
37
+ """
38
+ # Calculate start and end dates
39
+ end_date = pd.Timestamp.now()
40
+ start_date = end_date - pd.Timedelta(days=days)
41
+
42
+ # Convert dates to string format for the API call
43
+ start_date_str = start_date.strftime('%Y-%m-%d')
44
+ end_date_str = end_date.strftime('%Y-%m-%d')
45
+
46
+ # Fetch data for both intervals
47
+ data_4h = fetch_stock_data(symbol, start_date_str, end_date_str, interval='4h')
48
+ data_1h = fetch_stock_data(symbol, start_date_str, end_date_str, interval='1h')
49
+
50
+ return data_4h, data_1h
51
+
52
+ # Example usage
53
+ if __name__ == "__main__":
54
+ symbol = "AAPL" # Example stock symbol
55
+ data_4h, data_1h = fetch_data_for_indicators(symbol)
56
+ print("4-Hour Data:")
57
+ print(data_4h.head()) # Display the first few rows
58
+ print("\n1-Hour Data:")
59
+ print(data_1h.head()) # Display the first few rows