我运行了代码的scraper部分,得到了813个股票代码符号的列表,然后直接将该列表放入脚本中,这样我就不必每次调试时都进行scraper。
我也打断了电话线
yf.Ticker(i).options[0]
这样我就可以知道它的哪一部分产生了异常。像这样在一行上有一堆不同的东西,这会让调试变得更加困难。
你也只是在做
except:
,它明确地丢弃了错误消息,这意味着我不知道它是什么。我还让它明确地告诉我哪些代码错误,如果遇到错误,只需继续将代码添加到列表中。
代码只会循环直到出现错误,在这种情况下,字符串“error”将被添加到列表中
opts
,然后程序就结束了,因为您没有捕获循环中的错误,然后继续执行下一项。这意味着它只会在第一个错误时停止,因此您的列表中没有很多项。
第一个错误出现在索引116处的项目之后,这解释了为什么列表中只有那么多的项目。
下面是我的测试代码的外观(代码列表被截断):
import yfinance as yf
#I actually have all tickers in the list,
#I just removed a big chunk from the middle for example purposes
tickers = ['A', 'AA', 'AAL', 'AAP', 'ABB', 'ABC', 'ZM', 'ZNH', 'ZS', 'ZTO', 'ZTS']
opts = []
for i in range(len(tickers)):
ticker = tickers[i]
try:
ticker_obj = yf.Ticker(ticker)
except Exception as e:
print('cannot create yf.Ticker object', i, ticker, e)
continue
try:
ticker_obj_options = ticker_obj.options
except Exception as e:
print('cannot get options', i, ticker, e)
continue
try:
first_option = ticker_obj_options[0]
except Exception as e:
print('cannot get first option', i, ticker, e)
continue
opts.append(first_option)
print(opts)
这段代码的输出是:
cannot get first option 116 BTO tuple index out of range
cannot get first option 141 CEA tuple index out of range
cannot get first option 286 FERG tuple index out of range
cannot get first option 373 IHG tuple index out of range
cannot get first option 392 IX tuple index out of range
cannot get first option 397 JHX tuple index out of range
cannot get first option 525 NVR tuple index out of range
cannot get first option 600 RELX tuple index out of range
cannot get first option 637 SHG tuple index out of range
cannot get first option 676 SUZ tuple index out of range
cannot get first option 701 TLK tuple index out of range
cannot get first option 767 WBK tuple index out of range
意思是,对于那些股票代码
yf.Ticker
对象有一个空的
options
元组。至于为什么,我不理解这种金融方面的东西,所以这取决于你来找出为什么雅虎金融没有这些符号的选项。也许他们应该在他们的房间里放些东西
选项
也许他们不应该,但我不知道。