ExampleCodeIV
Below you can find functions that, inter alia, deliver an IV estimate, perform a Hausmann test on endogeneity and a Sargan test on instrument validity.
IVest.m
This is the function that delivers IV parameter estimates. It will work for exactly and over-identified cases
function [biv,bse,r2] = IVest(y,x,z);
% This function performs an IV estimation
% input: y, vector with dependent variable
% x, matrix with explanatory variable (include vector of ones if
% you want constant
% z, matrix with instrumental variables (at least as many cols as x)
% output: biv, estimated parameters using IV
% bse, standard errors for biv
% r2, Rsquared
[n,kx] = size(x); % sample size - n, number of explan vars (incl constant) - kx
[n,kz] = size(z); % sample size - n, number of instrumental vars - kz
pz = z*inv(z'*z)*z'; % Projection matrix
xpzxi = inv(x'*pz*x); % this is also (Xhat'Xhat)^(-1)
biv = xpzxi*x'*pz*y; % IV estimate
res = y - x*biv; % IV residuals
ssq = res'*res/(n-kx); % Sample variance for IV residuals
s = sqrt(ssq); % Sample Standard deviation for IV res
bse = ssq*xpzxi; % Variance covariance matrix for IV estimates
bse = sqrt(diag(bse)); % Extract diagonal and take square root -> standard errors for IV estimators
ym = y - mean(y);
r2 = 1 - (res'*res)/(ym'*ym);
end