%% Problem Set 7, question 3 (Michele Piffer, LSE, 15/11/2011)
% Omitted variable bias

% Play with covariance of regressors and true beta to show that 
% the effect of the bias depends on the sign of the covariance
% and on true beta of the omitted variable

clc 
clear            % get rid of data already in matlab


%% Generate DGP

n = 1000;                       % number of rows

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

rho = 12;                       % cov(x1,x2)
x2 = (rho/varx1)*x1 + 10*rand(n,1);    % coefficient equals covariance/variace

%samplecovariance
x1'*x2/n - (sum(x1)/n)*(sum(x2)/n)   % yes, approximately equals rho

X = [x1 x2];

epsilon = randn(n,1);            % true errors

beta_true = [2 5]';              % true parameters, which you want to estimate

y = X*beta_true + epsilon; 

%% Estimate mode

beta_hat = (X'*X)^(-1)*X'*y;     % using both variables
beta_omit = (x1'*x1)^(-1)*x1'*y;     % omitting x2

display('true')
beta_true'

display('not omitting x2')
beta_hat'

display('omitting x2')
beta_omit' 

display('note, sign of the bias is sign of rho*beta_true2. It makes sense')

