clear;clc
%% For Table 8

st_date = 197401; et_date = 201612;
z = xlsread('Portfolio_ret.xlsx','FF5','A2:I653','basic'); 
tt = find(z(:,1)>=st_date & z(:,1)<=et_date);
rf = z(tt,7)/100;
mkt = z(tt,2)/100;
tdate = z(tt,1);
yy = floor(tdate/100); mm = floor(tdate - yy*100);


%% Factor proxies G: test assets
z = xlsread('Portfolio_ret.xlsx','FF48vw','A3:AW530','basic'); 
tt = find(z(:,1)>=st_date & z(:,1)<=et_date);
N_G = size(z,2)-1;
G48 = z(tt,2:end)/100 - rf*ones(1,N_G);
[T,L48] = size(G48);


%% 48 Industry 
z = xlsread('Portfolio_ret.xlsx','FF48vw','A3:AW530','basic'); 
tt = find(z(:,1)>=st_date & z(:,1)<=et_date);
N = size(z,2)-1;
R48 = z(tt,2:end)/100 - rf*ones(1,N);

%% 70G
z = xlsread('Portfolio_ret.xlsx','Anomaly','A3:BS518','basic'); 
tt = find(z(:,1)>=st_date & z(:,1)<=et_date);
R80 = z(tt,2:end)/100;

 
%% 202 target
z = xlsread('Portfolio_ret.xlsx','Dacheng202vw','A3:GU554','basic'); 
tt = find(z(:,1)>=st_date & z(:,1)<=et_date);
N = size(z,2)-1;
R202 = z(tt,2:end)/100 - rf*ones(1,N);

%% all-but-micro stocks
load stock_ret_nomicro.mat;
ret = st_dataset; clear st_dataset;
ret = double(ret); % permno, year, month, xret, me, exchcd
ret_but = [ret(:,1), ret(:,2)*100+ret(:,3), ret(:,4)]; 

%% all stocks
load stock_ret.mat;
ret = st_dataset; clear st_dataset;
ret = double(ret); % permno, year, month, xret, me, exchcd
ret_all = [ret(:,1), ret(:,2)*100+ret(:,3), ret(:,4)]; 


  
NF = [1 3 5 6]; % number of factors
NoFF = 3; %

MPE = nan(NoFF,size(NF,2),4);  TR2 = nan(NoFF,size(NF,2),4);  
SR = nan(NoFF,size(NF,2),4);   A2R = nan(NoFF,size(NF,2),4);   

 
for j =1:size(NF,2); % No. of factors

[w_pca_48, w_pca2_48, w_pca3_48]=extract_factors_weight_pca(G48,NF(j));
pca1G48 = G48*w_pca_48;
pca2G48 = G48*w_pca2_48;
pca3G48 = G48*w_pca3_48;

FFs3 = nan(T,NF(j),NoFF);
FFs3(:,:,1)  =  pca1G48; 
FFs3(:,:,2)= pca2G48;
FFs3(:,:,3)= pca3G48; 

 for i = 1:NoFF;  % No. of models
      ff3=FFs3(:,:,i);      
      
       res  = performance_portfolio(R48, ff3); % OUTres = [MPE, TotalR2, SR, A2R];
      MPE(i,j,1) = res(1); TR2(i,j,1) = res(2); 
      SR(i,j,1)=res(3); A2R(i,j,1) = res(4);
      

      res = performance_portfolio(R202, ff3);
      MPE(i,j,2)=res(1); TR2(i,j,2)= res(2); 
      SR(i,j,2) =res(3); A2R(i,j,2)= res(4);
      
      res = performance_stock(tdate, ret_all, ff3);
      MPE(i,j,3)=res(1);  TR2(i,j,3)= res(2); 
      SR(i,j,3) =res(3); A2R(i,j,3)= res(4);    
      
      res = performance_stock(tdate, ret_but, ff3);
      MPE(i,j,4)=res(1);  TR2(i,j,4)= res(2); 
      SR(i,j,4) =res(3); A2R(i,j,4)= res(4);    
          
    end
    clear ff FFs;
end

%% Table 8 Performance of alternative PCA factors
Table8 = [[MPE(:,:,1),TR2(:,:,1)];nan(1,8);...
    [MPE(:,:,2),TR2(:,:,2)];nan(1,8);...
    [MPE(:,:,3),TR2(:,:,3)];nan(1,8);...
    [MPE(:,:,4),TR2(:,:,4)]];
 