clear;clc
%% For Table 6

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

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

NF = [1 3 5 6];

%% Target = R48
Rtarget = R48;
N = size(Rtarget,2);
std0 = std(Rtarget)';
Alpha = [zeros(N,1), std0*[0.5, 1, 1.5]/12];
NoFF = size(Alpha,2);

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 i = 1:size(Alpha,2)
    for j =1:size(NF,2);
      ff = func_rraff_PErestrict(Rtarget,G,NF(j), Alpha(:,i)); 
      
      res  = performance_portfolio(R48, ff); % 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, ff);
      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, ff);
      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, ff);
      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;
end

%% Table 6 Performance of RRA factors estimated with a pricing error restriction
Table6 = [[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)]];










