Parallelizing multiple iterations and randperm for a Monte Carlo simulation
Show older comments
I have a function which randomly picks stocks to buy, subject to the constraint of a fixed number of holding periods and fixed number of stocks that can be bought at any one time. The actual function is as follows:
function profit=monteCarloSim(stockPrices,numHoldingPeriods,numStocks,numSimuls)
[rows,cols] = size(stockPrices);
stockReturns = diff(stockPrices);
profit = zeros(numSimuls,1);
parfor i=1:numSimuls
buyWeights = zeros(rows-1,cols);
buySignal = randperm(rows-1,numHoldingPeriods);
buyRandomAssetPicks = randperm(cols, numStocks);
buyWeights(buySignal,buyRandomAssetPicks)=1/numStocks;
portfolioReturns = sum(stockReturns.*buyWeights,2);
profit(i) = sum(portfolioReturns);
end
end
I was planning to limit the number of operations in the loop by assigning each iteration of buyWeights to a 3D matrix. This way, I would take the portfolioReturns and profits(i) steps out of the loop, and completely vectorize them.
However, this approach becomes complicated when I have a huge number of simulations and a large data set, because there's not enough memory to store the whole 3D matrix. So I have to come up with a few extra steps to manage memory, e.g. build smaller chunks of the 3D matrix iteratively.
Even if I had the memory to do the 3D matrix approach, I'll still have to iterate the randperm function. I can't find a function to repeat this more effectively and I'm still a novice at using bsxfun.
Is there a way to speed this function up? I also have a good number of GPU cores, if a gpuArray method helps.
Thanks in advance!
Accepted Answer
More Answers (1)
Edric Ellis
on 25 Sep 2012
2 votes
If you take computations out of the PARFOR loop, then even if they are vectorized, they are no longer operating in parallel so it may not be faster. The two cases that you are considering both appear to involve transferring much more data from outside the PARFOR loop to be used inside it. This again will add overhead. Consider simply the 'profit(i)' calculation. Currently, the PARFOR loop only has to return a numSimuls-by-1 array. If you could return 'portfolioReturns' for summation outside the loop, you'd need to return numSimuls-by-(rows-1) elements. This extra data transfer might easily outweigh the benefit of performing a single call to SUM.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!