问题描述
我想用3年的时间模拟Python的股价走势,共300步,有5条路径。 股价可以上升或下降,上升的概率为q,下降的概率为1-q。
如果增加,则时段t中的价格=时段价格t-1 x u 如果减少,则期间价格t =期间价格t-1 x d
我对如何使用随机数回答这个问题感到困惑。尽管我这样做是可以显示结果的,但是我不确定将随机数与q进行比较是否是正确的方法。
#m = time step
#T = year
#sigma = volatility
#S0 = price period 0
#r = riskfree
def price_path(m,T,sigma,s0,r):
prices = np.zeros(m)
prices[0] = s0
u = np.exp(sigma*np.sqrt(T/m))
d = 1/u
q = (np.exp(sigma*T/m) - d) / (u-d)
for i in range(m-1):
rand_var = np.random.rand()
if(rand_var < q):
prices[i+1] = prices[i] * u
else:
prices[i+1] = prices[i] * d
return prices
np.random.seed(3912)
fig,ax =plt.subplots()
for i in range(5):
rd_walk = price_path(m=300,T=3,sigma=0.25,s0=50,r=0.05)`
plt.plot(rd_walk)
解决方法
您做得正确,因为它只是伯努利分布。
通过使用numpy
,您可以更简洁地编写price_path
:
def price_path(m,T,sigma,s0,r):
u = np.exp(sigma*np.sqrt(T/m))
d = 1/u
q = (np.exp(sigma*T/m) - d) / (u-d)
up_or_down = np.where(np.random.rand(m)<q,u,d)
up_or_down[0] = 1.
prices = s0 * np.cumprod(up_or_down)
return prices