How to get the price history of stock index in TD Ameritrade API such as SPX, DJX, NDX, RUT, etc.?

486 Views Asked by At

I have tried to get price history of stock market index such as S&P 500 use SPX as symbol, but the server return empty data. I can get all the normal stock's price history successfully such as AAPL, TSLA, etc.

I am using td-ameritrade-python-api from Alex Reed, here is the link: https://github.com/areed1192/td-ameritrade-python-api#installation

my code is as following: ( I removed the login part of the code as that should not be a problem in this case)

ct = str(int(datetime.today().timestamp()) * 1000)  # get current time as epoch in mS
ticker_list = ['AAPL', 'SPX'] 
for ticker in ticker_list:
    quotes = TDSession.get_price_history(
        symbol=ticker, 
        period_type='year', 
        period=1,
        frequency_type='daily', 
        end_date=ct
    )
    ic(quotes)
    if len(quotes['candles']) == 0:
        print('no data retrieved, pass.')
    else:
        print(quotes['candles'])

AAPL comes out ok, but SPX shows:

ic| quotes: {'candles': [], 'empty': True, 'symbol': 'SPX'}
1

There are 1 best solutions below

1
On

After some research, I found the answer:

the symbol for index at td ameritrade is using a different format: for SPX, it is $SPX.X if replace SPX with $SPX.X in ticker_list: ['AAPL', '$SPX.X'] it will work fine! hope this can help whoever has the same problem :)