Python 将Alphavantage API响应转换为数据帧
我一直在寻找其他相关的话题,所以只能找到类似的问题,但没有什么可以帮助我 我正在查询AlphaVantage的股票数据。我收到数据并解码,但由于格式问题,目前无法转换为熊猫数据帧。答复如下:Python 将Alphavantage API响应转换为数据帧,python,pandas,dataframe,alpha-vantage,Python,Pandas,Dataframe,Alpha Vantage,我一直在寻找其他相关的话题,所以只能找到类似的问题,但没有什么可以帮助我 我正在查询AlphaVantage的股票数据。我收到数据并解码,但由于格式问题,目前无法转换为熊猫数据帧。答复如下: { "Meta Data": { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol&
{
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "AAPL",
"3. Last Refreshed": "2021-04-26",
"4. Output Size": "Full size",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2021-04-26": {
"1. open": "134.8300",
"2. high": "135.0600",
"3. low": "133.5600",
"4. close": "134.7200",
"5. volume": "66905069"
},
"2021-04-23": {
"1. open": "132.1600",
"2. high": "135.1200",
"3. low": "132.1600",
"4. close": "134.3200",
"5. volume": "78756779"
},
"2021-04-22": {
"1. open": "133.0400",
"2. high": "134.1500",
"3. low": "131.4100",
"4. close": "131.9400",
"5. volume": "84566456"
},
运行以下代码后:
将请求作为rq导入
导入json
基本url=”https://www.alphavantage.co/query?"
params={“function”:函数,“symbol”:符号,“outputsize”:输出大小,“datatype”:数据类型,“apikey”:api\u key}
response=rq.get(base_url,params=params)
data\u str=数据字节。解码(“utf-8”)
尝试将数据加载到数据帧时出现问题:
data\u dict=json.load(data\u str)
df=pd.DataFrame(data_dict.items())
df.head()
返回:
0 1
0 Meta Data {'1. Information': 'Daily Prices (open, high, ...
1 Time Series (Daily) {'2021-04-26': {'1. open': '134.8300', '2. hig...
Meta Data Time Series (Daily)
1. Information Daily Prices (open, high, low, close) and Volumes NaN
2. Symbol AAPL NaN
3. Last Refreshed 2021-04-26 NaN
4. Output Size Full size NaN
5. Time Zone US/Eastern NaN
而且
data\u dict=json.load(data\u str)
df=pd.数据帧(数据记录)
df.head()
返回:
0 1
0 Meta Data {'1. Information': 'Daily Prices (open, high, ...
1 Time Series (Daily) {'2021-04-26': {'1. open': '134.8300', '2. hig...
Meta Data Time Series (Daily)
1. Information Daily Prices (open, high, low, close) and Volumes NaN
2. Symbol AAPL NaN
3. Last Refreshed 2021-04-26 NaN
4. Output Size Full size NaN
5. Time Zone US/Eastern NaN
两者都不可用。我要的是表单的数据帧:
date open high low close volume
有没有办法将响应转换成这种格式?因为您只需要
时间序列(每日)
值。因此,您可以在创建数据帧时直接使用
data_dict = json.loads(data_str)
df = pd.DataFrame(data_dict["Time Series (Daily)"])
df = df.T # Transpose Dataframe for desired results