td-ameritrade-python-api
td-ameritrade-python-api copied to clipboard
Price history with extended hours
Hello I'm trying to get symbol price history of pre and post market data (from previous day at 4:00PM to current day at 9:30AM) But, unfortunately it seems that the API give me that data from the current day only Can you help? Thanks in advance
here is the code
from td.client import TDClient
import datetime
from typing import Tuple
from pytz import timezone
# The TD API expects a timestamp in milliseconds. However, the timestamp()
# method only returns to seconds so multiply it by 1000.
def convert_date_to_td_timestamp(d: datetime.date):
return str(int(round(d.timestamp() * 1000)))
def convert_td_timestamp_to_date(t):
return datetime.datetime.fromtimestamp(int(t)/1000, timezone('US/Eastern'))
def get_onh() -> Tuple[datetime.date, datetime.date]:
tz = timezone('US/Eastern') # ET timezone
today = datetime.datetime.now(tz)
yesterday = today - datetime.timedelta(days=1)
t = datetime.time(hour=16, minute=00) # 16:00:01 post market
post_market = datetime.datetime.combine(yesterday, t) + datetime.timedelta(seconds=1) # 16:00:01 yesterday
t = datetime.time(hour=9, minute=30) # 9:29:59 pre market
pre_market = datetime.datetime.combine(today, t) - datetime.timedelta(seconds=1) # 9:29:59 today
return post_market, pre_market
# Create a new session, credentials path is required.
td = TDClient(
client_id='ID',
redirect_uri='https://localhost:8443',
credentials_path='creds.json'
)
# Login to the session
td.login()
# These values will now be our startDate and endDate parameters.
pre_market, post_market = get_onh()
print(f'post market is {post_market.strftime("%Y-%m-%d %H:%M")}')
print(f'pre market is {pre_market.strftime("%Y-%m-%d %H:%M")}')
hist_periodType = 'day'
hist_frequencyType = 'minute'
hist_frequency = 1
history = td.get_price_history(
symbol='MSFT',
period_type=hist_periodType,
frequency_type=hist_frequencyType,
start_date=post_market,
end_date=pre_market,
frequency=hist_frequency,
extended_hours=True # Include overnight
)
candles = history['candles']
dates = [convert_td_timestamp_to_date(i['datetime']) for i in candles]
d = max(dates)
d1 = min(dates)
print(f'oldest date: {d1.strftime("%Y-%m-%d %H:%M")}')
print(f'newest date: {d.strftime("%Y-%m-%d %H:%M")}')