%% Dynamic Panel (Michele Piffer, LSE, 15/2/2012)
% as T increases, inconsistency of FE estimation goes to zero while 
% OLS remains biased


clc 
clear 

%% DGP

T = 5;  % if = 1, OLS consistent. If increases, inconsistency of FE disappears
N = 100; % total individuals
NT = N*T;

% error
u = 10*randn(NT,1); % if iid

c = 5*randn(N,1);
cc = kron(c,ones(T,1));

% dependent variable

y = zeros(NT,1);

alpha = 0.50; % if T=2, bias of FE is -(1-alpha)/2 = -0.75. if true is zero, FE gives -1/T

for i=2:NT
   y(i) = alpha*y(i-1) + cc(i) + u(i);
end

% plot(y)

ylag = [zeros(NT-1,1), eye(NT-1); zeros(1,NT)]*y;

% display('endogeneity problem')
% ylag'*cc/NT + (sum(ylag)/NT)*sum(cc)/NT 

%% OLS estimation

beta_OLS = (ylag'*ylag)^(-1)*ylag'*y

beta_OLSloop = [];
for i=10 : NT
    beta_OLSloop(i) = (ylag(1:i,:)'*ylag(1:i,:))^(-1)*ylag(1:i,:)'*y(1:i,1);
end

% figure(1)
% plot(beta_OLSloop), hold on
% plot(alpha*ones(1,length(beta_OLSloop)), 'r'), hold off

%% FE estimation

dummies = kron(eye(N),ones(T,1));
X = [ylag, dummies];

beta_FE = (X'*X)^(-1)*X'*y;
beta_FE = beta_FE(1)


