首页 > 解决方案 > 如何使用 python alpha_vantage API 返回扩展的日内数据?

问题描述

我已经使用alpha vantage python API有一段时间了,但我只需要提取每日和日内时间序列数据。我正在尝试提取扩展的盘中数据,但没有任何运气让它发挥作用。尝试运行以下代码:

from alpha_vantage.timeseries import TimeSeries

apiKey = 'MY API KEY'

ts = TimeSeries(key = apiKey, output_format = 'pandas')

totalData, _ = ts.get_intraday_extended(symbol = 'NIO', interval = '15min', slice = 'year1month1')

print(totalData)

给我以下错误:

Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 9, in <module>
    totalData, _ = ts.get_intraday_extended(symbol = 'NIO', interval = '15min', slice = 'year1month1')
  File "/home/pi/.local/lib/python3.7/site-packages/alpha_vantage/alphavantage.py", line 219, in _format_wrapper
    self, *args, **kwargs)
  File "/home/pi/.local/lib/python3.7/site-packages/alpha_vantage/alphavantage.py", line 160, in _call_wrapper
    return self._handle_api_call(url), data_key, meta_data_key
  File "/home/pi/.local/lib/python3.7/site-packages/alpha_vantage/alphavantage.py", line 354, in _handle_api_call
    json_response = response.json()
  File "/usr/lib/python3/dist-packages/requests/models.py", line 889, in json
    self.content.decode(encoding), **kwargs
  File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 518, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

有趣的是,如果您查看TimeSeries 类,它指出扩展盘中作为“一个 csv_reader 对象中的时间序列”返回,而对我有用的其他所有内容都作为“两个 json 对象”返回。我 99% 确定这与问题有关,但我不完全确定,因为我认为调用日内扩展函数至少会返回 SOMETHING(尽管它采用不同的格式),但只是给了我一个错误。

另一个有趣的小提示是,该函数拒绝将“adjusted = True”(或 False)作为输入,尽管它在文档中......可能不相关,但它可能有助于诊断。

标签: pythonjsonalpha-vantagecsvreader

解决方案


似乎 TIME_SERIES_INTRADAY_EXTENDED 只能返回 CSV 格式,但 alpha_vantage 包装器应用 JSON 方法,这会导致错误。

我的解决方法:

from alpha_vantage.timeseries import TimeSeries
import pandas as pd

apiKey = 'MY API KEY'

ts = TimeSeries(key = apiKey, output_format = 'csv')

#download the csv
totalData = ts.get_intraday_extended(symbol = 'NIO', interval = '15min', slice = 'year1month1')

#csv --> dataframe
df = pd.DataFrame(list(totalData[0]))

#setup of column and index
header_row=0
df.columns = df.iloc[header_row]
df = df.drop(header_row)
df.set_index('time', inplace=True)

#show output
print(df)

推荐阅读