使用 yfinance 和 python 计算股票价值

Calculation of stock values with yfinance and 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', 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 (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 数据框来创建代码。在这个数据框中,Date 不是一个普通的列,而是给索引的一个名称(参见 base.py of yfinance). The index column behaves differently than other columns and actually can't be referenced by name. You can access it using TickerDf.index=='2020-12-30' or by turning it into a regular column using reset_index as explained in another question. Searching through an index is faster 中的第 240 行而不是搜索常规列,所以如果你正在查看大量数据,将其保留为索引对您有利。