clear;clc


%% Generate the spreadsheet "factor weights 48" in "figures.xlsx"

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

[~, abn] = xlsread('Portfolio_ret.xlsx','Anomaly','B2:BS2','basic'); 
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);
 
 
Rtarget = R48;
[w_rra, w_pls, w_pca]=extract_factors_weight(Rtarget,G,5);
rra = G*w_rra;
pls = G*w_pls;
pca = G*w_pca;

FF5=f5(:,1:5);
[A,B,ccr] = canoncorr(FF5,rra);

j = 1;
ypca = -w_pca(:,j)/(norm(w_pca(:,j))); 
ypls = -w_pls(:,j)/(norm(w_pls(:,j))); 
yrra = -w_rra(:,j)/(norm(-w_rra(:,j)));
out1=[ypca,ypls,yrra];

%% 2nd factor
j = 2;
yrra2 = -w_rra(:,j)/(norm(-w_rra(:,j)));

%% 3rd factor
j = 3;
yrra3 = -w_rra(:,j)/(norm(-w_rra(:,j)));


%% 4th factor
j = 4;
yrra4 = -w_rra(:,j)/(norm(-w_rra(:,j)));


%% 5th factor
j = 5;
yrra5 = -w_rra(:,j)/(norm(-w_rra(:,j)));

out=[out1,yrra2,yrra3,yrra4,yrra5];
%output out to excel for plot figures
