numpy Python(Requests)获取KeyError 'historical'

kx5bkwkv  于 2024-01-08  发布在  Python
关注(0)|答案(2)|浏览(212)
  1. import requests
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. def stockpriceanalysis(stock):
  5. stockprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line")
  6. stockprices = stockprices.json()
  7. #Parse the API response and select only last 1200 days of prices
  8. stockprices = stockprices['historical'][-1200:]
  9. #Convert from dict to pandas datafram
  10. stockprices = pd.DataFrame.from_dict(stockprices)
  11. stockprices = stockprices.set_index('date')
  12. #20 days to represent the 22 trading days in a month
  13. stockprices['20d'] = stockprices['close'].rolling(20).mean()
  14. stockprices['250d'] = stockprices['close'].rolling(250).mean()
  15. stockprices[['close','20d','250d']].plot(figsize=(10,4))
  16. plt.grid(True)
  17. plt.title(stock + ' Moving Averages')
  18. plt.axis('tight')
  19. plt.ylabel('Price')

字符串
当我试图用venv从我的Raspberry Pi 3执行这段代码时,我得到了“KeyError 'historical'”

mpgws1up

mpgws1up1#

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

  1. import requests
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. def stockpriceanalysis(stock):
  5. stockprices = requests.get(f"https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line")
  6. stockprices = stockprices.json()
  7. #Parse the API response and select only last 1200 days of prices
  8. if 'historical' in stockprices:
  9. stockprices = stockprices['historical'][-1200:]
  10. #Convert from dict to pandas datafram
  11. stockprices = pd.DataFrame.from_dict(stockprices)
  12. stockprices = stockprices.set_index('date')
  13. #20 days to represent the 22 trading days in a month
  14. stockprices['20d'] = stockprices['close'].rolling(20).mean()
  15. stockprices['250d'] = stockprices['close'].rolling(250).mean()
  16. stockprices[['close','20d','250d']].plot(figsize=(10,4))
  17. plt.grid(True)
  18. plt.title(stock + ' Moving Averages')
  19. plt.axis('tight')
  20. plt.ylabel('Price')
  21. else:
  22. print('Historical data not found for stock provided, information that was retrieved here:')
  23. print(stockprices)
  24. stockpriceanalysis('TSLA')

字符串

展开查看全部
a14dhokn

a14dhokn2#

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

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

字符串
检查official docs

相关问题