/pyTD

Python SDK for TD Ameritrade's Developer APIs

Primary LanguagePythonMIT LicenseMIT

pyTD

https://travis-ci.org/addisonlynch/pytd.svg?branch=master https://codecov.io/gh/addisonlynch/pytd/branch/master/graphs/badge.svg?branch=master

A robust Python Developer Kit to TD Ameritrade for Developers. Includes pre-defined classes and functions capable of obtaining market data and managing TD Ameritrade brokerage accounts.

Highlights:

Coming Soon

  • Accounts: Balances, Positions, Watchlists, Statistics, Preferences
  • Trading: Get/Place/Cancel/Replace Orders and Saved Orders

Documentation

Full documentation is located at addisonlynch.github.io/pyTD.

Installation

Dependencies

  • requests
  • pandas

From PyPi with pip (latest stable release):

$ pip install pyTD

From development repository (development version):

$ git clone https://github.com/addisonlynch/pyTD
$ cd pyTD
$ python3 setup.py install

Getting Started

1. Register for a developer account at the TD Ameritrade Developer Website. A TD Ameritrade Developer account is required to access TD Ameritrade Developer APIs. This is separate from your TD Ameritrade Brokerage Account(s).

2. Create your TD Ameritrade Developer application. See the pyTD documentation for more information on setting up an application.

3. Run pyTD.configure (docs to set up your configuration directory and generate your self-signed SSL certificate and key. Note: if using MacOS, you may not be able to generate the certificate and key using pyTD.configure. See Generating an SSL Key/Certificate for more information.

  1. Authenticate and Authorize pyTD by simply calling any function which returns data. For example get_quotes from pyTD.market will automatically prompt you to obtain a new refresh token:
from pyTD.market import get_quotes

get_quotes("AAPL")
# WARNING:root:Need new refresh token.
# Would you like to authorize a new refresh token? [y/n]:

Selecting y will open a browser for you to authorize your application. Once the browser opens, click "AUTHORIZE" to redirect to a TD Ameritrade login prompt.

From here, log in to your TD Ameritrade Brokerage Account. Once logged in, you have successfully authorized the application. The results of your query will display on screen.

After following the steps above, you will now have a new folder

Configuration

Configuring pyTD can be done in one of three ways, depending on the production environment. pyTD stores its configuration and caches refresh/access tokens by default in the ~/.tdm directory (can be customized with the environment variable TD_CONFIG_DIR).

To configure pyTD and create the necessary directory structure, enter your TD Ameritrade Developer app's Consumer Key (Consumer Key) and Callback URL (Callback URL) by one of the below methods:

Environment Variables (Recommended):

$ export TD_CONSUMER_KEY=TEST@AMER.OAUTHAP
$ export TD_CALLBACK_URL=https://localhost:8080

Pass as argument:

from pyTD import configure

configure({
    "callback_url": "https://localhost:8080",
    "consumer_key": "TEST@AMER.OAUTHAP"
})

Note: this configuration will be cached in the current session only

Instantiate a non-global API object:

from pyTD import api

a = api({
    "callback_url": "https://localhost:8080",
    "consumer_key": "TEST@AMER.OAUTHAP"
})

The Consumer Key and Callback URL passed in these scenarios will be cached in your configuration directory in the file tdm_config. Tokens will be cached in a file whose name is your Consumer Key.

Market Data

Quotes

Get real-time or delayed stock quotes

from pyTD.market import get_quotes

get_quotes("AAPL")

Movers

Get market movers, up or down, by change or percent

from pyTD.market import get_movers

get_movers("$DJI", direction='up', change='percent')

Hours

Get operating hours of markets

import datetime
from pyTD.market import get_market_hours

date = datetime.datetime(2018, 6, 29)

get_market_hours("EQUITY", date=date)

Option Chains

Get option chains for a optionable symbols

from pyTD.market import get_option_chain

get_option_chain("AAPL")

Price History

Get historical price data for charts

import datetime
from pyTD.market import get_price_history

start = datetime.datetime(2017, 1, 1)
end = datetime.datetime(2018, 1, 1)

get_price_history("AAPL", startDate=start, endDate=end)

Fundamentals

Get fundamental data

from pyTD.market import get_fundamentals

get_fundamentals("AAPL")

Instruments

Get Instrument by CUSIP ID

from pyTD.instruments import get_instrument

get_instrument("037833100")

Get Instrument by symbol

get_instrument("AAPL")

Get Instrument by description

from pyTD.instruments import get_instruments

get_instruments("computer", projection="desc-search")

Get Instrument via regex

get_instruments("AAP.*", projection="symbol-regex")

Logging

By default, logging to the console is disabled in pyTD, but can be set in a few different ways to either INFO, DEBUG, or ERROR

  1. Environment variable:
$ export TD_LOG_LEVEL=INFO
  1. Setting pyTD.log_level:
import pyTD
pyTD.log_level = "INFO"
  1. Using Python's logging module:
import logging
logging.basicConfig()
logging.getLogger("pyTD").setLevel(logging.INFO)

Supported Python Versions

Python versions 2.7 and 3.4+ are supported by pyTD.

Frequently Asked Questions

Contact

Email: ahlshop@gmail.com

Twitter: alynchfc

License

Copyright © 2018 Addison Lynch

See LISCENSE for details