% PCA analysis for SP500
N_data = 251;
price_data = xlsread('data_proj4');
return_data = (price_data(1:N_data,3:13)-price_data(2:N_data+1,3:13))./price_data(2:N_data+1,3:13);
Vcov = cov(return_data(:,1:10));
volatility = diag(Vcov);
[Veig,D] = eig(Vcov);
for k=1:10
    eigenmax(k) = D(11-k,11-k);
end
figure
bar(eigenmax);
ylabel('\lambda');
title('eigenvalues from max to min');
% for k=1:10
%    fprintf('Eigenvalues of covariance matrix are %10.6f\n',D(k,k));
% end

eigenpf1 = Veig(:,9)./volatility;
wsum = sum(eigenpf1);
eigenpf1 = eigenpf1/wsum;

return_port = zeros(N_data,1);
for k=1:10
    return_port = return_port+eigenpf1(k)*return_data(:,k);
end

price_port = 200*ones(N_data+1,1);
for k=N_data:-1:1
    price_port(k)=price_port(k+1)*(1+return_port(k));
end

figure
plot(price_data(:,1),price_data(:,13),'-',price_data(:,1),price_port,'-');
xlabel('t');
ylabel('price');
legend('SPY','Eigenportfolio');
title('Price Comparisons');