Search code examples
pythonsimulation

Simulating coin tosses on a fixed time scale and increasing the # of steps


I've written out some basic (and commonly used code) to simulate Weiner processes. Recently, I looked at Paul Wilmott Introduces Quantitative Finance (IInd edition, Chp 5, page 122) where a chart shows the impact of increasing the number of steps (while keeping T fixed at 1) on the coin toss experiment. I'm not quite sure how to create this chart.

enter image description here

The code is rather basic, but I'll share it:

def brownian(num_steps):
    w = np.ones(num_steps)     
    for i in range(1, num_steps):
        yi = np.random.choice([-1, 1])
        # dW
        w[i] = w[i-1]  + yi/np.sqrt(num_steps)
    return w

The problem is that I don't quite know how to make the num steps fit into the interval [0, 1] (i.e. the length of time on the x axis in the picture). Would appreciate some guidance Thanks


Solution

  • You can try this:

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    def brownian(num_steps):
        rng = np.random.default_rng()
        w = np.cumsum(2 * rng.integers(0, 2, num_steps-1) - 1)
        return np.r_[0, w] / np.sqrt(num_steps)
    
    num_steps = 50
    plt.style.use('seaborn-whitegrid')
    plt.plot(np.linspace(0, 1, num_steps), brownian(num_steps))
    plt.show()
    

    It gives:

    brownian motion