From b518115791914b1d7841d4dae57d685b13a3dcca Mon Sep 17 00:00:00 2001 From: moshferatu Date: Mon, 11 Nov 2024 09:02:51 -0800 Subject: [PATCH] Add script for retrieving daily data, including falling back to intraday bars while the market is still open --- daily_data.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 daily_data.py diff --git a/daily_data.py b/daily_data.py new file mode 100644 index 0000000..1f0b4e3 --- /dev/null +++ b/daily_data.py @@ -0,0 +1,39 @@ +from datetime import datetime, timedelta +from pandas import concat, DataFrame + +from ohlc import ohlc + +def get_daily_data(symbol: str, start_date: datetime = datetime.today() - timedelta(days = 365), + end_date: datetime = datetime.today()) -> DataFrame: + daily_data = ohlc(symbol = symbol, start_date = start_date, end_date = end_date) + + """ + The daily bar is not available for the current day until after market close. + It must be calculated using intraday (e.g., 5-minute) bars while the market is open. + """ + today = datetime.today().strftime('%Y-%m-%d') + if today not in daily_data['Date'].values: + intraday_data = ohlc(symbol = symbol, minutes = 5) + + open_price = intraday_data['Open'].iloc[0] + high_price = intraday_data['High'].max() + low_price = intraday_data['Low'].min() + close_price = intraday_data['Close'].iloc[-1] + total_volume = intraday_data['Total Volume'].iloc[-1] + + todays_data = { + 'Date': today, + 'Open': open_price, + 'High': high_price, + 'Low': low_price, + 'Close': close_price, + 'Total Volume': total_volume, + 'Period Volume': 0 + } + + daily_data = concat([daily_data, DataFrame([todays_data])], ignore_index = True) + + return daily_data + +if __name__ == '__main__': + print(get_daily_data(symbol = 'SPY'))