代码之家  ›  专栏  ›  技术社区  ›  TyRa97

在矩阵中保存循环结果

  •  -1
  • TyRa97  · 技术社区  · 6 年前

    我目前正在编程一个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 回复  |  直到 6 年前
        1
  •  0
  •   JE_Muc    6 年前

    要完全避免循环并使用快速干净的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!'