Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random walk pandas

I am trying to quickly create a simulated random walk series in pandas.

import pandas as pd
import numpy as np
dates = pd.date_range('2012-01-01', '2013-02-22')
y2 = np.random.randn(len(dates))/365
Y2 = pd.Series(y2, index=dates)
start_price = 100

would like to build another date series starting at start_price at beginning date and growing by the random growth rates. pseudo code:

P0 = 100
P1 = 100 * exp(Y2)
P2 = P1 * exp(Y2)

very easy to do in excel, but I cant think of way of doing it without iterating over a dataframe/series with pandas and I also bump my head doing that.

have tried:

p = Y2.apply(np.exp)-1
y = p.cumsum(p)
y.plot()

this should give the cumulatively compound return since start

like image 932
Joop Avatar asked May 24 '13 12:05

Joop


1 Answers

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def geometric_brownian_motion(T = 1, N = 100, mu = 0.1, sigma = 0.01, S0 = 20):        
    dt = float(T)/N
    t = np.linspace(0, T, N)
    W = np.random.standard_normal(size = N) 
    W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###
    X = (mu-0.5*sigma**2)*t + sigma*W 
    S = S0*np.exp(X) ### geometric brownian motion ###
    return S

dates = pd.date_range('2012-01-01', '2013-02-22')
T = (dates.max()-dates.min()).days / 365
N = dates.size
start_price = 100
y = pd.Series(
    geometric_brownian_motion(T, N, sigma=0.1, S0=start_price), index=dates)
y.plot()
plt.show()

enter image description here

like image 154
unutbu Avatar answered Oct 17 '22 05:10

unutbu