  %This code estimates an AR(3) model by least squares with some hypothesis
%testing in the end.

% sandp.mat is a MATLAB data set whose 5th column contains daily closing of
% the S&P 500 index from 01.03.2000 - 07.27.2011.

load sandp.mat;
dd = sandp;
n=size(dd,1);
date = dd(:,1);

sp = dd(:,5);
sp_0 = sp(2:n,1);
sp_1 = sp(1:n-1,1);
r = log (sp_0./sp_1);

r_3 = r(1:n-4);
r_2 = r(2:n-3);
r_1 = r(3:n-2);
r= r(4:n-1);

% t_ is a time index

t_ = (1:1:size(r,1));


% R is the matrix of regressors

bfone = ones(size(r,1),1);

Reg = [bfone r_1 r_2 r_3];

% phi_hat is the least squares estimate

phi_hat = (Reg'*Reg)\(Reg'*r);
phi_hat
% sigma_hat2

sigma_hat2 = (1/size(r,1))*(r-Reg*phi_hat)'*(r-Reg*phi_hat);
sigma_hat2
% Variance of phi_hat

var_phi = inv( (1/size(r,1))*(Reg'*Reg));
var_phi = sigma_hat2*var_phi;
var_phi

%Hypothesis testing

R = [0 0 0 1];
g_ = 0;

%R = [0 1 0 0; 
 %    0 0 1 0; 
  %   0 0 0 1];
%g_ = [0;0;0];

aux_=(R*var_phi*R')\(R*phi_hat-g_);
test_st=size(r,1)*(R*phi_hat-g_)'*aux_;

test_st

% test_t should be compared to a critical value associated with a
% chi_square with 1 degree of freedom if one restriction is being imposed

critical1 = chi2inv(0.95,1);

critical1

critical3 =  chi2inv(0.95,3);

%critical3



% Figure plots daily returns on the S&P 500

figure(1)
plot(t_,r)
box off
grid off
xlabel('Time Index (days)')
ylabel('Log returns')
title('Log-returns on S&P500 from 01.03.2000 - 07.27.2011')





