# python and derivatives pricing tutorial – brownian motion

In pricing models (black-scholes, local vol, libor market model) the source of uncertainty is Brownian motion. how to simulate it in python? python download

first, lets simulate dWt , we know it’s a gaussian variable with mean 0 and deviation $\sqrt {dt}$
google “python gaussian” and we get to numpy gaussian
so dWt is just np.random.randn()*math.sqrt(dt)

knowing dWt how to we get to Wt at time t? $W_T=\int_0^T {dW_t}$ and integral is just a sum , so $W_T = \sum {dW_t}$ , so final function to calculate W_T is:


import numpy as np
dt=0.01
def W(T):
sum=0
N=T/dt
for i in xrange(int(N)):
sum+=np.random.randn()*np.sqrt(dt)
return sum


now check calculate properties of brownian motion:

1) mean should be zero


T=1.0
nSim=10000
mean=0
for i in xrange(nSim):
mean+=W(T)
mean/=nSim
print mean


2) variance should be T


T=3.0
nSim=10000
mean=0
for i in xrange(nSim):
wt=W(T)
mean+=wt*wt
mean/=nSim
print mean


now lets calculate probability $P( W(1)<0 and W(2) < 0)$

nSim=100000
proba=0
for i in xrange(nSim):
w1=W(1)
w2=w1+W(1)
if w1<0 and w2<0:
proba+=1.
proba/=nSim
print proba

Posted in quant finance coding course