Search code examples
pythondataframeyahoo-finance

TypeError: dtype '<class 'datetime.date'>' not understood ; while converting Date of DataFrame?


I am working on below code, takes the data from yahoo finance and plotting the data for the technical analysis of the stock.

import pandas as pd
import pandas_datareader.data as web
import datetime as dt
import matplotlib.pyplot as plt
import mpl_finance
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates

ticker = 'MCD'
start = dt.date(2014, 1, 1)

#Gathering the data
data = web.DataReader(ticker, 'yahoo', start)


#Calc moving average
data['MA10'] = data['Adj Close'].rolling(window=10).mean()
data['MA60'] = data['Adj Close'].rolling(window=60).mean()
data.reset_index(inplace=True)
data['Date']=mdates.date2num(data['Date'].astype(dt.date))

Got this error

TypeError: dtype '<class 'datetime.date'>' not understood

Solution

  • If you set the date column to 'datetime.Index' format and set it as the index, the graph will be displayed. No conversion is required.try it.The setting of the library to be imported has been partially corrected.

    import pandas as pd
    import pandas_datareader.data as web
    import datetime as dt
    import matplotlib.pyplot as plt
    import mplfinance as mpf
    from mplfinance.original_flavor import candlestick_ohlc
    import matplotlib.dates as mdates
    
    ticker = 'MCD'
    start = dt.date(2014, 1, 1)
    
    #Gathering the data
    data = web.DataReader(ticker, 'yahoo', start)
    
    #Calc moving average
    data['MA10'] = data['Adj Close'].rolling(window=10).mean()
    data['MA60'] = data['Adj Close'].rolling(window=60).mean()
    data.reset_index(inplace=True)
    # data['Date']=mdates.date2num(data['Date'].astype(dt.date))
    data['Date'] = pd.to_datetime(data['Date'])
    data.set_index('Date', inplace=True)
    

    enter image description here