pythonpandasdataframestockyfinance

Python error when trying to get Date from yfinance Ticker object


I am trying to make a daily line graph for certain stocks, but am running into an issue. Getting the 'Close' price every 2 minutes functions correctly, but when I try and get 'Datetime' I am getting an error. I believe yfinance used pandas to create a dataframe, but I may be wrong. Regardless, I am having issues pulling a certain column from yfinance.

I am pretty new to python and many of the packages, so this might be a simple error, but my code is shown below.

stock = yf.Ticker('MSFT')
print(stock.history(period='1d', interval='2m'))
priceArray = stock.history(period='1d',interval='2m')['Close']
dateArray = stock.history(period='1d',interval='2m')['Datetime']
        

The error I am getting is:

File "C:\Users\TrevorSmith\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\frame.py", line 3024, in __getitem__ indexer = self.columns.get_loc(key)
  
File "C:\Users\TrevorSmith\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc raise KeyError(key) from err

KeyError: 'Date'

When I print the stock.history(period='1d',interval='2m) It shows the following column names:

Open        High         Low       Close  Volume  Dividends  Stock Splits  Datetime

Again, getting ['Close'] from this information works, but ['Date'], ['Datetime'], ['DateTime'], and ['Time'] do not work.

Am I doing something wrong here? Or is there another way to get the info I am looking for?


Solution

  • Datetime is no column name, it just looks like one:

    enter image description here

    Try print(stock.history(period='1d',interval='2m).keys()) and you will see.