% Recall that net returns take values in [-1,infty)
% Let there be three assets 
% mu is given

mu=[0.07;0.12;0.09];

% Omega is given

Omega = [0.12 0.02 0.01 ;
         0.02 0.3 0.03;
          0.01 0.03 0.18 ];
     
% A vector of ones

bone = ones(length(mu),1);

% Inverse of Omega

iomega=inv(Omega);

A=0.5*bone'*iomega*mu;
B=0.5*mu'*iomega*mu;
C=0.5*bone'*iomega*bone;
D=A^2-B*C;

g=(A*iomega*mu-B*iomega*bone)/(2*D);
h=(A*iomega*bone-C*iomega*mu)/(2*D);

%mup1 is the targeted expected return on the portfolio of risky assets

mup1 = 0.08;

% w is the lowest variance portfolio with expected return mup1

w = g+h*mup1;
w

% the minimum variance associated with this portfolio is
varp = w'*Omega*w;
varp

% mumin is the expected return on the minimum variance portfolio
mumin =-( g'*Omega*h)/(h'*Omega*h);
mumin

%varmin is the minimum variance portfolio

varmin = g'*Omega*g+(g'*Omega*h)*mumin;
varmin

%wmin are the weights on the minimum variance portfolio

wmin = g+h*mumin;
wmin

mup = linspace(min(mu),max(mu),50);
sigp = zeros(1,50);
for i=1:50;
    wp=g+mup(i)*h;
    sigp(i)=sqrt(wp'*Omega*wp);
end;

plot(sigp,mup)

%risk free rate of return is muf

muf = 0.02;

wbar = iomega*(mu-bone*muf);
cp = (mup1-muf)/((mu-bone*muf)'*iomega*(mu-bone*muf));

%Optimal weights for the portfolio that combines risk free asset with 3
%other risk bearing assets

wopt = wbar*cp;
wopt
sum(wopt)

%Tangency portfolio

wt=wbar/(bone'*wbar);

%weight on the risk free asset

wrf=1-(bone'*wopt);
wrf
% variance of the optimal portfolio

varopt = ((mup1-muf)^2)/((mu-bone*muf)'*iomega*(mu-bone*muf));
varopt
