python - 如何使用 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)作为输入,尽管它在文档中......可能不相关,但它可能有助于诊断。
解决方案
似乎 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)
推荐阅读
- mongodb - Powershell ISE 不会将 mongo 连接返回给用户,所以我不能在那里输入任何命令
- javascript - 如何创建多个保存在本地存储中的东西
- c++ - 如何调用抽象类的子类的析构函数?
- c# - Visual Studio Code 不会在调试断点处停止
- javascript - How do I apply the same logic to multiple repeated elements?
- c# - 结合多个领域查询结果.net
- c - 如何查看传入浮点数的大小?
- python - 如何修复 SyntaxError:尝试将零填充到数字字符串时语法无效?
- swift - 如何在 Android 等警报控制器中编写 Swift 数字选择器
- c - 链表相同的值