%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This script uses any Y matrix of input series and extends it forward
% for 12 quarters using an out of sample dynamic simulation
% from a VAR(p) process
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

n = size(Y,2);

% Create X and Y Matrices

Y_reg = nan(size(Y,1)-p,n);
X_reg = ones(size(Y,1)-p,1);

for depvar = 1:n
         
    Y_reg(:,depvar) = Y(p+1:end,depvar);
    
    for lags = 1:p
     
        X_reg = [X_reg,Y(p+1-lags:end-lags,depvar)];
    
    end
   
end


% Perform regression  

Beta = inv(X_reg'*X_reg)*(X_reg'*Y_reg);


% Forecast series

Y_extended = Y;

for h = 1:12

    Y_temp = Y_extended;
    
    for depvar = 1:n
       
        Y_temp(size(Y_extended,1)+1,depvar) = Beta(1,depvar);
        
    end
    
    for depvar = 1:n
    
        for indepvar = 1:n    

            for lags = 1:p

                Y_temp(end,depvar) = Y_temp(end,depvar) + Beta(1+lags+4*(indepvar-1),depvar)*Y_temp(end-lags,indepvar);
                Y_extended = Y_temp;  

            end    

        end    

    end    

end


clear Y_reg X_reg Beta Phi_i depvar indepvar