要完全避免循环并使用快速干净的pythonic矢量化操作,您可以编写如下操作:
import matplotlib.pyplot as plt
import numpy as np
T = 2
mu = 0.15
sigma = 0.10
S0 = 20
dt = 0.01
N = round(T/dt) ### Paths
simu = 20 ### number of simulations
i = 1
## creates an array with values from 0 to T with N elementes (T/dt)
t = np.linspace(0, T, N)
## result matrix creation not needed, thanks to gboffi for the hint :)
## random number showing the Wiener process
W = np.random.standard_normal(size=(simu, N))
W = np.cumsum(W, axis=1)*np.sqrt(dt) ### standard brownian motion ###
X = (mu-0.5*sigma**2)*t + sigma*W
res = S0*np.exp(X) ### new Stock prices based on the simulated returns ###
现在您的结果存储在
真实的
矩阵,或者正确地
np.ndarray
.
NdP射线
是的标准数组格式
numpy
因此是最广泛使用和支持的数组格式。
要绘制它,需要提供进一步的信息,例如:是否要绘制结果数组的每一行?这看起来像:
for i in range(simu):
plt.plot(t, res[i])
plt.show()
如果要在计算后检查形状的一致性,可以执行以下操作:
assert res.shape == (simu, N), 'Calculation faulty!'