%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Econometrics 2
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This code estimates the Euler equation of Hansen and Singelton using IV.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear
clc

% Load the data.

load data                                                                   % c is c(t)/c(t-1), re is the value weighted average return, 
                                                                            % rf is the T-bill rate.

T = size(c,1);                                                              % Number of observations.

x = [ones(T-1,1) rf(2:T)];                                        
y = c(2:T);

z = [ones(T-1,1) c(1:T-1) re(1:T-1)];                                       % Instrument matrix.
pz = z*inv(z'*z)*z';

% IV Estimation.

b_iv = inv(x'*pz*x)*x'*pz*y;

u = y - x*b_iv;
s2 = (u'*u)/(T-size(x,2));

vcmat = s2*inv(x'*pz*x);
se = sqrt(diag(vcmat));

% Display the results.

fprintf('--------------------------------------------------------------\n')
fprintf('IV estimates. \n')
fprintf('--------------------------------------------------------------\n')
fprintf('\n')

fprintf('           b        SE   \n')
fprintf('b0      %0.4f       %0.4f     \n', b_iv(1), se(1))
fprintf('b1      %0.4f       %0.4f     \n', b_iv(2), se(2))
