%% First example from 132MMO course

%% Input
I = load('shares_2014.dat');
[m,n] = size(I);
p = 30; % Required profit in 2014-2015 investement

%% Data analysis
ARR = zeros(m-1,n);

% Implements the formula written on whiteboard
for i=1:m-1
    ARR(i,:) = (I(i+1,:)-I(i,:))./I(i,:)*100; 
    % ./ apply division compentwise
end

ERR = mean(ARR); % Expect profit
R = cov(ARR); % Risk quantification

%% Prepare data for quadprog function
H = R;
f = zeros(n,1);
A = -ERR;
b = -p;
Aeq=ones(1,n);
beq=1;
lb=zeros(n,1);

x = quadprog(H,f,A,b,Aeq,beq,lb,[]);

%% Risk
.5*x'*R*x

%% Profit 
ERR*x

%% Reality
I_final = load('shares_real_2015.dat');

RR = (I_final-I(end,:))./I(end,:)*100; % True rate of return
RR*x % True profit


