【问题标题】:Setting yahoo finance date as dataframe index将雅虎财务日期设置为数据框索引
【发布时间】:2016-01-11 07:59:50
【问题描述】:

我有一个 python 函数,可以将雅虎财务数据存储到数据框。

from pandas.io.data import DataReader
bars= DataReader(symbol, "yahoo",hist_date, today)

我得到的结果返回到 bar 如下

数据帧:

                    Open  High   Low  Close  Volume  Adj Close\nDate                                                  
                   \n2011-01-12  2.00  2.00  2.00   2.00     100   1.891661
                   \n2011-01-13  2.00  2.00  1.92   2.00    6800   1.891661
                   \n2011-01-14  1.84  2.24  1.84   2.19    1500   2.071369
                   \n2011-01-18  2.25  2.25  2.02   2.02    4300   1.910578
                   \n2011-01-19  2.07  2.12  2.07   2.12    3400   2.005161
                   \n2011-01-20  2.21  2.21  2.10   2.17    5000   2.052452
                   \n2011-01-21  2.25  2.25  2.20   2.20     600   2.080827
                   \n2011-01-24  2.20  2.20  2.12   2.18    2300   2.061911 

现在我想将日期列作为数据框的索引字段。此外,当我尝试在表格中显示数据框时,我无法在任何地方显示日期字段。是不是因为在列标题和列数据之前有一个 \n 。

【问题讨论】:

  • print bars.index 是什么?
  • display the dataframe in a table 是什么意思?
  • 我试图使用数据表在 html 中显示数据框的内容
  • 那你试试bars.to_html('page.html') ?
  • 或者你想先重置索引:bars.reset_index().to_html('page1.html')

标签: python pandas dataframe yahoo-finance


【解决方案1】:

首先,让我从雅虎检索 Google 5 天的历史数据:

from pandas.io.data import DataReader
import datetime as dt

today = dt.datetime.today().strftime('%Y-%m-%d')
hist = (dt.datetime.today()-dt.timedelta(7)).strftime('%Y-%m-%d')

df = DataReader('GOOG', 'yahoo', hist, today)

df

                  Open        High        Low       Close   Volume  Adj Close
Date                        
2016-01-05  746.450012  752.000000  738.640015  742.580017  1947700 742.580017
2016-01-06  730.000000  747.179993  728.919983  743.619995  1938600 743.619995
2016-01-07  730.309998  738.500000  719.059998  726.390015  2944300 726.390015
2016-01-08  731.450012  733.229980  713.000000  714.469971  2442600 714.469971

这向我显示了 6 列数据:OHLC、交易量和调整后收盘价,以及名为 Date 的索引的一列

要确定数据框确实按日期索引,您甚至可以尝试:

df.index
DatetimeIndex(['2016-01-05', '2016-01-06', '2016-01-07', '2016-01-08'], dtype='datetime64[ns]', name='Date', freq=None)

这个简短的练习是否解决了您的问题?

PS
调整关闭后的列名和Date 的顺序对我来说似乎很奇怪......

【讨论】:

  • 好的,这正是我所遵循的。现在我希望日期(数据框的索引)成为数据框中的另一个列,以便它可以像所有其他列一样显示。我尝试了代码数据框['']
  • @RahulRameshan 要将索引移动到列尝试df.reset_index()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多