RSS Feed

Simulated Random Walk in MATLAB

0
simRandomWalk

Put in simple terms, a Random Walk basically involves taking successive random steps and tracing the trajectory. I adapted the example from part one of Wilmott on Quantitative Finance and wrote a quick MATLAB script to simulate a simple random walk. Basically flip a coin if it is heads multiply the equity seed by 1.01 and if its tails multiply by 0.99.

Results

The graphs below show succesive runs of the script. I simulated 10,000 coin tosses in each test.

Sim one: You flipped 5069 heads & 4931 tails

Random Walk One

Sim Two: You flipped 4946 heads & 5054 tails

Random Walk 2 MATLABSim Three: You flipped 5026 heads & 4974 tails

Random Walk 3 MATLABSim Four: You flipped 5042 heads & 4958 tails

Random Walk 4 MATLABMATLAB Code

Writing the code in MATLAB is very straightforward I wrote the code in less then five minutes so it is a bit rough around the edges. I probably could refactor it but it does the job.

% Simple Simulated Random Walk Adapted 
% from part 1 Paul Wilmott on Quant Fin

% create matrix with random int either 1 or 2
randMat = randi(2,10000,1);
randEquity = [1:10000];

headCount = 0;
tailCount = 0;
equitySeed = 100.00;

for i=1:10000
    if randMat(i)==1
        % we flipped a heads
        headCount = headCount + 1;
        equitySeed = 1.01 * equitySeed;
        randEquity(i) = equitySeed;
    else
        % must have flipped tails
        tailCount = tailCount + 1;
        equitySeed = 0.99 * equitySeed;
        randEquity(i) = equitySeed;
    end
end

fprintf('You flipped %i heads & %i tails\n', headCount, tailCount);
plot(randEquity);
title('\bf \fontname{Arial} \fontsize{16}Simulated Random Walk');
xlabel('\bf \fontname{Arial} \fontsize{12}Number of Coin Tosses');
ylabel('\bf \fontname{Arial} \fontsize{12}Price in ($)');

% clean-up
clear equitySeed headCount tailCount randMat i;

0 comments »

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trading Wisdom

One market paradigm that I take exception to is : Buy low and sell high. I believe far more money is made by buying high and selling at even higher prices. That means buying stocks that have already had good moves and have high relative strength – that is, stocks in demand by other investors. I would much rather invest in a stock that’s increasing in price and take the risk that it may begin to decline than invest in a stock that’s already in a decline and try to guess when it will turn around. — Richard Driehaus