You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在树莓派3虚拟环境执行Python Requests代码时遇KeyError 'historical'

解决股票价格分析代码的KeyError 'historical'问题

在树莓派3的虚拟环境(venv)中运行以下股票价格分析Python代码时,触发了KeyError 'historical'错误,以下是问题排查和解决方法:

原代码

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')

问题原因

KeyError 'historical'说明API返回的JSON数据中不存在historical字段,常见原因包括:

  • API请求未携带必填的密钥,返回错误信息而非正常数据
  • 股票代码输入错误(该API主要支持美股代码,需确保格式正确,如AAPL而非AAPL.SW)
  • 树莓派网络无法正常访问该API域名
  • API返回了错误状态码(如404、401)

解决步骤

  1. 查看API实际返回内容
    在代码中添加打印语句,确认返回的JSON结构:

    stockprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line")
    stockprices = stockprices.json()
    print(stockprices)  # 新增这行,查看返回内容
    

    如果返回包含Error Message等字段,说明请求未通过验证或参数错误。

  2. 添加API密钥
    当前该API需要密钥才能访问,免费版申请后,将密钥添加到请求URL中:

    API_KEY = "你的API密钥"
    stockprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line&apikey={API_KEY}")
    
  3. 验证股票代码
    确保传入的股票代码为有效美股代码,例如AAPL、MSFT,避免使用带交易所后缀的格式。

  4. 检查网络连接
    在树莓派终端执行ping financialmodelingprep.com,确认网络能正常访问该域名;若无法访问,检查网络设置或代理配置。

优化后的代码示例

import requests
import pandas as pd
import matplotlib.pyplot as plt

def stockpriceanalysis(stock):
    API_KEY = "你的API密钥"  # 替换为实际密钥
    url = f"https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line&apikey={API_KEY}"
    stockprices = requests.get(url)
    
    # 检查请求状态码
    if stockprices.status_code != 200:
        print(f"请求失败,状态码:{stockprices.status_code}")
        return
    
    stockprices = stockprices.json()
    
    # 检查是否存在historical字段
    if 'historical' not in stockprices:
        print(f"API返回错误:{stockprices.get('Error Message', '未知错误')}")
        return
    
    #Parse the API response and select only last 1200 days of prices
    stockprices = stockprices['historical'][-1200:]

    #Convert from dict to pandas dataframe
    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')
    plt.show()  # 新增显示图表的语句

内容的提问来源于stack exchange,提问作者programmer wannabe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 05:20:58