# How to do a geometric Brownian motion in Python

• 1 minGeometric Brownian Motion (GBM) is a stochastic process that describes the evolution of the price of a financial asset over time. The model assumes that the stock price follows a log-normal distribution and that the change in the stock price is proportional to the current stock price and a normally distributed random variable.

In Python, you can model GBM by using the following formula to update the stock price at each time step:

```
price[t] = price[t-1] * np.exp((mu - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * e)
```

Where:

`price[t]`

is the stock price at time`t`

`price[t-1]`

is the stock price at time`t-1`

`mu`

is the mean return of the stock`sigma`

is the standard deviation of the returns of the stock`dt`

is the time step (`T/N`

, where`T`

is the total time period and`N`

is the number of time steps)`e`

is a random normal variable with mean 0 and standard deviation 1

Here's a simple Python script for GBM simulation:

```
import numpy as np
# Number of time steps
N = 252
# Total time period
T = 1
# Mean return
mu = 0.05
# Standard deviation of returns
sigma = 0.2
# Initial stock price
S = 100
# Time step
dt = T/N
# Initialize prices array
prices = np.zeros([N])
# First price is the initial price
prices[0] = S
# Loop through the remaining time steps
for i in range(1, N):
# Generate random normal variable
e = np.random.normal(0, 1)
# Update the stock price using the geometric Brownian motion model
prices[i] = prices[i-1] * np.exp((mu - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * e)
```

This script generates a simulation of the stock price over `N`

time steps. The stock price at each time step is updated using the formula for GBM, with the `np.random.normal`

function generating a random normal variable for the change in the stock price at each time step.