Reputation: 159
I have 2 files GBM_simulation.py
and test_GBM.py
.
GBM_simulation.py
import numpy as np
# Return path as numpy array of length and step predefined
# simulate exact GBM
def GBM(n, dt, s0, r, sigma):
path = np.zeros(n)
s_old = s0
for i in range(n):
s_new = s_old*np.exp((r-sigma**2/2)*dt + sigma*(dt)**(1/2)*np.random.normal())
path[i] = s_new
s_old = s_new
return path
# simulate Euler scheme GBM:
def Euler_GBM(n, dt, s0, r, sigma):
path = np.zeros(n)
s_old = s0
for i in range(n):
s_new = s_old*(1 + r*dt + sigma*(dt)**(1/2)*np.random.normal())
path[i] = s_new
s_old = s_new
return path
test_GBM.py
import matplotlib.pyplot as plt
import GBM_simulation as sim
s0 = 2
n = 500
r = 1
sigma = 1
dt = 0.001
exact = sim.GBM(n, dt, s0, r, sigma)
euler = sim.Euler_GBM(n, dt, s0, r, sigma)
# Now plot
plt.plot(exact, label = 'Exact')
plt.plot(euler, label = 'Euler')
plt.legend(loc = 'best')
plt.show()
However, when I run test_GBM.py
on IPython console, the graph I get doesn't look correct at all. I tested on Jupyter Notebook (with some minor modifications) and it worked properly. Why does this happen?
Edit: this is the graph I got on Jupyter notebook
Upvotes: 0
Views: 88
Reputation: 12410
I can't believe that I didn't notice this immediately. Indentation matters - your return statement was inside the loop. The correct function definition is of course:
import numpy as np
# Return path as numpy array of length and step predefined
# simulate exact GBM
def GBM(n, dt, s0, r, sigma):
path = np.zeros(n)
s_old = s0
for i in range(n):
s_new = s_old*np.exp((r-sigma**2/2)*dt + sigma*(dt)**(1/2)*np.random.normal())
path[i] = s_new
s_old = s_new
return path
# simulate Euler scheme GBM:
def Euler_GBM(n, dt, s0, r, sigma):
path = np.zeros(n)
s_old = s0
for i in range(n):
s_new = s_old*(1 + r*dt + sigma*(dt)**(1/2)*np.random.normal())
path[i] = s_new
s_old = s_new
return path
For future reference my debugging procedure - I printed out the values for each single data point in the function loop to see, why the values drop immediately to zero. Et voilà - only one data point was calculated, so something must have been wrong with your loop definition.
Upvotes: 1