Tuesday, 10 December 2019

Annoting date on chart

I am trying to add a straight line down which would have date printed vertically on the line. I have added a picture of how i am trying to accomplish this below. I have also included the code which i am trying to annotate with.

My code:

import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
import numpy as np

start = datetime.date(2015,1,1)
end = datetime.date.today()
start1 = datetime.date(2019,1,1)

data = web.DataReader("^GSPC", 'yahoo',start, end)
data1 = web.DataReader("^GSPC", 'yahoo', start1, end)

data.index = pd.to_datetime(data.index, format ='%Y-%m-%d')
data1.index = pd.to_datetime(data1.index, format ='%Y-%m-%d')

full_dates = pd.date_range(start, end)
data = data.reindex(full_dates)
data1 = data1.reindex(full_dates)

data['year'] = data.index.year
data['month'] = data.index.month
data['week'] = data.index.week
data['day'] = data.index.day
data1['year'] = data1.index.year
data1['month'] = data1.index.month
data1['week'] = data1.index.week
data1['day'] = data1.index.day


data.set_index('month',append=True,inplace=True)
data1.set_index('month',append=True,inplace=True)
data.set_index('week',append=True,inplace=True)
data1.set_index('week',append=True,inplace=True)
data.set_index('day',append=True,inplace=True)
data1.set_index('day',append=True,inplace=True)

data['pct_day']= data['Adj Close'].pct_change()
data1['pct_day']= data1['Adj Close'].pct_change()

df = data.groupby(['month', 'day']).mean()
df2 = data1.groupby(['month', 'day']).mean()

df['cumsum_pct_day']=df['pct_day'].cumsum(axis = 0)
df2['cumsum_pct_day']=df2['pct_day'].cumsum(axis = 0)

ax = df.plot(y='cumsum_pct_day', grid = True, label='df')
df2.plot(y='cumsum_pct_day', grid= True, ax=ax, label='df2')

ylims = ax.get_ylim()
ax.vlines(end, ylims[0], data1.Close[0], linestyles='--')
ax.text(end, data1.Close[0], end, ha='right', va='top', rotation=90)
ax.set_ylim(ylims)


plt.show()

enter image description here

For some reason i am getting warning :

enter image description here

But the line is not plotting. Could you advise why it is not doing so?



from Annoting date on chart

No comments:

Post a Comment