Simulated Random Walk in MATLAB

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.

MATLAB Simulation Results

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

Sim One: You flipped 5069 heads & 4931 tails

Sim One Simulated Random Walk

Sim Two: You flipped 4946 heads & 5054 tails

Sim Two Simulated Random Walk

MATLAB 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('Simulated Random Walk');
xlabel('Number of Coin Tosses');
ylabel('Price in ($)');

% clean-up 
clear equitySeed headCount tailCount randMat i;

MATLAB makes it very easy to quickly conduct experiments and run simulations. It would be far to time consuming to manually flip a coin 10,000 times. This quick example highlights how a simple random walk can look very similar to stock or security charts. It also shows how powerful MATLAB is as a learning and prototyping tool

No Responses

Leave a Reply