python - Python KeyError : 0,你能帮我找出错误吗?
问题描述
我的 python 代码中有一个 keyError 0 。
我真的不明白在我的情况下意味着什么我读了很多关于它但我自己找不到我的错误有人可以帮我找到它并可能向我解释吗?
问候,
# use a function to pull all info from website
def getdata(stock):
# company quote group of items
company_quote = requests.get(f"https://financialmodelingprep.com/api/v3/quote/{stock}")
company_quote = company_quote.json()
share_price = float("{0:.2f}".format(company_quote[0]['price']))
# balance sheet
BS = requests.get(f"https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/{stock}?period=quarter")
BS = BS.json()
# total debt
debt = float("{0:.2f}".format(float(BS['financials'][0]['Total debt'])/10**9))
# total cash
cash = float("{0:.2f}".format(float(BS['financials'][0]['Cash and short-term investments'])/10**9))
# income statement group of item
IS = requests.get(f"https://financialmodelingprep.com/api/v3/financials/income-statement/{stock}?period=quarter")
IS = IS.json()
# most recent quarterly revenue
qRev = float("{0:.2f}".format(float(IS['financials'][0]['Revenue'])/10**9))
# company profile group of items
company_info = requests.get(f"https://financialmodelingprep.com/api/v3/company/profile/{stock}")
company_info = company_info.json()
# CEO
ceo = company_info['profile']['ceo']
return (share_price, cash, debt, qRev, ceo)
tickers = ('AAPL', 'MSFT', 'GOOG', 'MVIS')
data = map(getdata, tickers)
# create the dataframe with pandas to store all of the info
df = pd.DataFrame(data, columns = ['Total Cash', 'Total Debt', 'Q3 2019 Revenue', 'CEO'], index = tickers)
print(df)
# writing to excel
writer = pd.ExcelWriter('example.xlsx')
df.to_excel(writer, 'Statistics')
writer.save()
解决方案
我刚刚执行了您粘贴的代码,似乎问题是您没有正确使用 API,似乎缺少 API KEY,从您的代码中我得到了这个:
{'Error Message': 'Invalid API KEY. Please retry or visit our documentation to create one FREE https://financialmodelingprep.com/developer/docs'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in getdata
KeyError: 0
因此,请查看 API 并发送正确的值(可能缺少标头等)
推荐阅读
- javascript - 更新时重新创建相关记录
- python-3.x - trainable_variables 通过方法调用后返回零
- r - 如何使用箭头指示的偏移 geom_text() 标签绘制 geom_tile()?
- mysql - mysql中的分类树
- javascript - 在浏览器中编辑外部 JS 脚本,可以吗?
- python - train() 缺少 1 个必需的位置参数:'target_train'
- c# - 我的代码不断抛出我的 catch 异常,我不知道为什么
- web - 在 luminus 中调用 clojure 函数时出现防伪令牌错误
- css - 如何将大于 100 个文件的文件上传到 github
- python - keras.preprocessing.image_dataset_from_directory 声明它已找到所有类,然后使用其中的一小部分