Home > Mobile >  Combine multiple dataframes returned from TDA-API python library
Combine multiple dataframes returned from TDA-API python library

Time:11-17

I have the code below that is saving a file for each ticker in my list, but I am trying to workout how to append all tickers into one dataframe and then save to CSV.

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)

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 = 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', 'GME', 'TSLA','GDXJ','SPY','UVXY','TLT','NIO','RKT',]
for symbol in symbols:
    get_chains(symbol)

I've tried applying this solution but I'm lost.

symbols = ['AAPL', 'GME', 'TSLA','GDXJ','SPY','UVXY','TLT','NIO','RKT',]
data = pd.DataFrame()
for symbol in symbols:
    tmp = get_chains(symbol)
    tmp.reset_index(inplace=True)
    tmp['Symbol'] = Symbol
    data = data.append(tmp, ignore_index=True)
    
filename = datetime.datetime.now().strftime('option_chain-%Y-%m-%d-%H-%M.csv')
path = "c:/Users/capnb/Desktop/"
    
data.to_csv(path filename)

CodePudding user response:

use this to replace relevant code sections.

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")
    ### ---- changes start here ---- ###
    df['Symbol'] = symbol
    return df

symbols = ['AAPL', 'GME', 'TSLA','GDXJ','SPY','UVXY','TLT','NIO','RKT',]
df_list = [] ### collect dataframes
for symbol in symbols:
    df_list.append(get_chains(symbol))

### concat dataframes
df_final = pd.concat(df_list)
df_final.reset_index(inplace=True)
    
filename = datetime.datetime.now().strftime('option_chain-%Y-%m-%d-%H-%M.csv')
path = "c:/Users/capnb/Desktop/"
  • Related