【问题标题】:How do I plot the average of a random walk/monte carlo sim Python如何绘制随机游走/蒙特卡罗模拟 Python 的平均值
【发布时间】:2020-09-15 18:25:48
【问题描述】:

我有一个问题,我正在绘制随机游走,我希望获得所有模拟的平均线。我的代码如下:

import numpy as np
from math import sqrt
import matplotlib.pyplot as plt

# starting stock price
S = 100

# number of trading days
T = 252

# random data inputs
mu = 0.061
stdev = 0.165

if __name__ == '__main__':

    average= []

    # running the simulation multiple times (# specified in range) times
    for i in range(100):

        daily_returns = np.random.normal((mu/T), stdev/sqrt(T), T) + 1

        # set starting price and create price series generated by above random daily returns
        price_list = [S]

        for x in daily_returns:
            price_list.append(price_list[-1]*x)

        # Generate Plots - price series and histogram of daily returns
        plt.plot(price_list, color='gray')
        plt.hist(daily_returns-1, 100) # Note that we run the line plot and histogram separately, not simultaneously.
        average.append(np.mean(price_list))
    plt.plot(average, color='red')
    plt.show()

我遇到的问题是我能够提出的平均线(可能是错误的)似乎在情节中途停止了。我确信这是一个简单的解决方法,但它会让我发疯!

谢谢!

【问题讨论】:

    标签: python-3.x pandas numpy matplotlib random-walk


    【解决方案1】:

    它失败的原因是因为您运行了 100 次模拟,所以 len(avarage) 将是 100,但 len(price_list) 始终是 252 + 1。修复的最简单方法是使这两个相同。但这并不能解决另一个大问题:您计算每次模拟 252 + 1 天的平均价格,这就是为什么您的平均价格在开始日是错误的。你应该按天计算。更好的解决方案是:

    import numpy as np
    import matplotlib.pyplot as plt
    
    S = 100
    T = 10
    mu = 0.061
    stdev = 0.165
    SIMULATIONS = 100
    
    if __name__ == '__main__':
        # the array to store simulation results
        full_array = np.empty(shape=(SIMULATIONS, T + 1))
    
        for i in range(SIMULATIONS):
            daily_returns = np.random.normal((mu/T), stdev/np.sqrt(T), T) + 1
            
            # A more efficient way of calculating the same as you have
            # It's a simple geometric series.
            price_list = np.empty(shape=len(daily_returns) + 1)
            price_list[0] = S
            price_list[1:] = daily_returns
            price_list = np.cumprod(price_list)
            plt.plot(price_list, color="gray")
            
            # save that simulation run
            full_array[i, :] = price_list
    
    # plot the mean by days
    plt.plot(np.mean(full_array, axis=0), color="red")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 2020-01-07
      • 2019-11-11
      • 2014-03-26
      相关资源
      最近更新 更多