Code covered by the BSD License  

Highlights from
Enhancing e-Infrastructures with Advanced Technical Computing: Parallel MATLAB® on the Grid

Exercise6_interactive_spmd.m
%% 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.


%% Clear out all old variables
clear all

%% Opening a matlabpool

if matlabpool('size') == 0
    matlabpool open 2
else
    warning('MATLAB:poolOpen', 'matlabpool already open')
end

%% Loading in historical stock data 

numFiles = 4; % number of files to use
numStocks = 200; % number of stocks to use
numPoints = 10;  % number of points on the efficency frontier

x = Exercise6_loadReturns(numFiles,numStocks);

%% Calculating the covariance matrix 

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);

%% Visualization

fig2 = figure;
Exercise6_plot_optim(fig2, risk, ret);

%% Close the matlabpool 

if matlabpool('size') ~= 0
    matlabpool close
else
    warning('MATLAB:poolClose', 'matlabpool already closed')
end

Contact us at files@mathworks.com