HTML5爬取时tuple赋值变量报错,如何迭代查询多只股票期权合约
解决方案
"TypeError: can only concatenate str (not "tuple") to str"报错的根因是你给stock赋值'AAPL','AMZN'时,实际生成的是元组类型,但options.get_options_chain接口仅支持传入单个字符串格式的股票代码,无法直接识别多代码集合。
你可以通过for循环迭代所有股票代码完成批量查询,最简实现代码如下:
import pandas as pd # 公共配置仅需执行1次,无需放在循环内 pd.set_option('display.max_columns', None) # 把所有需要查询的股票代码放入列表,可自行增删 tickers = ['AAPL', 'AMZN'] expire_date = 'October 15, 2021' # 逐个迭代查询 for stock in tickers: print(f"===== {stock} 认购期权合约数据 =====") chain = options.get_options_chain(stock, expire_date) print(chain['calls'])
如果需要把所有查询结果合并为一个总表方便后续分析,可使用如下优化版代码:
import pandas as pd pd.set_option('display.max_columns', None) tickers = ['AAPL', 'AMZN'] expire_date = 'October 15, 2021' call_data_list = [] for stock in tickers: chain = options.get_options_chain(stock, expire_date) df = chain['calls'] df['所属股票代码'] = stock # 新增列标记数据所属股票 call_data_list.append(df) # 合并所有数据为单个DataFrame total_call_df = pd.concat(call_data_list, ignore_index=True) print(total_call_df)
内容的提问来源于stack exchange,提问作者James Anderson
相关产品推荐
相关产品推荐

