In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def figure_label():
plt.xlabel('time')
plt.ylabel('x')
In [2]:
def brownian_motion(T, N):
z = np.hstack(([0], np.random.randn(N - 1)))
return np.cumsum(z * np.sqrt(T / N))
T, N, n = 1, 10001, 100
t = np.linspace(0, T, N)
motions = np.zeros((n, N))
for i in range(n):
motions[i, :] = brownian_motion(T, N)
plt.title('mean and variance')
plt.plot(t, np.mean(motions, axis=0))
plt.plot(t, np.var(motions, axis=0))
figure_label()
In [3]:
def geometric_brownian_motion(T, N, sigma, r, x):
t = np.linspace(0, T, N)
W = brownian_motion(T, N)
return x * np.exp((r + sigma ** 2 / 2) * t + sigma * W)
sigma, r, x = 2, 4, 2
for i in range(n):
motions[i, :] = geometric_brownian_motion(T, N, sigma, r, x)
plt.title('Mean')
plt.plot(t, np.mean(motions, axis=0)), figure_label()
plt.figure()
plt.title('Variance')
plt.plot(t, np.var(motions, axis=0)), figure_label()
Out[3]:
In [4]:
def geometric_brownian_motion(T, N, t_0, x, y):
t = np.linspace(0, T, N)
W = brownian_motion(T, N)
return x + W - (t - t_0) / (T - t_0) * (W[-1] - y + x)
t_0, x, y = 0, -1, 2
t = np.linspace(0, T, N)
motions = np.zeros((n, N))
for i in range(n):
motions[i, :] = geometric_brownian_motion(T, N, t_0, x, y)
plt.title('Mean')
plt.plot(t, np.mean(motions, axis=0)), figure_label()
plt.figure()
plt.title('Variance')
plt.plot(t, np.var(motions, axis=0)), figure_label()
Out[4]: