【问题标题】:Calculation of stock values with yfinance and python使用 yfinance 和 python 计算股票价值
【发布时间】:2021-04-07 21:27:06
【问题描述】:

我想在 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]

【问题讨论】:

    标签: python-3.x yfinance


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-21
      • 2021-09-06
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      相关资源
      最近更新 更多