format long;
clear;
load ('SP500_sentment_new.mat', 'Mt','DataSize') 
load('anchoring.mat', 'Xmax','X52','Dt','It')
load technical.mat
load Para_sentiment.mat
load SP500_longer.mat

Switch1=3; %return with 3, 6, 9, 12 month horizon
if Switch1==3
    Rt=Rt3;
elseif Switch1==6
    Rt=Rt6;
elseif Switch1==9
    Rt=Rt9;
elseif Switch1==12
    Rt=Rt12;
end

A0=[ones(DataSize,1) Xmax];
X0=lscov(A0,X52);
X52Orthogonal=(X52-X0(1)-X0(2)*Xmax);

ParaTau=[6 9 12];
Mt1=zscore([Mt(1:end-1,ParaTau) X52Orthogonal MA(:,1:2)]); %standardized

Mt2=[Mt(1:end-1,ParaTau) X52Orthogonal MA(:,1:2)]; %non-standardized

size_tech=size(Mt1,2);

pi_tau=zeros(2,size_tech);
aligned_Mt=zeros(2,DataSize); % aligned_Mt(2,:)' is the aligned Mt
for i=1:size_tech
    A1=[ones(DataSize,1) Rt];
    pi_tau(:,i)=lscov(A1,Mt1(:,i));
end

for j=1:DataSize
    A2=[pi_tau(2,:)'];
    aligned_Mt(:,j)=lscov(A2,Mt1(j,:)');
end

aligned_Mt=zscore(aligned_Mt(2,:)');

aligned_Mt_test=zscore(Mt1*Mt1'*Rt*(Rt'*Mt1*Mt1'*Mt1*Mt1'*Rt)^(-1)*Rt'*Mt1*Mt1'*Rt);
std1=std(Mt1*Mt1'*Rt*(Rt'*Mt1*Mt1'*Mt1*Mt1'*Rt)^(-1)*Rt'*Mt1*Mt1'*Rt);
Weights1=Mt1'*Rt*(Rt'*Mt1*Mt1'*Mt1*Mt1'*Rt)^(-1)*Rt'*Mt1*Mt1'*Rt/std1;


%% regimes H and L

Switch=0; %0: Markov regime switch model; 1: Stambaugh_Yu_Yuan_JFE_12
if Switch==0
    STATES=(sign(pi1(2:end)-0.5)+1)/2; %STATES=1 if at state 1;  STATES=0 if at state 2
    Number_High=high_m;
elseif Switch==1
    STATES=(RegimeSYY+9)/12; %STATES=1 if at state 1 (high);  STATES=0 if at state 2 (low)
    Number_High=round(DataSize/2);
end
RtH=zeros(Number_High,1);
MtH1=zeros(Number_High,1);
RtL=zeros(DataSize-Number_High,1);
MtL1=zeros(DataSize-Number_High,1);
NumberH=0;
NumberL=0;
for i=1:DataSize
    if STATES(i)==1
        NumberH=NumberH+1;
        RtH(NumberH)=Rt(i);
        MtH1(NumberH,:)=aligned_Mt(i,:);
    elseif STATES(i)==0
        NumberL=NumberL+1;
        RtL(NumberL)=Rt(i);
        MtL1(NumberL,:)=aligned_Mt(i,:);
    end
end
aligned_Mt_H=zscore(MtH1); %standardized
aligned_Mt_L=zscore(MtL1); %standardized



save('NONFUND_variable_long_horizon.mat','aligned_Mt','Rt','aligned_Mt_H','RtH','aligned_Mt_L','RtL','DataSize','Number_High','Mt1','Switch1') 


