首页 > 解决方案 > 从 Alphavantage api 读取数据时,我无法访问日期列

问题描述

我正在尝试使用 AlphaVantage API 将数据放入数据框并在 Plotly dash 中使用。我能够看到数据,但无法读取日期列。请帮忙。

import pandas as pd
import configparser
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
import plotly.graph_objs  as go
import plotly.express as px
import datetime

parser = configparser.RawConfigParser()
parser.read('config_key.ini')
info = parser['apikey']['key']

ts = TimeSeries(key=info,output_format='pandas', indexing_type='date')
data, meta_data = ts.get_daily(symbol='AAPL', outputsize='full')
data.rename(columns={'date':'Date','1. open': 'open', '2. high': 'high',
                     '3. low': 'low', '4. close': 'close', '5. volume': 'volume'},
            inplace=True)
data.sort_values(by='date', ascending=False, inplace=True)

data.head()
[enter image description here][1]

标签: pythonpandasdataframeplotlyplotly-dash

解决方案


获取的数据框的日期被索引,因此它将data.index代替data['date']. 由于我没有使用配置解析器,因此代码改变了我们获取 API 信息的方式。

import pandas as pd
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
import datetime

with open('./alpha_vantage_api_key.txt') as f:
    api_key = f.read()

ts = TimeSeries(key=api_key, output_format='pandas', indexing_type='date')
data, meta_data = ts.get_daily(symbol='AAPL', outputsize='full')
data.rename(columns={'date':'Date','1. open': 'open', '2. high': 'high',
                     '3. low': 'low', '4. close': 'close', '5. volume': 'volume'},
            inplace=True)
data.sort_values(by='date', ascending=False, inplace=True)

data.head()
            open    high    low     close   volume
date                    
2020-11-20  118.64  118.7700    117.290     117.34  73604287.0
2020-11-19  117.59  119.0600    116.810     118.64  74112972.0
2020-11-18  118.61  119.8200    118.000     118.03  76322111.0
2020-11-17  119.55  120.6741    118.960     119.39  74270973.0
2020-11-16  118.92  120.9900    118.146     120.30  91183018.0

import plotly.graph_objects as go

fig = go.Figure(data=[go.Candlestick(x=data.index,
                open=data['open'],
                high=data['high'],
                low=data['low'],
                close=data['close'])])

fig.show()

在此处输入图像描述


推荐阅读