Random Walk Plots In Python

Hi there. In this page, I play around with plotting random walk paths in the Python programming language. The code is heavily based from the book Data Analysis In Python by Wes McKinney. In the book, there is no code for the plots. I add in the code for plots.


Plotting A Single Random Walk Path

To start import random, numpy as np, seed from random and matplotlib’s pyplot as plt.



Having a random seed allows for the results to be reproduced. Not having one will change the results and plots every time random functions are used.



For simplicity, the random walk starts at the position of $y = 0$. The walk list will store the position of the random walk after each step/jump. The number of steps is 1000.


In a random walk jump, the jump either goes up by one or down by one. This jump is done with the use of an if-else statement in one line within the for loop. Each step is added to the random walk’s position.




Plotting The Result

Now that the random walk positions have been obtained after each step, a plot can be generated with matplotlib’s pyplot. You can use plt.plot(walk) on its own but I wanted to add in some labels and a title.



Basic Statistics On The Random Walk

From the generated random walk path, some basic statistics on it can be obtained with the use of Python’s Numpy functions.



Multiple Random Walk Paths

In the previous section, only one random walk path was generated. For multiple random walk paths, the code would need some adjustments.

In the code below, the number of random walk paths and the number of steps for each random walk are specified. Each random number is generated through Numpy’s randint (which is different from random’s randint function).

In the steps variable, any draws that are a 1 stay a 1 for an up jump and anything other than a 1 from a number in draws turns into a -1 with the use of Numpy’s where function. (The where function operates like an if else statement.) The random walk positions are in the walks variable.



Plotting the results for multiple random walks is not much different than before in terms of the code.



Like in the previous section, you can gather some basic statistics with the use of Numpy functions.



Leave a Reply