Implementing a random walk forecast in Python

In previous posts I introduced very simple (and naive) forecasting methods, namely CAGR-based forecasting and simple moving average forecasting. I implemented such forecasting methods in R and demonstrated basic use cases.

In this post I want to introduce another simple forecasting method: Random walk forecasting. I will implement an example using Python.

Random walk forecasting can e.g. be used for creating a simple baseline model against which other forecasts can be compared. A random walk can be a good benchmark. Here I am e.g. thinking of financial market analysis where many financial engineers try to create trading strategies and forecasting models that can be tested against random walks.

Below I implement a random walk forecasting function in Python. The function requires the random module.

import random
# function for simulating a random walk; parameters include annual growth rate, starting point etc.
def random_walk_forecast(annualGrowth,
    # declare empty prediction return list 
    prediction = []
    # convert annual growth into daily growth, assuming defined number of productive days per year
    g = (1+annualGrowth)**(1/productiveDaysPerYear)-1
    # calculate all prediction values
    for i in range(0,forecastLength):
        # if first prediction then list is still empty
        if i == 0:
    # return the list of predicted values
    return prediction

Using the random_walk_forecast we can visualize a random walk forecast using pyplot, as part of the matplotlib library in Python:

# list with historical data
historicals = [800,1000,874,945,1121,1245,1020]
# assumed annual growth rate
growth_rate = 0.03
# prediction, assuming 220 productive days per year; forecasting for 10 work day horizon
predictions = random_walk_forecast(annualGrowth = growth_rate,
                                  startPoint = historicals[-1],
                                  standardDeviationRelativeToMeanGrowth = 500)
# import matplotlib.pyplot for being able to create plots
import matplotlib.pyplot as plt
# set figure size
plt.figure(figsize = (20,5))
# merge historicals and predictions; lets extend predictions onto historicals
# create a simple bar plot,len(historicals)+1),
        color = "#229900")
# add a title to the graph
plt.title("time series wrandom walk: result of simple forecasting appraoch",size=20)
# add axis labels
plt.ylabel("values of interest",size=14)
# show the plot

This concludes my simple example.

You May Also Like

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.