tdameritrade

Python interface to TD Ameritrade Api

https://dev.azure.com/tpaine154/tdameritrade/_apis/build/status/timkpaine.tdameritrade?branchName=masterBuild Status https://img.shields.io/azure-devops/coverage/tpaine154/tdameritrade/8Coverage https://img.shields.io/github/license/timkpaine/tdameritrade.svgLicense https://img.shields.io/pypi/v/tdameritrade.svgPyPI https://img.shields.io/readthedocs/tdameritrade.svgDocs

Getting Started

Install

Install from pip

pip install tdameritrade

or from source

python setup.py install

Docs

Major changes in the v0.1.0 update to the way tokens are handled.You will still need the original authentication instructions, but the TDClient now takes the refresh token and client id, not the access token. A new session class handles token expiration and will automatically call a new token as needed.

It is recommended that you store these as environmental variables.

client_id = os.getenv('TDAMERITRADE_CLIENT_ID')
account_id = os.getenv('TDAMERITRADE_ACCOUNT_ID')
refresh_token = os.getenv('TDAMERITRADE_REFRESH_TOKEN')

tdclient = tdameritrade.TDClient(client_id=client_id, refresh_token=refresh_token, account_ids=[account_id])

See the tests\test_client.py file for examples on current usage.

Read the docs!

All functionality is available as methods on the TDClient object. For most methods, there is a convenience method to return the result as a pandas DataFrame.

https://raw.githubusercontent.com/timkpaine/tdameritrade/master/docs/img/client/client.png

Most data fetching methods accept the symbol as argument. For equities, this is just the ticker.

https://raw.githubusercontent.com/timkpaine/tdameritrade/master/docs/img/client/quote.png

For different assets, utilize the search and instrument methods to lookup symbols. For options, you can utilize the options method.

https://raw.githubusercontent.com/timkpaine/tdameritrade/master/docs/img/options.png

API Documentation

Authentication

TD Ameritrade requires an OAuth token. It is somewhat laborious to get this, but parts have been automated here with selenium.

Steps

Step 1

Navigate and register/login to the TD Developer page.

Step 2

Navigate to My Apps

auth1.png

Step 3

Create a new one

Step 4

Set the name and id to something reasonably unique, and the redirect to http://localhost:8080 for now.

Step 5

run tdameritrade.auth.authentication from a python prompt, with client_id=consumer_key and redirect_uri from step 4.

Step 6

Sign in and authorize your app.

You can enter credentials by hand or store them in environment variables TDAUSER and TDAPASS. When stored, the first page will be filled in and advanced automaticly.

auth2.png auth3.png

Step 7

Return to the prompt, if you entered the info correctly you should see your tokens printed. Write these down, i recommend keeping a keys.sh file setting ACCESS_TOKEN and REFRESH_TOKEN environment variables.

auth4.png
class tdameritrade.client.TDClient(client_id=None, refresh_token=None, account_ids=None)[source]

Bases: object

accounts(positions=False, orders=False)[source]

get user accounts. caches account ids in accountIds if not provided during initialization

Parameters:
  • positions (bool) – include position information
  • orders (bool) – include order information
accountsDF()[source]

get accounts as dataframe

cancelOrder(accountId, orderId)[source]

cancel the given order

Parameters:
  • accountId (int) – account id the order is under
  • orderId (int) – order id of order to cancel
createSavedOrder(accountId, order)[source]

create a saved order

Parameters:
  • accountId (int) – id of account to place order under
  • order (JSON) – order instance to place
createWatchlist(accountId, watchlist)[source]

create watchlist for account

Parameters:
  • accountId (int) – account to get watchlist for
  • watchlist (JSON) – watchlist to create
deleteSavedOrder(accountId, savedOrderId)[source]

delete a saved order

Parameters:
  • accountId (int) – id of account to place order under
  • savedOrderId (int) – id of order instance to delete
deleteWatchlist(accountId, watchlistId)[source]

delete watchlist for account

Parameters:
  • accountId (int) – account to delete watchlist from
  • watchlistId (int) – watchlist to delete
fundamentalSearch(symbol)[source]

helper to search for a symbol using fundamental projection

fundamentalSearchDF(symbol)[source]

helper to search for a symbol using fundamental projection and return DF

history(symbol, periodType=None, period=None, frequencyType=None, frequency=None, endDate=None, startDate=None, needExtendedHoursData=True)[source]

get price history

Parameters:
  • symbol (str) – symbol to get price history for
  • periodType (str) – period type to request
  • period (int) – period to use
  • frequencyType (str) – frequency type to use
  • frequency (int) – frequency to use
  • endDate (int) – End date as milliseconds since epoch. If startDate and endDate are provided, period should not be provided. Default is previous trading day.
  • startDate (int) – Start date as milliseconds since epoch. If startDate and endDate are provided, period should not be provided.
  • needExtendedHoursData (bool) – true to return extended hours data, false for regular market hours only. Default is true
historyDF(symbol, **kwargs)[source]

get history as dataframe

hours(market='EQUITY', date=None)[source]

get market hours

Parameters:
  • market (str) – market to get hours for, in (‘EQUITY’, ‘OPTION’, ‘FUTURE’, ‘BOND’, ‘FOREX’)
  • date (str) – date to get hours for, yyyy-MM-dd or yyyy-MM-dd’T’HH:mm::ssz
instrument(cusip)[source]

get instrument info from cusip

Parameters:cusip (str) – the cusip to use, can find it by looking up in search
instrumentDF(cusip)[source]

get instrument info from cusip as dataframe

movers(index, direction='up', change='percent')[source]

request market movers

Parameters:
  • index (str) – index to look for movers in
  • direction (str) – up or down
  • change (str) – percent or value
options(symbol, contractType='ALL', strikeCount=-1, includeQuotes=False, strategy='SINGLE', interval=None, strike=None, range='ALL', fromDate=None, toDate=None, volatility=None, underlyingPrice=None, interestRate=None, daysToExpiration=None, expMonth='ALL', optionType='ALL')[source]

request option chain information

Parameters:
  • symbol (str) – Enter one symbol
  • contractType (str) – Type of contracts to return in the chain. Can be CALL, PUT, or ALL. Default is ALL.
  • strikeCount (int) – The number of strikes to return above and below the at-the-money price.
  • includeQuotes (bool) – Include quotes for options in the option chain. Can be TRUE or FALSE. Default is FALSE.
  • strategy (str) – Passing a value returns a Strategy Chain. Possible values are SINGLE, ANALYTICAL (allows use of the volatility, underlyingPrice, interestRate, and daysToExpiration params to calculate theoretical values), COVERED, VERTICAL, CALENDAR, STRANGLE, STRADDLE, BUTTERFLY, CONDOR, DIAGONAL, COLLAR, or ROLL. Default is SINGLE.
  • interval (int) – Strike interval for spread strategy chains (see strategy param).
  • strike (float) – Provide a strike price to return options only at that strike price.
  • range (str) – Returns options for the given range. Possible values are: ITM: In-the-money NTM: Near-the-money OTM: Out-of-the-money SAK: Strikes Above Market SBK: Strikes Below Market SNK: Strikes Near Market ALL: All Strikes Default is ALL.
  • fromDate (str) – Only return expirations after this date. For strategies, expiration refers to the nearest term expiration in the strategy. Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd’T’HH:mm:ssz.
  • toDate (str) – Only return expirations before this date. For strategies, expiration refers to the nearest term expiration in the strategy. Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd’T’HH:mm:ssz.
  • volatility (float) – Volatility to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • underlyingPrice (float) – Underlying price to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • interestRate (float) – Interest rate to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • daysToExpiration (int) – Days to expiration to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • expMonth (str) – Return only options expiring in the specified month. Month is given in the three character format. Example: JAN Default is ALL.
  • optionType (str) – Type of contracts to return. Possible values are: S: Standard contracts NS: Non-standard contracts ALL: All contracts Default is ALL.
optionsDF(symbol, contractType='ALL', strikeCount=-1, includeQuotes=False, strategy='SINGLE', interval=None, strike=None, range='ALL', fromDate=None, toDate=None, volatility=None, underlyingPrice=None, interestRate=None, daysToExpiration=None, expMonth='ALL', optionType='ALL')[source]

return options chain as dataframe

orders(accountId=None, orderId=None, maxResults=-1, fromEnteredTime=None, toEnteredTime=None, status=None)[source]

get order

Parameters:
  • accountId (int) – account id
  • orderId (int) – orderId
  • maxResults (int) – max number of results to return
  • fromEnteredTime (str) – yyyy-MM-dd to filter by
  • toEnteredTime (str) – yyyy-MM-dd to filter by
  • status (str) – only return orders with this status
placeOrder(accountId, order)[source]

place an order

Parameters:
  • accountId (int) – id of account to place order under
  • order (JSON) – order instance to place
preferences(accountId=None)[source]

get preferences for account

Parameters:accountId (int) – account to get preferences for
quote(symbol)[source]

get quote for symbol

Parameters:symbol (str) – symbol to get quote for
quoteDF(symbol)[source]

get quote, format as dataframe

replaceOrder(accountId, orderId, order)[source]

place an order

Parameters:
  • accountId (int) – id of account to place order under
  • orderId (int) – id of order to replace
  • order (JSON) – order instance to place
replaceSavedOrder(accountId, savedOrderId, order)[source]

create a saved order

Parameters:
  • accountId (int) – id of account to place order under
  • savedOrderId (int) – id of order instance to delete
  • order (JSON) – order instance to place
replaceWatchlist(accountId, watchlistId, watchlist)[source]

update watchlist for account

Parameters:
  • accountId (int) – account to get watchlist for
  • watchlistId (int) – watchlist to update
  • watchlist (JSON) – watchlist to update with
savedOrders(accountId=None, savedOrderId=None)[source]

get saved orders

Parameters:
  • accountId (int) – id of account to get saved orders from
  • savedOrderId (int) – id of saved order
search(symbol, projection='symbol-search')[source]

Search for a symbol

Parameters:
  • symbol (sring) – string to search for
  • projection (string) – projection to use, in (‘symbol-search’, ‘symbol-regex’, ‘desc-search’, ‘desc-regex’, ‘fundamental’)
searchDF(symbol, projection='symbol-search')[source]

search for symbol as a dataframe

transactions(accountId=None, type=None, symbol=None, startDate=None, endDate=None)[source]

get transactions by account

Parameters:
  • accountId (int) – account id (defaults to client’s ids)
  • type (str) – transaction type, in (‘ALL’, ‘TRADE’, ‘BUY_ONLY’, ‘SELL_ONLY’, ‘CASH_IN_OR_CASH_OUT’, ‘CHECKING’, ‘DIVIDEND’, ‘INTEREST’, ‘OTHER’, ‘ADVISOR_FEES’)
  • symbol (str) – transactions for given symbol
  • start_date (str) – start date as string yyyy-MM-dd
  • end_date (str) – end date as string yyyy-MM-dd
transactionsDF(accountId=None, type=None, symbol=None, startDate=None, endDate=None)[source]

get transaction information as Dataframe

updatePreferences(accountId, preferences)[source]

update preferences for account

Parameters:
  • accountId (int) – account to get preferences for
  • preferences (JSON) – preferences to update
updateWatchlist(accountId, watchlistId, watchlist)[source]

update watchlist for account

Parameters:
  • accountId (int) – account to get watchlist for
  • watchlistId (int) – watchlist to update
  • watchlist (JSON) – watchlist to update with
watchlists(accountId=None, watchlistId=None)[source]

get watchlist for account

Parameters:
  • accountId (int) – account to get watchlist for
  • watchlistId (int) – watchlist to get
tdameritrade.client.response_is_valid(resp)[source]
tdameritrade.auth.access_token(refresh_token, client_id)[source]
tdameritrade.auth.authentication(client_id, redirect_uri, tdauser=None, tdapass=None)[source]
tdameritrade.auth.main()[source]