This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.

13.3. Simulating a Brownian motion

  1. Let's import NumPy and matplotlib.
In [ ]:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
  1. We will simulate Brownian motions with 5000 time steps.
In [ ]:
n = 5000
  1. We simulate two independent one-dimensional Brownian processes to form a single two-dimensional Brownian process. The (discrete) Brownian motion makes independent Gaussian jumps at each time step (like a random walk). Therefore, we just have to compute the cumulative sum of independent normal random variables (one for each time step).
In [ ]:
x = np.cumsum(np.random.randn(n))
y = np.cumsum(np.random.randn(n))
  1. Now, to display the Brownian motion, we could just do plot(x, y). However, the result would be monochromatic and a bit boring. We would like to use a gradient of color to illustrate the progression of the motion in time. Matplotlib forces us to use a small hack based on scatter. This function allows us to assign a different color to each point at the expense of dropping out line segments between points. To work around this issue, we interpolate linearly the process to give the illusion of a continuous line.
In [ ]:
k = 10  # We add 10 intermediary points between two 
        # successive points.
# We interpolate x and y.
x2 = np.interp(np.arange(n*k), np.arange(n)*k, x)
y2 = np.interp(np.arange(n*k), np.arange(n)*k, y)
In [ ]:
# Now, we draw our points with a gradient of colors.
plt.scatter(x2, y2, c=range(n*k), linewidths=0,
            marker='o', s=3,,)
plt.xticks([]); plt.yticks([]);

You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).

IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).