%% Portfolio Optimization Demo (with Distributed Arrays and SPMD)
% This demo calculates returns the risk-return relationship in the stock
% portfolio that is optimal in the mean-variance sense. covMat and expRet
% are the covariance and mean returns of a collection of stocks and muVec
% is a vector of desired returns.
%
% The covariance matrix (covMat) is calculated using distributed arrays. In
% this case the large data set is caused having many thousands time points
% for each stocks. In this case, we may be able to fit all data in a single
% machine for demostration purposes using local workers. However, it is
% easy to imagine that for more time points or more stocks, you may reach
% the limit on your single machine.
%
% Once the covariance matrix is created, since it is N x N where N is just
% the number of stocks, it can be held in a single computers memory and
% used locally.
%
% Copyright 2008 The MathWorks, Inc.
% $Revision: 1.1.6.1 $ $Date: 2007/11/09 20:04:57 $
% $Revision: modified to use distributed arrays, S.Zaranek, 2008/29/09 $
%% Clearing out all old variables.
%% Loading in historical stock data
x = Exercise6_loadReturns(numFiles,numStocks);
%%
spmd
[n,m] = size(x);
display(size(x));
% calculating the covariance and expected return
expRet = sum(x)/m;
expRet = gather(expRet);
x = bsxfun(@minus,localPart(x),sum(localPart(x),1)./m); % Remove mean
x = codistributed(x, codistributor('1d',1));
covMat = (x' * x) / (m-1);
covMat = gather(covMat,1);
end
%% Calculating range and points along the efficency frontier
expRet = expRet{1}; % getting data back from workers
covMat = covMat{1}; % getting data back from workers
retRange = [min(expRet(expRet > 0)) max(expRet)];
rangeFudge = abs(diff(retRange))/20; % a little above and below the range
retRange = retRange + [rangeFudge -rangeFudge];
muVec = linspace(retRange(1), retRange(2), numPoints); % points along frontier
%% Find the frontier for the stock portfolio
%
% This function uses a parfor. You can combine parfor and spmd in the same
% program along with serial code.
[risk, ret] = Exercise6_task_optim(covMat, expRet, muVec);
%% Or could run the version using parfor that we created earlier.
% You can combine parfor and spmd in the same script along with serial
% code!
clearvars -except risk ret