%% Partition Multivariate Time Series Data for Estimation
% Consider fitting a VAR(4) model to the data and variables in docid:econ_ug#bsxcds7-1, and holding out the last 2 years of data to validate the predictive power of the fitted model.
% Load the data. Create a timetable containing the predictor and response variables

load Data_USEconModel

responsenames = ["CPIAUCSL" "UNRATE" "GDP"];
predictorname = "GCE";
TT = DataTable(:,[responsenames predictorname]);

% Identify all rows in the timetable containing at least one missing observation (NaN).

whichmissing = ismissing(TT);
idxvar = sum(whichmissing) > 0;
hasmissing = TT.Properties.VariableNames(idxvar)
wheremissing = find(whichmissing(:,idxvar) > 0)

% The unemployment rate is missing the first year of data in the sample.
% Remove the observations (rows) with the leading missing values from the data.

TT = rmmissing(TT);

% rmmissing uses listwise deletion to remove all rows from the input  timetable containing at least one missing observation.
% A VAR(4) model requires 4 presample responses, and the forecast sample requires 2 years (8 quarters) of data. Partition the response data into presample, estimation, and forecast sample variables. Partition the predictor data into estimation and forecast sample variables (presample predictor data is not considered estimation).

p = 4;              % Num. presample observations
fh = 8;             % Forecast horizon
T = size(TT,1);      % Total sample size
eT = T - p - fh;    % Effective sample size

idxpre = 1:p;
idxest = (p + 1):(T - fh);
idxfor = (T - fh + 1):T;

Y0 = TT{idxpre,responsenames};  % Presample responses
YF = TT{idxfor,responsenames};  % Forecast sample responses
Y = TT{idxest,responsenames};   % Estimation sample responses

xf = TT{idxfor,predictorname};
x = TT{idxest,predictorname};

% When estimating the model using estimate, specify a varm model template representing a VAR(4) model and the estimation sample response data Y as inputs. Specify the presample response data Y0 to initialize the model by using the 'Y0' name-value pair argument, and specify the estimation sample predictor data x by using the 'X' name-value pair argument. Y and x are synchronized data sets, while Y0 occurs during the previous four periods before the estimation sample starts.
% After estimation, you can forecast the model using forecast by specifying the estimated VARX(4) model object returned by estimate, the forecast horizon fh, and estimation sample response data Y to initialize the model for forecasting. Specify the forecast sample predictor data xf for the model regression component by using the 'X' name-value pair argument. Determine the predictive power of the estimation model by comparing the forecasts to the forecast sample response data YF.
% Copyright 2020 The MathWorks, Inc.