%% Year-over-Year Returns from Daily Prices with Business Calendar Awareness
% This example shows how to compute year-over-year rolling returns for five years of simulated daily prices and also includes business calendar awareness.
% Simulate five years of daily prices and store the result in the timetable TT. Then, use isbusday to retain only data for New York Stick Exchange (NYSE) business dates.

rng(200,'twister')
time = (datetime(2014,1,1):caldays:datetime(2018,12,31))';
price = 100 + 0.1*(0:numel(time) - 1)'.*cumsum(randn(numel(time),1)/100); 
price = round(price*100)/100;                 % Round prices to the nearest penny
TT = timetable(price,'RowTimes',time,'VariableNames',{'Prices'});
TT = TT(isbusday(TT.Properties.RowTimes),:);  % Retain only NYSE business days
head(TT,10)

% Use addBusniessCalendar to add NYSE business calendar awareness. The business calendar logic determines if the date of the previous period is a business date, and if it is not, then the most recent business day preceding that date is found. For example, since 21-May-2016 is a Saturday and 22-May-2016 is a Sunday, year-over-year prices for Monday 22-May-2017 are compared to Friday 20-May-2016.

TT = addBusinessCalendar(TT);  % Add NYSE business calendar

% Compute the year-over-year returns and display the last few prices and corresponding returns.

returns = rollingreturns(TT, 'Period', calyears);
tail([TT returns])

% Copyright 2020 The MathWorks, Inc.