使用yahooquery获取期权数据报错:DataFrame无'calls'属性
问题描述
运行Python代码时持续报错:AttributeError: 'DataFrame' object has no attribute 'calls',尝试直接调用option_chain_data()时又触发TypeError: 'DataFrame' object is not callable。
代码预期实现:
- 借助yahoo_fin获取股票实时价格
- 通过yahooquery获取期权链数据
- 将数据导出为CSV和Excel文件
用户原代码:
#max.Länge: 7 Tage import requests #import yfinance as yf from datetime import datetime from datetime import timedelta from datetime import timezone from datetime import date import time import csv import urllib.request import pandas as pd from yahoo_fin.stock_info import get_live_price from yahoo_fin.options import get_calls from yahoo_fin.options import get_puts import os import yahooquery from yahooquery import Ticker start = datetime.now() #cdate = datetime.now().strftime('%Y-%m-%d') #Get Date on which the File was saved sdate = datetime.now().strftime('%Y-%m-%d-%H-%M') #SGet Date on which the File was saved cdate = datetime.now().strftime('%Y-%m-%d') #Get Date on which the File was saved tickerlist = ['^SPX', 'UVXY', 'SPY', '^NDX', '^RLG', '^RLV', '^RUO', '^RUT', 'IWM', 'QQQ', '^RUA'] for ticker in tickerlist: underlying = get_live_price(ticker) ticker_obj = Ticker(ticker, asynchronous=True) options_rawdata = ticker_obj.option_chain ticker_str = ticker # Verwende das Ticker-Symbol direkt als Dateiname options_rawdata_csv = options_rawdata.calls # Use calls to get the Dataframe options_rawdata_csv.to_csv(f"/home/magellan/DWH/LIVE/Options/Index/" + ticker_str + "_" + sdate + ".csv", header=True, sep=';', index=False, decimal=",") options_rawdata_csv.to_excel(r"/home/magellan/DWH/LIVE/Options/Index/" + ticker_str + "_" + sdate + ".xlsx")
修复方案
问题根源
yahooquery的Ticker.option_chain返回的是合并了所有到期日、看涨/看跌期权的DataFrame,并非带有calls属性的对象。你混淆了yahoo_fin(分calls/puts返回)和yahooquery的API逻辑,导致属性调用错误。
具体修复步骤
- 提取看涨期权数据:从
option_chain的DataFrame中筛选optionType为CALL的行 - 处理文件名特殊字符:将ticker中的
^替换为_,避免文件系统识别异常 - 可选:保留看跌期权导出逻辑:如果需要看跌期权,同样筛选
optionType为PUT的行
修复后的完整代码:
#max.Länge: 7 Tage import requests from datetime import datetime import pandas as pd from yahoo_fin.stock_info import get_live_price import os from yahooquery import Ticker start = datetime.now() sdate = datetime.now().strftime('%Y-%m-%d-%H-%M') tickerlist = ['^SPX', 'UVXY', 'SPY', '^NDX', '^RLG', '^RLV', '^RUO', '^RUT', 'IWM', 'QQQ', '^RUA'] # 定义保存路径 save_path = "/home/magellan/DWH/LIVE/Options/Index/" os.makedirs(save_path, exist_ok=True) # 确保路径存在 for ticker in tickerlist: # 获取实时价格 underlying = get_live_price(ticker) # 初始化Ticker对象 ticker_obj = Ticker(ticker, asynchronous=True) # 获取期权链数据(返回DataFrame) options_rawdata = ticker_obj.option_chain # 筛选看涨期权数据 calls_data = options_rawdata[options_rawdata['optionType'] == 'CALL'] # 处理文件名中的特殊字符(替换^为_) ticker_filename = ticker.replace('^', '_') csv_filename = f"{save_path}{ticker_filename}_{sdate}.csv" excel_filename = f"{save_path}{ticker_filename}_{sdate}.xlsx" # 导出为CSV和Excel calls_data.to_csv(csv_filename, header=True, sep=';', index=False, decimal=",") calls_data.to_excel(excel_filename)
额外说明
- 如果需要导出看跌期权,只需复制看涨期权的筛选逻辑,将
optionType改为PUT即可 os.makedirs(save_path, exist_ok=True)确保保存目录存在,避免因路径不存在导致的写入错误
内容的提问来源于stack exchange,提问作者schnjopi
相关产品推荐
相关产品推荐

