Generate a Random Walk
Whereas stock returns are often modeled as white noise, stock prices closely follow a random walk. In other words, today's price is yesterday's price plus some random noise.
You will simulate the price of a stock over time that has a starting price of 100 and every day goes up or down by a random amount. Then, plot the simulated stock price. If you hit the "Run Code" code button multiple times, you'll see several realizations.
This exercise is part of the course
Time Series Analysis in Python
Exercise instructions
- Generate 500 random normal "steps" with mean=0 and standard deviation=1 using
np.random.normal()
, where the argument for the mean isloc
and the argument for the standard deviation isscale
. - Simulate stock prices
P
:- Cumulate the random
steps
using the numpy.cumsum()
method - Add 100 to
P
to get a starting stock price of 100.
- Cumulate the random
- Plot the simulated random walk
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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()