load AAPL.mat;
dd = AAPL;
n=size(dd,1);
date = dd(:,1);
n
sp = dd(:,5);
sp_0 = sp(2:n,1);
sp_1 = sp(1:n-1,1);
r = log (sp_0./sp_1);

% Defining regressors 
r_l2 = r(1:n-3);
r_l1 = r(2:n-2);

% Defining regressands 
r = r(3:n-1);


bfone = ones(size(r,1),1);
Reg1 = [bfone r_l1 r_l2];

% Least squares estimator
phi_hat1 = (Reg1'*Reg1)\(Reg1'*r);
phi_hat1

% Forecast

rhat = Reg1*phi_hat1;

%Variance estimator 
sigma_hat21 = (1/size(r,1))*(r-Reg1*phi_hat1)'*(r-Reg1*phi_hat1);
sigma_hat21

% Covariance matrix estimator
var_phi1 = inv( (1/size(r,1))*(Reg1'*Reg1));
var_phi1
var_phi = sigma_hat21*var_phi1;
var_phi
%Hypothesis testing

% Test 2.2

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


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

critical3 =  chi2inv(0.95,2);
[test_st critical3]



% Test on item h

R1 = [0 0 1];
g1 = 0;


aux_1=(R1*var_phi*R1')\(R1*phi_hat1-g1);
test_st1=size(r,1)*(R1*phi_hat1-g1)'*aux_1;

critical1 = chi2inv(0.95,1);

[test_st1 critical1]


fdata = sortrows([r rhat],1);

%Correlation in item i
corr(fdata(:,1),fdata(:,2))

% Plot

figure(1)
plot(fdata(:,1),fdata(:,2),".")
box off
grid off
xlabel('Log returns')
ylabel('Forecasted Log returns')
title('Log-returns agains forecast')


chi2inv(0.95,2)
chi2inv(0.95,1)
chi2inv(0.975,1)
norminv(0.95)
norminv(0.975)



