47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
from datetime import datetime, timedelta
|
|
from pandas import concat, DataFrame
|
|
|
|
from ohlc import ohlc
|
|
|
|
def get_daily_data(symbol: str, start_date: datetime = None, end_date: datetime = None) -> DataFrame:
|
|
|
|
if start_date is None:
|
|
start_date = datetime.today() - timedelta(days = 365)
|
|
if end_date is None:
|
|
end_date = datetime.today()
|
|
|
|
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 bars while the market is open.
|
|
"""
|
|
today = datetime.today().date()
|
|
if today not in daily_data['Date'].values:
|
|
intraday_data = ohlc(symbol = symbol, minutes = 5)
|
|
|
|
if intraday_data.empty:
|
|
return daily_data
|
|
|
|
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]
|
|
volume = intraday_data['Volume'].sum()
|
|
|
|
todays_data = {
|
|
'Date': today,
|
|
'Open': open_price,
|
|
'High': high_price,
|
|
'Low': low_price,
|
|
'Close': close_price,
|
|
'Volume': volume
|
|
}
|
|
|
|
daily_data = concat([daily_data, DataFrame([todays_data])], ignore_index = True)
|
|
|
|
return daily_data
|
|
|
|
if __name__ == '__main__':
|
|
print(get_daily_data(symbol = 'SPY'))
|