我看过很多关于同一个问题的帖子,但还没有找到我的具体问题的答案。
我正在运行两个循环:-loop 1获取一组不同的股票名称,并将它们添加到yahoo finance API URL以获取它们的期权数据。因为每只股票都有许多期权,所以我运行循环2,它在范围内循环i(len(来自互联网的期权价格)),以访问每只股票的每个期权的每个价格。对于大约15只股票,整个过程运行良好,然后停止,并显示错误消息'list index out out range‘
有谁知道我做错了什么吗?提前谢谢。
代码:
stock_list = ['TREE', 'TSLA', ...]
y = len(stock_list)
while True:
for x in range(0,y):
link =("https://query2.finance.yahoo.com/v7/finance/options/" + stock_list[x])
try:
optionchain = requests.get(link).json()
except:
optionchain = 0
L = len(optionchain['optionChain']['result'][0]['options'][0]['calls'])
while True:
for i in range (L+1):
try:
arbitrage = optionchain['optionChain']['result'][0]['options'][0]['calls'][i]['lastPrice'] - (optionchain['optionChain']['result'][0]['options'][0]['calls'][i]['strike'] + optionchain['optionChain']['result'][0]['options'][0]['calls'][i]['ask'])
except:
arbitrage = 0
if arbitrage > 0:
print(stock_list[x])
print('pay: ')
print(100*optionchain['optionChain']['result'][0]['options'][0]['calls'][i]['ask'])
print('for a risk free profit of: ')
print(100*arbitrage)
print('info:')
print(optionchain['optionChain']['result'][0]['options'][0]['calls'][i])
print(' ')
else:
print(stock_list[x], i, ' No arbitrage')
break一段时间后,shell返回:
LOXO 13 No arbitrage
LOXO 14 No arbitrage
Traceback (most recent call last):
File "/Users/owner/Desktop/arbitrage option.py", line 18, in <module>
L = len(optionchain['optionChain']['result'][0]['options'][0]['calls'])
IndexError: list index out of range发布于 2018-10-27 05:18:29
这不是一个完整的答案,但这里有一些建议来解决你的问题。
请注意,错误显示在以下行上:
L = len(optionchain['optionChain']['result'][0]['options'][0]['calls'])这为您提供了有关哪个列表和哪个索引可能存在问题的线索。
现在,我在该行中看到了访问列表的两个位置:
L = len(optionchain['optionChain']['result'][0]['options'][0]['calls'])
^ ^
| |
Here Here所以,其中之一肯定是问题所在。但是是哪一个呢?
要找出答案,请尝试将长行拆分为两行较短的行:
part_1 = optionchain['optionChain']['result'][0]
L = len(part_1['options'][0]['calls'])现在,当你运行它的时候,你会得到你的错误的一个更具体的行号。
例如,假设错误发生在第一行(part_1 =)。
为什么会发生这个错误?
了解更多信息的一种方法是在访问列表之前将其打印出来:
list_1 = optionchain['optionChain']['result']
print('list_1 = ', list_1)
part_1 = list_1[0]
L = len(part_1['options'][0]['calls'])现在,如果你看到这个list_1 = [],就会给你一个关于为什么会发生错误的线索。
祝好运!
https://stackoverflow.com/questions/52992725
复制相似问题