在矩阵中保存循环的结果

时间:2018-06-08 12:08:12

标签: python arrays list numpy

我目前正在编写一个用于执行几何布朗运动的Python工具。执行运动的循环完成并按预期工作。现在我遇到了在大矩阵中保存模拟的各种结果并将其绘制出来的问题。

我尝试使用append函数,但事实证明我得到的结果是每个模拟的另一个数组的列表,而不是一个大矩阵。

我的代码:

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)

## empty Matrix for the end results
res = []

while i < simu + 1:

    ## random number showing the Wiener process
    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) ### new Stock prices based on the simulated returns ###

    res.append(S)     #appends the resulting array to the result table

    i += 1

#plotting of the result Matrix
plt.plot(t, res)
plt.show() 

如果有人可以帮我解决这个问题,我会很高兴,因为我打算用不同的路径绘制时间(存储在大矩阵中)。

提前谢谢你,

尼克

1 个答案:

答案 0 :(得分:0)

要完全避免循环并使用快速和干净的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中。 np.ndarraynumpy的标准数组格式,因此是使用最广泛且支持的数组格式 要绘制它,您需要提供更多信息,例如:您是否要绘制结果数组的每一行?这将是:

for i in range(simu):
    plt.plot(t, res[i])
plt.show()

如果要在计算后检查形状的一致性,可以执行以下操作:

assert res.shape == (simu, N), 'Calculation faulty!'