% This script performs the BL optimization and makes a comparison with the
% market neutral porfolio.
% For more details go to "www.gerardoferrara.com", by G. Ferrara.

clc; clear; close all;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MKT_NEUTRAL=[0.1 0.55 0.05 0.093 0.144 0.03 0.012 0.021]';

figure(1)
pie(MKT_NEUTRAL)
title('Market Nutral Adjusted Portfolio')

RETURNS=xlsread('database.xls', 'Series','b2:i22')

COV=cov(RETURNS);

RISK_FREE=0.03;

VAR_NEUTR=MKT_NEUTRAL'*COV*MKT_NEUTRAL;

LAMBDA=(0.06-RISK_FREE)/VAR_NEUTR;

EXP_RET_MKT_NEUTRAL=COV*MKT_NEUTRAL*LAMBDA+RISK_FREE;

figure(2)
bar(EXP_RET_MKT_NEUTRAL)
title('Market Neutrsl Expected REturns')
grid on

LAMBDA2=(0.05-RISK_FREE)/VAR_NEUTR;
EXP_RET_MKT_NEUTRAL2=COV*MKT_NEUTRAL*LAMBDA2+RISK_FREE;


COMPARISON=[EXP_RET_MKT_NEUTRAL EXP_RET_MKT_NEUTRAL2];

figure(3)
bar(COMPARISON)
title('Results of first and second reverse optimization')
grid on


MACRO_PREMIUM=[0 0.003 0.0045 0.045 0.045 0.045 0.045 0.045];


LAMDA_CHOSE=(MKT_NEUTRAL'*MACRO_PREMIUM')/VAR_NEUTR

EXP_RET_MKT_NEUTRAL_END=COV*MKT_NEUTRAL*LAMDA_CHOSE+RISK_FREE;
RISK_PREMIUM_MKT_NEUTRAL=COV*MKT_NEUTRAL*LAMDA_CHOSE;

[RISK RETURN WEIGHTS]=portopt(EXP_RET_MKT_NEUTRAL_END,COV, 100);


figure(4)
subplot(1,2,1)
pie(MKT_NEUTRAL)
subplot(1,2,2)
pie(WEIGHTS(27,:))


TAU=1/21;


P=[0 0 0 0 -1 1 0 0;
    0 0 0 1 0 0 0 0];

Q=[0.04; 0.09];


C=[0.04;0.04]; %Omega

OMEGA=[(1/C(1,1)-1)*P(1,:)*TAU*COV*P(1,:)', 0;0, (1/C(2,1)-1)*P(2,:)*TAU*COV*P(2,:)'];

REND_BLACK_LITTERMAN=(inv(inv(TAU*COV)+P'*inv(OMEGA)*P))*(inv(TAU*COV)*EXP_RET_MKT_NEUTRAL_END+P'*inv(OMEGA)*Q);


COMPAR_REND_ATT=[EXP_RET_MKT_NEUTRAL_END REND_BLACK_LITTERMAN];


figure(5)
bar(COMPAR_REND_ATT)
title('E(r) market neutral versus B-L')
grid on



[RISK1 RETURN1 WEIGHTS1]=portopt(REND_BLACK_LITTERMAN,COV, 100);

[NUN, NUN1, NAMETEXT]=xlsread('database','Series','B1:I1');


A=0;
B=1;

figure(6)
subplot(2,1,1)
area(WEIGHTS)
ylim([0 1])
subplot(2,1,2)
area(WEIGHTS1)
ylim([0 1])
title('Composition mkt neutr versus B-L')
legend1 = legend(NAMETEXT,'Location','SouthOutside')



