首页 > 解决方案 > 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()

标签: pythondictionarykeyerror

解决方案


我刚刚执行了您粘贴的代码,似乎问题是您没有正确使用 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 并发送正确的值(可能缺少标头等)


推荐阅读