Slartibartfast
Slartibartfast

Reputation: 1190

Not able to annotate on plot - KeyError

I have the following code:

import pandas as pd
import datetime as date
from pandas_datareader import data as web
import calendar
from dateutil.relativedelta import *
from pandas.tseries.offsets import *

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

stock = '^NSEI'
data = web.DataReader(stock, 'yahoo', start, end)
fig , ax = plt.subplots(figsize=(12, 4), dpi =500)

data.plot(y='Close', ax = ax)

Here i am omitting a section of code but the product is :

exceptthursday 
Out[4]: 
                  Day
Date                 
2011-01-26  Wednesday
2011-03-02  Wednesday
2011-04-12    Tuesday
2011-04-22     Friday
2011-08-15     Monday
              ...
2020-05-25     Monday
2020-10-02     Friday
2020-11-16     Monday
2020-11-30     Monday
2020-12-25     Friday

[114 rows x 1 columns]

Then we have the following code:

for anotate in (exceptthursday.index + BDay()):
    ax.annotate('holliday', xy=(anotate, data['Close'].loc[anotate]),  xycoords='data',
                xytext=(-30, 40), textcoords='offset points',
                size=13, ha='center', va="baseline",
                bbox=dict(boxstyle="round", alpha=0.1),
                arrowprops=dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1));

When i run this code i am getting the following error:

KeyError: Timestamp('2011-01-27 00:00:00')

I am not sure why i am getting this error because the start is in year 2014 so why is the error in year 2011?

Upvotes: 1

Views: 221

Answers (1)

Raghul Raj
Raghul Raj

Reputation: 1458

You are passing exceptthursday's indices for iteration. Which contains timestamps starting from 2011-01-26. The error must come in data['Close'].loc[anotate]. if I'm not wrong. Because data's start is from date.datetime(2014,1,1) which doesn't have the 2011's timestamp

Glad to help.Happy coding!:)

Upvotes: 1

Related Questions