An Introduction to the TD Ameritrade API in Python

Stefan Gouyet
Analytics Vidhya
Published in
4 min readMay 27, 2020

With the TD Ameritrade API, analyzing stock market data has never been so easy. With just a little set up and a few lines of code, users have access to a whole host of stocks and options data.

Generate a Consumer Key

In order to use the TD Ameritrade API, we need a consumer key. This can be found by accessing TD’s developer website, creating an account, and then requesting a token. Once API access has been granted, you will be provided a consumer key:

Now that we have authentication completed, we can move on to writing our Python code:

Setup

First, let’s import our required packages. I use requests for the API requests and JSON for parsing the data.

import requests
import json

Next, we need to pass our consumer key as a variable:

Now let’s connect to the API. I will demonstrate this with a few different endpoints:

  1. Stock Quote

If you are looking to get a quote of an equity, the endpoint is the following:

endpoint = 'https://api.tdameritrade.com/v1/marketdata/{stock_ticker}/quotes?'

To get information regarding American Airlines’ stock, we can feed “AAL” into the {stock_ticker} placeholder.

full_url = endpoint.format(stock_ticker='AAL')page = requests.get(url=full_url,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)

We are returned with current stock data about American Airlines, including current price, 52-week range, volatility, and volume.

2. Historical Price

We can also look at a stock’s historical share price. The code looks very similar to the quotes endpoint, with pricehistory replacing quotes in the endpoint:

endpoint = 'https://api.tdameritrade.com/v1/marketdata/{stock_ticker}/pricehistory'full_url = endpoint.format(stock_ticker='AAL')page = requests.get(url=full_url,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)

We are returned with a long list of candles, corresponding to different timestamps:

The pricehistory endpoint has many parameters, corresponding to different periods and frequencies.

For example, to retrieve weekly historical data for the past year of AAL share prices, we can use the same endpoint as above but with four new parameters added:

endpoint = 'https://api.tdameritrade.com/v1/marketdata/{stock_ticker}/pricehistory?periodType={periodType}&period={period}&frequencyType={frequencyType}&frequency={frequency}'full_url = endpoint.format(stock_ticker='AAL',periodType='year',period=1,frequencyType='weekly',frequency=1)page = requests.get(url=full_url,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)

This will return us with one year’s worth of candles:

3. Fundamentals Data

We can also gather fundamentals data, via the instruments endpoint:

base_url = 'https://api.tdameritrade.com/v1/instruments?&symbol={stock_ticker}&projection={projection}'endpoint = base_url.format(stock_ticker = 'AAL',
projection = 'fundamental')
page = requests.get(url=endpoint,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)

We are returned with a whole host of information, ranging from p/e ratio to debt ratio to CUSIP number.

This endpoint allows for different types of “projections,” described below:

4. Options Data

We can also gather options data with the TD Ameritrade API:

base_url = 'https://api.tdameritrade.com/v1/marketdata/chains?&symbol={stock_ticker}'endpoint = base_url.format(stock_ticker = 'AAL')page = requests.get(url=endpoint, 
params={'apikey' : td_consumer_key})
content = json.loads(page.content)

The above API call will return a long list of options contracts (740 in this case!). It’s better to be more specific for this sort of request.

Let’s look specifically for put options with a November 20, 2020 expiration date:

base_url = 'https://api.tdameritrade.com/v1/marketdata/chains?&symbol={stock_ticker}&contractType={contractType}&fromDate={date}&toDate={date}'endpoint = base_url.format(stock_ticker = 'AAL',
contractType = 'PUT',
date='2020-11-20')
page = requests.get(url=endpoint,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)

Here, we add a few more parameters: fromDate and toDate, which are both set to “2020–11–20,” and contractType, set to “PUT.”

We are now returned with just 22 options contracts:

If you want to set a specific strike price, you can do so with the {strike} parameter:

base_url = 'https://api.tdameritrade.com/v1/marketdata/chains?&symbol={stock_ticker}\
&contractType={contract_type}&strike={strike}&fromDate={date}&toDate={date}'
endpoint = base_url.format(stock_ticker = 'AAL',
contract_type = 'PUT',
strike = 9,
date='2020-06-19')
page = requests.get(url=endpoint,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)

— -

There are other interesting API endpoints available, such as transaction history (if you use TD Ameritrade to trade) and “movers,” which tracks high/low performing stocks within different index (i.e. top 10 upward stocks today within DJI index). More info can be found in TD Ameritrade’s documentation.

— —

This post was republished to my personal blog on September 4, 2020.

--

--

Stefan Gouyet
Analytics Vidhya

Frontend Engineer | Cloud enthusiast | Washington, D.C.