numpy Python(Requests)获取KeyError 'historical'

kx5bkwkv  于 5个月前  发布在  Python
关注(0)|答案(2)|浏览(79)
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'”

mpgws1up

mpgws1up1#

您的代码假定stockprices对象中总是有一个字段“historical”,这里我修改了您的代码来检查这个字段,如果没有找到,我将打印出API返回的内容。

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
    if 'historical' in stockprices:
        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')
    else:
        print('Historical data not found for stock provided, information that was retrieved here:')
        print(stockprices)

stockpriceanalysis('TSLA')

字符串

a14dhokn

a14dhokn2#

看起来你忘了提供API key。我运行了这段代码,它要求我提供一个API key。

{'Error Message': 'Invalid API KEY. Please retry or visit our documentation to create one FREE https://financialmodelingprep.com/developer/docs'}

字符串
检查official docs

相关问题