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 is a 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()
This exercise is part of the course
Time Series Analysis in Python
In this four-hour course, you’ll learn the basics of analyzing time series data in Python.
In this chapter you'll learn about some simple time series models. These include white noise and a random walk.
Exercise 1: Autocorrelation FunctionExercise 2: Taxing Exercise: Compute the ACFExercise 3: Are We Confident This Stock is Mean Reverting?Exercise 4: White NoiseExercise 5: Can't Forecast White NoiseExercise 6: Random WalkExercise 7: Generate a Random WalkExercise 8: Get the DriftExercise 9: Are Stock Prices a Random Walk?Exercise 10: How About Stock Returns?Exercise 11: StationarityExercise 12: Is it Stationary?Exercise 13: Seasonal Adjustment During Tax SeasonWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.