clear
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This code produces Table 1 of Hansen and Lee (forthcoming at Econometrica)
% "Inference for Iterated GMM Under Misspecification"
%
% For errors and/or comments please contact Seojeong (Jay) Lee at
% jay.lee@unsw.edu.au
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

global x

% Sample size
n = 250;

% True value
b = 0;

% Number of Monte Carlo repetition
r = 10;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for mis = 1:6
    if mis == 1
        a = -0.3;
    elseif mis == 2
        a = -0.25;
    elseif mis == 3
        a = 0;
    elseif mis == 4
        a = 0.5;
    elseif mis == 5
        a = 1;
    elseif mis == 6
        a = 2;
    end

sigx2 = a + 1;

bhat = zeros(r,1);
s = zeros(r,1);
s0 = zeros(r,1);
J = zeros(r,1);
pv = zeros(r,1);
numit = zeros(r,1);
Size_t = zeros(3,1);
Size_t0 = zeros(3,1);

for iter = 1:r

    x = randn(n,1).*(sigx2)^0.5;

    b0 = mean(x);
    [bhat(iter),s(iter),V,s0(iter),V0,J(iter),pv(iter),numit(iter)] = iterated_gmm_nl_cen(b0);
    
    t = (bhat(iter)-b)/s(iter);
    t0 = (bhat(iter)-b)/s0(iter);
    
    if isnan(bhat(iter))==0
        Size_t = Size_t + (abs(t)>norminv([0.995 0.975 0.95]',0,1));
        Size_t0 = Size_t0 + (abs(t0)>norminv([0.995 0.975 0.95]',0,1));
    end

end

Bias_bhat = nanmean(bhat)-b;
SD_bhat = nanstd(bhat);
Mean_s = nanmean(s);
Mean_s0 = nanmean(s0);
Size_t = Size_t/r;
Size_t0 = Size_t0/r;
Reject_J = nanmean(pv < 0.05);
Ratio = Mean_s/SD_bhat;
Ratio0 = Mean_s0/SD_bhat;

Median_numiter = median(numit);
Freq_NonConv = sum(isnan(bhat));

tb = 1;
fprintf(tb, '& %8.4f & %8.4f & %8.4f & %8.4f & %8.4f & %8.4f & %8.4f & %8.4f\\\\ \n', a,Ratio,Ratio0,Size_t(2),Size_t0(2),Reject_J,Median_numiter,Freq_NonConv*100/r);

end
