Skip to main content

This package extend from https://github.com/timkpaine/tdameritrade.

Project description

Information

This package extend from https://github.com/timkpaine/tdameritrade I crawled data options from TD Ameritrade API with thousand requests by hour and my application has generated over 11k tokens in the last few hours when I use tdameritrade package maybe when I send a get request to TDA then a token generated so TD Ameritrade API team notice me. Then I used redis to keep token and using it in 30minute before re-generated. I only modified session.py file and keep others. Bonus, I created 2 methods to get history stock price and options straddle as Yahoo Options.

Installation

pip install pip install tdameritrade-ext --upgrade

Get Options

  • Get options
from tdameritrade_ext.client import TDClient
import time
c = TDClient()
data = c.options('AAPL', fromDate=time.strftime("%Y-%m-%d"))

Get Options Chain as Straddle (similar Yahoo Options)

def get_option_chain(ticker):
    df = None
    try:
        c = TDClient()
        df = c.options(ticker, fromDate=time.strftime("%Y-%m-%d"))
    except AssertionError as e:
        print("error 1", e)
        log.exception(e)
    except Exception as e:
        print("error 2", e)
        log.exception(e)

    if df == None:
        return None

    putExp = df['putExpDateMap']
    puts = {}
    for date, put in putExp.items():
        dates = date.split(":")
        date_expiration = dates[0]
        itemputs = {}
        for strike, itemstrikes in put.items():
            if strike[-2:] == '.0':
                strike = round(float(strike))
            itemstrike = itemstrikes[0]
            itemput = {
                'strike': strike,
                'put': {
                    'contractSymbol': itemstrike['symbol'],
                    'strike': strike,
                    'lastPrice': itemstrike['last'],
                    'change': itemstrike['netChange'],
                    'percentChange': itemstrike['percentChange'],
                    'volume': itemstrike['totalVolume'],
                    'openInterest': itemstrike['openInterest'],
                    'impliedVolatility': itemstrike['volatility'],
                    'open': itemstrike['openPrice'],
                    'high': itemstrike['highPrice'],
                    'low': itemstrike['lowPrice'],
                    'close': itemstrike['closePrice'],
                    'date': itemstrike['tradeTimeInLong'],
                    'bid': itemstrike['bid'],
                    'ask': itemstrike['ask']
                }
            }
            itemputs[strike] = itemput
        puts[date_expiration] = itemputs

    callExp = df['callExpDateMap']
    calls = {}
    for date, call in callExp.items():
        dates = date.split(":")
        date_expiration = dates[0]

        put = puts[date_expiration] if date_expiration in puts else {}
        itemcalls = []
        for strike, itemstrikes in call.items():
            if strike[-2:] == '.0':
                strike = round(float(strike))
            itemstrike = itemstrikes[0]
            itemcall = {
                'strike': strike,
                'call': {
                    'contractSymbol': itemstrike['symbol'],
                    'strike': strike,
                    'lastPrice': itemstrike['last'],
                    'change': itemstrike['netChange'],
                    'percentChange': itemstrike['percentChange'],
                    'volume': itemstrike['totalVolume'],
                    'openInterest': itemstrike['openInterest'],
                    'impliedVolatility': itemstrike['volatility'],
                    'open': itemstrike['openPrice'],
                    'high': itemstrike['highPrice'],
                    'low': itemstrike['lowPrice'],
                    'close': itemstrike['closePrice'],
                    'date': itemstrike['tradeTimeInLong'],
                    'bid': itemstrike['bid'],
                    'ask': itemstrike['ask']
                },
                'put': put[strike]['put'] if strike in put else {}
            }
            itemcalls.append(itemcall)
        calls[date_expiration] = itemcalls

    return calls
  • Get history by ticker and interval: 1m, 5m, 10m, 15m, 30m, 1h, 1d
def get_data_ticker(ticker, interval):
    c = TDClient()
    period_type = 'day'
    period = 1
    frequency_type = 'minute'
    frequency = 1

    if (interval == '5m'):
        frequency = 5
        period = 2
    elif (interval == '10m'):
        frequency = 10
        period = 3
    elif (interval == '15m'):
        frequency = 15
        period = 5
    elif (interval == '30m'):
        frequency = 30
        period = 10
    elif (interval == '1h'):
        frequency = 30
        period = 2
    elif (interval == '1d'):
        period_type = 'month'
        period = 6
        frequency_type = 'daily'
        frequency = 1

    resp = c.history(symbol=ticker,
                               periodType=period_type,
                               period=period,
                               frequencyType=frequency_type,
                               frequency=frequency)

    if 'candles' not in resp:
        return None
    candles = resp['candles']

    if (interval == '1h'):
        datas = []
        for item in candles:
            date_time = datetime.fromtimestamp(item['datetime'] / 1000)
            m = date_time.minute
            if m == 0:
                datas.append(item)
    else:
        datas = candles
    
    return datas

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tdameritrade_ext-0.0.1.tar.gz (24.5 kB view details)

Uploaded Source

Built Distribution

tdameritrade_ext-0.0.1-py3-none-any.whl (26.4 kB view details)

Uploaded Python 3

File details

Details for the file tdameritrade_ext-0.0.1.tar.gz.

File metadata

  • Download URL: tdameritrade_ext-0.0.1.tar.gz
  • Upload date:
  • Size: 24.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.0

File hashes

Hashes for tdameritrade_ext-0.0.1.tar.gz
Algorithm Hash digest
SHA256 6c15db968581aa3dd939bae9e75851562d01aef682f9fb30818dc9d49992391e
MD5 d985c98d39f350ab4b24b499b7991a99
BLAKE2b-256 4fe04ad47ab87b64a9935b720e1cc918f733315195d455caf23414b72ef40351

See more details on using hashes here.

Provenance

File details

Details for the file tdameritrade_ext-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: tdameritrade_ext-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 26.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.0

File hashes

Hashes for tdameritrade_ext-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a57e69e91869a32a3ff1be92f7638f192cf661209a6fcaf0c05f059d64ef4dde
MD5 29a991de92162f869b8c91e17680192c
BLAKE2b-256 ee58614122bc9b52b20b3f4d4455e305aca8366798c73834f1e8fc97173afe6c

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page