clear;clc
%% For Table 4

%%  Use the R codes "weighting matrix" to get new W2 following Fan, Liao, and Mincheva (2013),
%% new W2 are saved in 'S2_1.xlsx' 'S2_3.xlsx' 'S2_5.xlsx' 'S2_6.xlsx'
%% change weighting matrix
S2(:,:,1)= xlsread('S2_1.xlsx','Sheet1','A2:CB81','basic'); 
S2(:,:,2)= xlsread('S2_3.xlsx','Sheet1','A2:CB81','basic'); 
S2(:,:,3)= xlsread('S2_5.xlsx','Sheet1','A2:CB81','basic'); 
S2(:,:,4)= xlsread('S2_6.xlsx','Sheet1','A2:CB81','basic');

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);

z = xlsread('Portfolio_ret.xlsx','Anomaly','A3:BS518','basic'); 
tt = find(z(:,1)>=st_date & z(:,1)<=et_date);
f5 = z(tt,2:7)/100; % benchmark: 1, 3, 5, 6 factors
G = z(tt,2:end)/100;
[T,L] = size(G);


%% 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);
 

%% 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);

%% individual 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)]; 

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];

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

 
for j =1:size(NF,2); % No. of factors
    s2=S2(:,:,j);
 
 rra48  = func_rraff_weightchange(R48,G,NF(j),s2); % R48 are basis assets
 ff= rra48;
    
      res  = performance_portfolio(R48, ff); % OUTres = [MPE, TotalR2, SR, A2R];
      MPE(j,1) = res(1); TR2(j,1) = res(2); 
         
      res = performance_portfolio(R202, ff);
      MPE(j,2) = res(1); TR2(j,2) = res(2); 

      res = performance_stock(tdate, ret_all, ff);
      MPE(j,3) = res(1); TR2(j,3) = res(2); 
      
      res = performance_stock(tdate, ret_but, ff);
      MPE(j,4) = res(1); TR2(j,4) = res(2);      
  
end

%% Table 4 Performance of RRA factors: An alternative estimation
Table4=[MPE',TR2']


 
