clear;
rng(1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This code is used to generate critical values for the CLR statistic \
% for various N with fixed T = 100 500
% the emprirical distribution of the test statistic under the null
% with various N and T

% we pre-calculate three sets of the CLR crtical values
% we fix K (number of factors) in the beginning
% (1) conventional asymptotics: critical values based on chi2 for various N
% (2) finite sample: critical values based on normal and wishart for fixed T and various N
% Given the insensitivity of the statistic to $r$, we fix the r and compare
% the differences for different sets of N and T
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% we pre-store the critical values for further use
% Input values N varies from 3 to asset_num
% T (sample zie),K (factor number)  is fixed
case_id=1; %1: conventional; 2: finite 
T=500;
K=1;

%
quan=0.95;
asset_num =45;
rdd_num=500000;
r=1.5;

if case_id==1
% (1) conventional asymptotics: critical values based on chi2 for various N
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


CLR_qunatile=NaN(asset_num,1);
for n=3:asset_num
    fprintf('%2.0f out of %2.0f\n', n, asset_num);
    N=n;
    CLR=NaN(rdd_num,1);
    
    parfor i=1:rdd_num
        CLR(i)=CLR_simu_dist(N,T,K,r,0);
    end
    CLR_qunatile(n)= quantile(CLR,quan);
    
end
num=(1:45)';
save CritivalValues_CLR_T500_asym.mat num CLR_qunatile
CLR_qunatile=CLR_qunatile(1:45);
figure()
plot(CLR_qunatile(1:45))

elseif case_id==2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% (2) finite sample: critical values based on normal and wishart for fixed T and various N
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLR_qunatile=NaN(asset_num,1);
for n=3:asset_num
    fprintf('%2.0f out of %2.0f\n', n, asset_num);
    N=n;
    CLR=NaN(rdd_num,1);
    
    parfor i=1:rdd_num
        CLR(i)=CLR_simu_dist(N,T,K,r,1);
    end
    CLR_qunatile(n)= quantile(CLR,quan);
    
end
num=(1:45)';
save CritivalValues_CLR_T500_finite.mat num CLR_qunatile
CLR_qunatile=CLR_qunatile(1:45);
figure()
plot(CLR_qunatile(1:45))



end