Home > Software engineering >  Adding loop for multiple tickers in TDA-API python script
Adding loop for multiple tickers in TDA-API python script

Time:11-16

I've managed to piece together the following code, and am wondering how to reference multiple tickers instead of only 'AAPL'. I'm new to python and have starting making some traction, but I'm scratching my head here. Thanks!

from tda import auth, client
import json
import config
import pandas as pd
import datetime

try:
    c = auth.client_from_token_file(config.token_path, config.api_key)
except FileNotFoundError:
    from selenium import webdriver
    with webdriver.Chrome(executable_path='/Users/capnb/Documents/TDAmeritrade/chromedriver') as driver:
        c = auth.client_from_login_flow(
            driver, config.api_key, config.redirect_uri, config.token_path)

r = c.get_option_chain('AAPL')
data = json.loads(r.text)

ret = []
for date in data["callExpDateMap"]:
    for strike in data["callExpDateMap"][date]:
        ret.extend(data["callExpDateMap"][date][strike])
for date in data["putExpDateMap"]:
    for strike in data["putExpDateMap"][date]:
        ret.extend(data["putExpDateMap"][date][strike])
df = pd.DataFrame(ret)
for col in ("tradeTimeInLong", "quoteTimeInLong", "expirationDate", "lastTradingDay"):
    df[col] = pd.to_datetime(df[col], unit="ms")
filename = datetime.datetime.now().strftime('option_prices-%Y-%m-%d-%H-%M.csv')
path = "c:/Users/capnb/Desktop/"
    
df.to_csv(path filename)

CodePudding user response:

Don't think you can call more than one symbol at a time, so create a list of tickers and loop. see if this works.

def get_chains(symbol):
    r = c.get_option_chain(symbol)
    data = json.loads(r.text)

    ret = []
    for date in data["callExpDateMap"]:
        for strike in data["callExpDateMap"][date]:
            ret.extend(data["callExpDateMap"][date][strike])
    for date in data["putExpDateMap"]:
        for strike in data["putExpDateMap"][date]:
            ret.extend(data["putExpDateMap"][date][strike])
    df = pd.DataFrame(ret)
    for col in ("tradeTimeInLong", "quoteTimeInLong", "expirationDate", "lastTradingDay"):
        df[col] = pd.to_datetime(df[col], unit="ms")
    # filename = datetime.datetime.now().strftime('option_prices-%Y-%m-%d-%H-%M.csv')
    filename = symbol   '-option_prices-'   datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')   '.csv'
    path = "c:/Users/capnb/Desktop/"
        
    df.to_csv(path filename)

symbols = ['AAPL', 'GE', 'TSLA']
for symbol in symbols:
    get_chains(symbol)
  • Related