import requests
import pandas as pd
import matplotlib.pyplot as plt
def stockpriceanalysis(stock):
stockprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line")
stockprices = stockprices.json()
#Parse the API response and select only last 1200 days of prices
stockprices = stockprices['historical'][-1200:]
#Convert from dict to pandas datafram
stockprices = pd.DataFrame.from_dict(stockprices)
stockprices = stockprices.set_index('date')
#20 days to represent the 22 trading days in a month
stockprices['20d'] = stockprices['close'].rolling(20).mean()
stockprices['250d'] = stockprices['close'].rolling(250).mean()
stockprices[['close','20d','250d']].plot(figsize=(10,4))
plt.grid(True)
plt.title(stock + ' Moving Averages')
plt.axis('tight')
plt.ylabel('Price')
字符串
当我试图用venv从我的Raspberry Pi 3执行这段代码时,我得到了“KeyError 'historical'”
2条答案
按热度按时间mpgws1up1#
您的代码假定
stockprices
对象中总是有一个字段“historical”,这里我修改了您的代码来检查这个字段,如果没有找到,我将打印出API返回的内容。字符串
a14dhokn2#
看起来你忘了提供API key。我运行了这段代码,它要求我提供一个API key。
字符串
检查official docs。