%% Endogeneity of a Regressor (Michele Piffer, LSE, 13/12/2011)

% if DGP has a constant term and one endogenous regressor, show that if
% the regressor is positively correlated to the error, the estimator
% for the regressor is positively biased 

clc 
clear % get rid of data already in matlab

%% Generate DGP

n = 1000;                             % number of rows
x1 = ones(n,1);

epsilon = randi([-15 15], n, 1);     % zero in expected value
vareps = sum(epsilon.^2)/n-(sum(epsilon)/n)^2;

rho = 50;                            % cov(x,epsilon)
meanx2 = 15;
x2 = (rho/vareps)*epsilon + 10*randn(n,1) + meanx2;    

%samplecovariance
display('Sample endogeneity of the regressor')
epsilon'*x2/n - (sum(epsilon)/n)*(sum(x2)/n)   % yes, approximately equals rho

X = [x1 x2];     

beta_true = [2 5]';                  % true parameters

y = X*beta_true + epsilon; 

%% Estimate model using X and y

beta_hat = (X'*X)^(-1)*X'*y;         % OLS regressors

display('true')
beta_true'

display('Direction of the bias')
beta_hat'
