用yfinance和python计算股票价值

问题描述

我想在 Python 3 中对股票价格进行一些计算,并且我已经安装了 yfinance 模块。

我尝试获得这样的个人价值:

import yfinance as yf

#define the ticker symbol
tickerSymbol = 'MSFT'

#get data on this ticker
tickerData = yf.Ticker(tickerSymbol)

#get the historical prices for this ticker
tickerDf = tickerData.history(period='1d',start='2015-1-1',end='2020-12-30')
row_date = tickerDf[tickerDf['Date']=='2020-12-30']
value = row_date.Open.item()

#see your data
print (value)

但是当我运行它时,它说:

KeyError: 'Date'

这很奇怪,因为当我这样做时,它运行良好并且我有列日期:

import yfinance as yf

#define the ticker symbol
tickerSymbol = 'MSFT'

#get data on this ticker
tickerData = yf.Ticker(tickerSymbol)

#get the historical prices for this ticker
tickerDf = tickerData.history(period='1d',end='2020-12-30')
#row_date = tickerDf[tickerDf['Date']=='2020-12-30']
#value = row_date.Open.item()

#see your data
print (tickerDf)

我得到以下结果:

G:\python> python test.py
              Open        High         Low       Close    Volume  Dividends  Stock Splits
Date
2014-12-31   41.512481   42.143207   41.263744   41.263744  21552500        0.0             0
2015-01-02   41.450302   42.125444   41.343701   41.539135  27913900        0.0             0
2015-01-05   41.192689   41.512495   41.086088   41.157158  39673900        0.0             0
2015-01-06   41.201567   41.530255   40.455355   40.553074  36447900        0.0             0
2015-01-07   40.846223   41.272629   40.410934   41.068310  29114100        0.0             0
...                ...         ...         ...         ...       ...        ...           ...
2020-12-22  222.690002  225.630005  221.850006  223.940002  22612200        0.0             0
2020-12-23  223.110001  223.559998  220.800003  221.020004  18699600        0.0             0
2020-12-24  221.419998  223.610001  221.199997  222.750000  10550600        0.0             0
2020-12-28  224.449997  226.029999  223.020004  224.960007  17933500        0.0             0
2020-12-29  226.309998  227.179993  223.580002  224.149994  17403200        0.0             0

[1510 rows x 7 columns]

解决方法

在幕后,yfinance 使用 Pandas 数据框来创建 Ticker。在此数据框中,Date 不是普通列,而是为索引指定的名称(请参阅 base.py of yfinance 中的第 240 行)。索引列的行为与其他列不同,实际上不能按名称引用。您可以使用 TickerDf.index=='2020-12-30' 或使用 reset_index 将其转换为常规列来访问它,如 another question 中所述。搜索 through an index is faster 而不是搜索常规列,因此如果您要查看大量数据,将其保留为索引对您有利。