Numpy Exercise 3

Imports


In [83]:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns

In [3]:
import antipackage
import github.ellisonbg.misc.vizarray as va


Downloading:  https://raw.githubusercontent.com/ellisonbg/misc/master/vizarray.py
Using existing version:  github.ellisonbg.misc.vizarray

Geometric Brownian motion

Here is a function that produces standard Brownian motion using NumPy. This is also known as a Wiener Process.


In [47]:
def brownian(maxt, n):
    """Return one realization of a Brownian (Wiener) process with n steps and a max time of t."""
    t = np.linspace(0.0,maxt,n)
    h = t[1]-t[0]
    Z = np.random.normal(0.0,1.0,n-1)
    dW = np.sqrt(h)*Z
    W = np.zeros(n)
    W[1:] = dW.cumsum()
    return t, W

Call the brownian function to simulate a Wiener process with 1000 steps and max time of 1.0. Save the results as two arrays t and W.


In [76]:
t, W = brownian(1.0,1000)

In [6]:
assert isinstance(t, np.ndarray)
assert isinstance(W, np.ndarray)
assert t.dtype==np.dtype(float)
assert W.dtype==np.dtype(float)
assert len(t)==len(W)==1000

Visualize the process using plt.plot with t on the x-axis and W(t) on the y-axis. Label your x and y axes.


In [7]:
plt.plot(t, W)
plt.xlabel('t')
plt.ylabel('W(t)')
#lookin' good


Out[7]:
<matplotlib.text.Text at 0x7ff386afad10>

In [8]:
assert True # this is for grading

Use np.diff to compute the changes at each step of the motion, dW, and then compute the mean and standard deviation of those differences.


In [9]:
dW = np.diff(W)

def mean(dW):
    return dW.cumprod()/len(dW)

def standard_deviation(dW):
    mean(dW)
    variance = 0
    for i in dW:
        variance += (mean(dW) - i) ** 2
    return variance/float(len(dW))** 0.5
#used format from codecademy

In [10]:
assert len(dW)==len(W)-1
assert dW.dtype==np.dtype(float)

Write a function that takes $W(t)$ and converts it to geometric Brownian motion using the equation:

$$ X(t) = X_0 e^{((\mu - \sigma^2/2)t + \sigma W(t))} $$

Use Numpy ufuncs and no loops in your function.


In [89]:
def geo_brownian(t, W, X0, mu, sigma):
    "Return X(t) for geometric brownian motion with drift mu, volatility sigma."""
    brownian(t, W)
    t, W = brownian(t, W)
    Xt = X0 * np.exp(np.multiply(int(mu) - ((int(sigma) ** 2)/2),t) + ((sigma) * brownian(t,W)))
    return Xt
#I have played with this so much, I don't know what it is stopping it from working. Part of it could be that I don't know 
# when to use numpy ufuncs and when to use our regular addition and subtraction, etc. It would help if talked more about 
# these things in class before having homework due with them.

In [90]:
assert True # leave this for grading

Use your function to simulate geometric brownian motion, $X(t)$ for $X_0=1.0$, $\mu=0.5$ and $\sigma=0.3$ with the Wiener process you computed above.

Visualize the process using plt.plot with t on the x-axis and X(t) on the y-axis. Label your x and y axes.


In [91]:
a = geo_brownian(1.0, 1000, 1.0, 0.5, 0.3)
plt.plot(t,a)
#This would work if my previous step worked


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-91-2aada253496f> in <module>()
----> 1 a = geo_brownian(1.0, 1000, 1.0, 0.5, 0.3)
      2 plt.plot(t,a)

<ipython-input-89-73250b74dd96> in geo_brownian(t, W, X0, mu, sigma)
      3     brownian(t, W)
      4     t, W = brownian(t, W)
----> 5     Xt = X0 * np.exp(np.multiply(int(mu) - ((int(sigma) ** 2)/2),t) + ((sigma) * brownian(t,W)))
      6     return Xt

<ipython-input-47-29f374a70eeb> in brownian(maxt, n)
      1 def brownian(maxt, n):
      2     """Return one realization of a Brownian (Wiener) process with n steps and a max time of t."""
----> 3     t = np.linspace(0.0,maxt,n)
      4     h = t[1]-t[0]
      5     Z = np.random.normal(0.0,1.0,n-1)

/usr/local/lib/python2.7/dist-packages/numpy/core/function_base.pyc in linspace(start, stop, num, endpoint, retstep, dtype)
     82 
     83     """
---> 84     num = int(num)
     85 
     86     # Convert float/complex array scalars to float, gh-3504

TypeError: only length-1 arrays can be converted to Python scalars

In [ ]:
assert True # leave this for grading