我如何绘制随机 walk/monte carlo sim Python 的平均值

How do I plot the average of a random walk/monte carlo sim Python

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

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()

我遇到的问题是我能够得出的平均线(可能不正确)似乎在情节中途停止了。我相信这是一个简单的修复,但它会让我发疯!

谢谢!

失败的原因是你运行模拟了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")