0

I am trying to plot a graph using matplotlib . I am using this code from : how to plot candlesticks in python

The code is :

from pandas_datareader import data
import matplotlib.pyplot as plt
from mpl_finance import candlestick2_ohlc
import matplotlib.dates as mdates
import fix_yahoo_finance as yf
import datetime

start = datetime.date(2018, 1, 1)
end = datetime.date.today()

aapl = yf.download("AAPL",start,end) 
aapl.reset_index(inplace=True)

aapl['Date'] = aapl.index.map(mdates.date2num)

fig, ax = plt.subplots()
plt.xlabel("Date")
plt.ylabel("Price")

candlestick2_ohlc(ax, aapl.Open, aapl.High, aapl.Low, aapl.Close, width=1, colorup='g')
plt.savefig('my_figure.png')
plt.show() 

When I run this code in google colab , I get this error :

AttributeError                            Traceback (most recent call last)
    <ipython-input-21-521826b3b41d> in <module>()
         16 
         17 
    ---> 18 aapl['Date'] = aapl.index.map(mdates.date2num)
         19 
         20 

3 frames
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

/usr/local/lib/python3.6/dist-packages/matplotlib/dates.py in _to_ordinalf(dt)
    226         tzi = UTC
    227 
--> 228     base = float(dt.toordinal())
    229 
    230     # If it's sufficiently datetime-like, it will have a `date()` method

AttributeError: 'int' object has no attribute 'toordinal'

The line of code causing the issue is this : aapl['Date'] = aapl.index.map(mdates.date2num)

When I change this line to : aapl['Date'] = mdates.date2num , the entire code works without any issues .

I am using :

matplotlib: 3.0.3 Pandas : 0.24.2

Can someone please inform me as to why the previous code will not work ? Any help will be greatly appreciated .

Jake P
  • 480
  • 3
  • 19
The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
  • 1
    if the code works without issues why does it matter? – Jake P Jul 30 '19 at 17:47
  • Obviously taking code from some other *question* is dangerous, because if it was working correctly, that question wouldn't have been asked, I guess. Rather look at examples from *answers* that are reportedly working. – ImportanceOfBeingErnest Jul 30 '19 at 23:10
  • @JakeP It matters because I am in the learning phase .. so I wanted to know the reason behind the error which will help me in the future . – The Dark Knight Jul 31 '19 at 07:56
  • @ImportanceOfBeingErnest I agree with you , but I am currently trying to learn the library related stuff . Hence I mostly try to copy code from the internet and try to check if it's working or failing . If I understand why it's failing , then I get to learn the pitfalls behind coding like this . – The Dark Knight Jul 31 '19 at 07:58
  • I'm not sure what `aapl.index.map()` does. Try printing out `aapl['Date'] = aapl.index.map(mdates.date2num)` and `aapl['Date'] = mdates.date2num` to see what's different. If they appear the same check if they are the same datatype – Jake P Jul 31 '19 at 12:00

0 Answers0