首页 > 解决方案 > Python:pandas data_reader -> plotly candelstick graph not identify date column from tiingo stock data api import

问题描述

任务是在特定日期范围内通过 pandas data_reader 从 tiingo api 导入股票数据,然后将其绘制成蜡烛图。导入工作。然而,绘图并未将“日期”识别为 x 轴变量。请参阅最后的错误消息。

代码:

import os
import pandas_datareader as dr
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime
start = datetime(2019, 11, 1)
end = datetime(2020, 10, 31)
my_api_key = os.environ.get("TIINGO_API_KEY")
stock_df = dr.get_data_tiingo('TTWO', start=start, end=end, api_key= my_api_key)
fig = go.Figure(data=[go.Candlestick(x=stock_df['date'],
               open=stock_df['open'],
               high=stock_df['high'],
               low=stock_df['low'],
               close=stock_df['close'])])

fig.show()

错误信息:

    ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\miniconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2894             try:
-> 2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'date'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-5-e6052ae4135a> in <module>
----> 1 fig = go.Figure(data=[go.Candlestick(x=stock_df['date'],
      2                open=stock_df['open'],
      3                high=stock_df['high'],
      4                low=stock_df['low'],
      5                close=stock_df['close'])])

~\miniconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2900             if self.columns.nlevels > 1:
   2901                 return self._getitem_multilevel(key)
-> 2902             indexer = self.columns.get_loc(key)
   2903             if is_integer(indexer):
   2904                 indexer = [indexer]

~\miniconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:
-> 2897                 raise KeyError(key) from err
   2898 
   2899         if tolerance is not None:

KeyError: 'date'

为了给您更多关于数据帧 stock_df 的上下文,这里是前五个原始数据。索引和列输入

stock_df.head()

显示:

stock_df 的前五列

的输入

stock_df.columns

显示:

Index(['close', 'high', 'low', 'open', 'volume', 'adjClose', 'adjHigh',
       'adjLow', 'adjOpen', 'adjVolume', 'divCash', 'splitFactor'],
      dtype='object')

输入:

stock_df.index

显示:

MultiIndex([('TTWO', '2019-11-01 00:00:00+00:00'),
            ('TTWO', '2019-11-04 00:00:00+00:00'),
            ('TTWO', '2019-11-05 00:00:00+00:00'),
            ('TTWO', '2019-11-06 00:00:00+00:00'),
            ('TTWO', '2019-11-07 00:00:00+00:00'),
            ('TTWO', '2019-11-08 00:00:00+00:00'),
            ('TTWO', '2019-11-11 00:00:00+00:00'),
            ('TTWO', '2019-11-12 00:00:00+00:00'),
            ('TTWO', '2019-11-13 00:00:00+00:00'),
            ('TTWO', '2019-11-14 00:00:00+00:00'),
            ...
            ('TTWO', '2020-10-19 00:00:00+00:00'),
            ('TTWO', '2020-10-20 00:00:00+00:00'),
            ('TTWO', '2020-10-21 00:00:00+00:00'),
            ('TTWO', '2020-10-22 00:00:00+00:00'),
            ('TTWO', '2020-10-23 00:00:00+00:00'),
            ('TTWO', '2020-10-26 00:00:00+00:00'),
            ('TTWO', '2020-10-27 00:00:00+00:00'),
            ('TTWO', '2020-10-28 00:00:00+00:00'),
            ('TTWO', '2020-10-29 00:00:00+00:00'),
            ('TTWO', '2020-10-30 00:00:00+00:00')],
           names=['symbol', 'date'], length=252) 

标签: pythonpandasplotlytiingo

解决方案


感谢@r-beginners 提供的选项,我找到了解决方案。要调用多索引中的列,我的问题的正确代码是:

.index.get_level_values

包括在我绘制烛台图的代码中,错误消息消失了:烛台图的更正代码:

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

fig.show()

Pandas 文档中有关 .index.get_level_values的更多详细信息


推荐阅读