TypeError: cannot concatenate object of type '<class 'yfinance.ticker.Options'>'; only Series and DataFrame objs are valid

TypeError: cannot concatenate object of type '<class 'yfinance.ticker.Options'>'; only Series and DataFrame objs are valid

下面是我的代码,用于从股票代码列表中提取股票期权数据,然后将所有股票期权的数据帧连接成一个。但是,我收到以下错误消息:“TypeError:无法连接类型为‘”的对象;只有 Series 和 DataFrame 对象有效

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)

为了绑定到列表,我们不能使用pd.concat(),所以如果我们将初始值设为数据框,问题就解决了。

import yfinance as yf
import pandas as pd

tickers = ['AAPL','AA','AAL']

opt_appended = pd.DataFrame()

for symbol in tickers:
    try:
        ticker = yf.Ticker(symbol)
        opt = ticker.option_chain('2021-07-30')
        opt_appended = opt_appended.append(opt)
    except ValueError:
        continue
contractSymbol lastTradeDate strike lastPrice bid ask change percentChange volume openInterest impliedVolatility inTheMoney contractSize currency
0 AAPL210730C00065000 2021-07-28 19:37:45 65 80.32 78.75 81.3 -1.18 -1.44785 5 81 4.1875 True REGULAR USD
1 AAPL210730C00070000 2021-07-22 18:17:27 70 74.95 74.3 75.8 -2.26 -2.92708 2 153 4.01563 True REGULAR USD
2 AAPL210730C00075000 2021-07-28 17:19:38 75 70.05 69.25 70.85 -3.39999 -4.62899 20 197 3.67188 True REGULAR USD
3 AAPL210730C00080000 2021-07-22 14:59:05 80 67.8 63.9 66.25 0 0 67 133 3.46094 True REGULAR USD
4 AAPL210730C00085000 2021-07-27 16:09:57 85 60.95 59.6 61.15 0 0 12 186 3.89063 True REGULAR USD

顺序追加到 DataFrame 的成本非常高,因为它需要在每次迭代时构建一个新的 DataFrame。因此,通常避免使用它们。由于 option_chain returns 是一个可迭代的,我们应该 extend 列表而不是附加到列表。然后在最后执行单个concat

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]