Below is my code to pull stock option data from a list of stock tickers then concatenate all of the stock option's dataframes into one. However, I am getting the following error message: "TypeError: cannot concatenate object of type '<class 'yfinance.ticker.Options'>'; only Series and DataFrame objs are valid"
opt_appended = []
for symbol in tickers:
try:
ticker = yf.Ticker(symbol)
opt = ticker.option_chain('2021-07-30')
opt_appended.append(opt)
except ValueError:
continue
opt_appended = pd.concat(opt_appended)
Sequential appends to a DataFrame are extremely costly as it requires a new DataFrame to be build every iteration. For this reason, they are generally avoided. Since option_chain
returns an iterable, instead of appending to the list we should extend
the list. Then perform a single concat
at the end.
import pandas as pd
import yfinance as yf
tickers = ['AAPL', 'AA', 'AAL']
opts_list = []
for symbol in tickers:
try:
ticker = yf.Ticker(symbol)
opt = ticker.option_chain('2021-07-30')
opts_list.extend(opt)
except ValueError:
continue
new_df = pd.concat(opts_list)
new_df
:
contractSymbol lastTradeDate ... contractSize currency
0 AAPL210730C00065000 2021-07-28 19:37:45 ... REGULAR USD
1 AAPL210730C00070000 2021-07-22 18:17:27 ... REGULAR USD
2 AAPL210730C00075000 2021-07-28 17:19:38 ... REGULAR USD
3 AAPL210730C00080000 2021-07-22 14:59:05 ... REGULAR USD
4 AAPL210730C00085000 2021-07-27 16:09:57 ... REGULAR USD
.. ... ... ... ... ...
28 AAL210730P00029000 2021-07-26 13:31:18 ... REGULAR USD
29 AAL210730P00029500 2021-07-26 13:32:22 ... REGULAR USD
30 AAL210730P00030000 2021-07-22 16:52:08 ... REGULAR USD
31 AAL210730P00031000 2021-07-22 15:53:55 ... REGULAR USD
32 AAL210730P00032000 2021-07-26 13:30:11 ... REGULAR USD
[253 rows x 14 columns]