Adding Recession Bars to a line plot

Hi all
I am trying to figure out how to add NBER recession bars to my graph.
I understand that I need to format my date correctly using datenum for the recessionplot function to work.
To summarise, I am running a rolling regression. The date vector (datevec) has been generated using a rolling vector created in my code. Once I've got my coefficient (timevardelta + standard error bands) I am graphing it against the datevec.
Now I understand that the format of the datevec is not appropriate to use recessionplot.
Below is the code I am using for my graph:
clear all, clc
load datevec
load adjtimevarsd
load timevardelta
% Plot rolling regression results in Figure 1:
figure(1); clf ;
plot(datevec,timevardelta','LineWidth',1.5) ;
hold on ;
plot(datevec,timevardelta'+1.96*adjtimevarsd',':','Color',[.4 .4 .4],'LineWidth',1.5) ;
plot(datevec,timevardelta'-1.96*adjtimevarsd',':','Color',[.4 .4 .4],'LineWidth',1.5) ;
plot(datevec,ones(size(datevec)),'k', datevec, zeros(size(datevec)),'k') ;
ylim = get(gca,'YLim') ;
axis([2005, 2016.05, -0.50, 3.00]) ;
ylim = get(gca,'YLim') ;
xlim = get(gca,'XLim');
% redraw lines, tick marks, and axis lines
plot(datevec,timevardelta','LineWidth',1.5) ;
plot(datevec,timevardelta'+1.96*adjtimevarsd',':','Color',[.4 .4 .4],'LineWidth',1.5) ;
plot(datevec,timevardelta'-1.96*adjtimevarsd',':','Color',[.4 .4 .4],'LineWidth',1.5) ;
plot(datevec,ones(size(datevec)),'k', datevec, zeros(size(datevec)),'k') ;
ticks = get(gca,'XTick') ;
for tick = ticks ;
plot([tick,tick],[ylim(1),ylim(1)+.015*(ylim(2)-ylim(1))],'k') ;
plot([tick,tick],[ylim(2),ylim(2)-.015*(ylim(2)-ylim(1))],'k') ;
end ;
plot([xlim(1),xlim(2)],[ylim(1),ylim(1)],'k') ;
plot([xlim(1),xlim(2)],[ylim(2),ylim(2)],'k') ;
plot([xlim(1),xlim(1)],[ylim(1),ylim(2)],'k') ;
plot([xlim(2),xlim(2)],[ylim(1),ylim(2)],'k') ;
hold off ;
I have provided the data files, for your consideration.
I would be very grateful if you could please help me through (any hints, tips...anything!) how to graph NBER recession bars on my graph.
Thank you all.
Regards Parvesh

11 Comments

datevec is a builtin Matlab function; be better to not alias it with a variable.
What is the definition for the fractional portion of the year--is it based on days in the given year, 365 days, 365.25 days, ...???
The best way by far to proceed will be to convert to datetime; plot and friends are datetime aware.
Also, what is the recessionplot function????
To use recession plot dates must be converted to datenum.
Anyway I'll keep trying to get the code right.
You didn't answer the question about the time scaling of the year data...that's the first step however you approach it.
I don't have the Econometrics TB so can't look at what the function actually uses...surprising it hasn't been updated to handle datetime but still need answer to the above Q? to convert to datenum
In the rolling regression the following applies:
A year is defined as trading year with 254 days.
The roll date for the regression is 10 day.
dpb
dpb on 2 Nov 2018
Edited: dpb on 2 Nov 2018
That may be for whatever the regression was, but what's the real time representation of the (unfortunately-named) datevec array?
Per the documentation, the plot is based on datenum so to compute that time it needs must be able to be related back to actual y,m,d that was used to calculate that fractional year; the question is what was that correlation?
If it really was based on trading days, that's tough nut to crack because then you need to also have the actual market holiday schedule as well...
I did a quick look-see and it appears that it is based on actual number of days in the given year; please confirm if this is/is not true.
Where did those values come from; that source should state how they were created....or maybe the real dates are also available from the source to use directly would be even easier???
ADDENDUM And, for the two plots to line up when and if you are able to call recessionplot, the base plot will also have to be in datenum units on the time/x axis or the recession bands won't be in the correct place.
Hi there.
Below is the code I am using:
% Clean working environment
close all; clear; clc
% parameters that will be used by NLS nonlinear optimization routine:
global y X X2 k ndeltas yr ;
% load s&p500 price index file
load Data30.txt;
PI = Data30;
yr = PI(:, 1);
mo = PI(:, 2);
dy = PI(:, 3);
m30 = PI(:, 4); % price index 30-minutes before event time
p30 = PI(:, 5); % price index 30-minutes after event time
returns_30mins = ((p30-m30)./m30) ; % returns for event window (-30,30)
date = datenum(yr,mo,dy) ; % for graphing
nrows = length(yr);
%%%%%%%%%%%%%%%REMOVED PART OF THE CODE TO KEEP ONLY IMPORTANT MATERIAL %%%%%%%%%%%%
% Use estimated beta to run rolling regressions of delta
i = find(yr==2004 & mo==1); startrolldate = i(1); % rolling regression plot start date
i = find(yr==2016 & mo==12); endrolldate = i(end); % rolling regression plot end date
% define new regressor
surp = [const, X *beta] ;
% rolling regression parameters
rollby = 1 ; % number of days to roll by - Daily
% ES trades from 18:01 to 17:00 Friday to Sunday; non-trading hours are from
% 16:00 to 16:15 & 17:01 to 18:00 ==> 1,365 data points per day
% Size of rolling regression window (centered), 1 yr = 254 business days
window = 254 ;
rollvec = 1:rollby:nrows ;
for i = 1:length(rollvec) ;
[deltatemp, omegatemp] = ols(y(max(1,rollvec(i)-window/2+1):min(rollvec(i)+window/2,nrows)), ...
surp(max(1,rollvec(i)-window/2+1):min(rollvec(i)+window/2,nrows),:), 0) ;
timevardelta(i) = deltatemp(2) ;
timevarsd(i) = sqrt(omegatemp(2,2)) ;
end ;
% adjust timevarsd to account for uncertainty about beta
for i = startyr:endyr ;
j = find(yr==i & mo==6) ;
j2 = find(rollvec > j(end)) ;
yrmidpts(i-startyr+1) = rollvec(j2(1)) ;
end ;
% yrmidpts(2016-startyr+1) = rollvec(end) ; %uncomment this if sample doesn't end in Dec
for i = 2:length(yrmidpts)-1 ;
j = find(rollvec>=yrmidpts(i) & rollvec<yrmidpts(i+1)) ;
adjtimevarsd(j) = (stderrs(k+i-1) + [0:length(j)-1]*(stderrs(k+i)-stderrs(k+i-1))/length(j)) .* ...
timevarsd(j)./ (timevarsd(j(1)) + [0:length(j)-1]*(timevarsd(j(end))-timevarsd(j(1)))/length(j)) ;
end ;
j = find(rollvec<yrmidpts(2)) ;
adjtimevarsd(j) = stderrs(k+1) * timevarsd(j)/timevarsd(j(end)) ;
j = find(rollvec>=yrmidpts(end)) ;
adjtimevarsd(j) = stderrs(k+ndeltas-1) * timevarsd(j)/timevarsd(j(1)) ;
% Plot rolling regression results in Figure 1:
figure(1); clf ;
plot(date,timevardelta','LineWidth',1.5) ;
hold on ;
plot(date,timevardelta'+1.96*adjtimevarsd',':','Color',[.4 .4 .4],'LineWidth',1.5) ;
plot(date,timevardelta'-1.96*adjtimevarsd',':','Color',[.4 .4 .4],'LineWidth',1.5) ;
plot(date,ones(size(date)),'k', date, zeros(size(date)),'k') ;
ax = gca;
datetick('x','yyyy')
xlabel('Year');
ylabel('Delta');
axis tight;
recessionplot;
You were right to point out that I was not using datenum for the initial plots.
If you look at (line 14) I have modified it to use datenum.
From there on I went on to perform my rolling regressions etc.
Once this is done I am plotting the graphs against datenum; hence, I am able to call on recessionplot.
  • Does my code look ok to you?*
My apologies for the time it is taking me to reply...I am fairly new to using matlab so every time you are throwing a question at me I go back to the help files so I make sure I am not giving any stupid answers!
Highly appreciate your help!
OK, so you did have the original time data, after all. (I was sure that must have been so... VBG)
yr = PI(:, 1);
mo = PI(:, 2);
dy = PI(:, 3);
...
date = datenum(yr,mo,dy) ; % for graphing
is the right way to proceed except that again you chose a variable name that happens to be a Matlab builtin function...
>> which date
C:\ML_R2017\toolbox\matlab\timefun\date.m
>>
The code editor will highlight these for you; I'd recommend as you're learning to not get into the habit of ignoring the orange markers on the RH side just routinely...
As far as whether the rest of the code "look ok to you?" I don't have the TB to run it and don't know a thing about the particular econometric analysis so can't comment on it, but the code itself appears reasonable on the surface. Does it give you something that looks expected? Can you compare it to a known result as a check, maybe?
MUSINGS FOLLOW:
For datenum, since my coding style is to typically use pretty short (even terse, maybe?) variable names for temporaries and obvious variables, I typically will just write
dn=datenum(yr,mo,dy) ; % for graphing
to remind me it is a date number. (For datetime that would be dt, but since I historically did a lot of signal processing work that to me innately means "delta-time" so I use dtm instead).
Everybody has to develop a style of their own with which they are comfortable between verboseness and too terse so these are simply my own choices. I am, admittedly, also an elder statesmen who grew up in days of limited memory and punch cards and upper-case-only FORTRAN so "shorter was better" to keep lines within columns 7-72 on a card and old habits may loosen some but never go away entirely. :)
"is the right way to proceed except that again you chose a variable name that happens to be a Matlab builtin function..."
Noted! I will re-work the way I define my variable names to avoid clashes with Matlab inbuilt function names.
Does it give you something that looks expected? Can you compare it to a known result as a check, maybe?
The shape is as expected in literature. In fact I compared it to one of the most cited paper that used similar econometric technique and the shape of the graph looks fairly similar.
That being said I finally do have some code...with the confidence that the amount of errors I might have made is very small...so I can send it to my supervisory team for review.
Now I need to get back to the help files to format my graph and make it look much better with regards to the information I am trying to convey.
Thanks a lot for helping out.
I have an issue when trying to plot a graph and overaly recession bar on it when changing the rollby value.
The code runs ok when the rollby equal to 1, i.e. I am performing daily rolling regressions.
However, when I change rollby to, say, 10. The code for graphing the coefficient does not work.
I get the following error:
Error using plot
Vectors must be the same length.
Error in Mutivariate_30Mins (line 173)
plot(dn,timevardelta','LineWidth',1.5)
It appears that I am missing a line of code that adjusts the x-axis values for date when rolling window changes; so, my issue is kind of understandable because Matlab cannot figure out that the date vector has changed to the fact that the rolling window has changed.
Any tip around how to get past this issue?
Thank you in advance for your help.
PS:
The dates have gaps.
I cannot keep the whole dataset as I have 4.8 million plus observations and it would be difficult to run an nls regression if I keep the full length of my dataset.
That says you've not selected the same number of elements from the two variables. It looks like your plot statement hasn't been modified to use a subset of the full time array dn x variable commensurate with the y variable.

Sign in to comment.

Answers (0)

Commented:

dpb
on 10 Nov 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!