我正在尝试在熊猫中快速创建模拟随机游走系列。
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
希望在开始日期从start_price开始构建另一个日期系列,并以随机增长率增长。 伪代码:
P0 = 100
P1 = 100 * exp(Y2)
P2 = P1 * exp(Y2)
在excel中很容易做到,但是我不能想到这样做而不用pandas迭代数据帧/系列,我也会这样做。
尝试过:
p = Y2.apply(np.exp)-1
y = p.cumsum(p)
y.plot()
这应该给出自开始以来累积的复合回报
答案 0 :(得分:12)
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()