生成随机游走
股票的「收益」通常建模为白噪声,而股票的「价格」则更贴近随机游走。也就是说,今天的价格等于昨天的价格再加上一些随机噪声。
您将模拟一只股票的价格随时间变化。初始价格为 100,每天随机上升或下降。然后绘制模拟的股价。如果多次点击 "运行代码" 按钮,您会看到多次不同的模拟结果。
本练习是课程的一部分
Python 中的时间序列分析
练习说明
- 使用
np.random.normal()生成 500 个均值为 0、标准差为 1 的正态分布「步长」,其中均值参数为loc,标准差参数为scale。 - 模拟股票价格
P:- 使用 numpy 的
.cumsum()方法对随机steps做累加; - 给
P加上 100,使起始股价为 100。
- 使用 numpy 的
- 绘制该随机游走的模拟轨迹。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Generate 500 random steps with mean=0 and standard deviation=1
steps = np.random.normal(loc=___, scale=___, size=___)
# Set first element to 0 so that the first price will be the starting stock price
steps[0]=0
# Simulate stock prices, P with a starting price of 100
P = ___ + np.cumsum(___)
# Plot the simulated stock prices
plt.plot(___)
plt.title("Simulated Random Walk")
plt.show()