Testing for random walks

The random walk hypothesis (RWH) just like the efficient-market hypothesis (refer to the Examining the market with the non-parametric runs test recipe) claims that the market cannot be beaten. The RWH stipulates that asset prices perform a random walk. You can in fact generate pretty convincing stock price charts just by flipping a coin repeatedly.

In 1988, finance professors Lo and MacKinlay constructed a test for the RWH using the natural log(arithm) of asset prices as data. The test specifies the log prices to drift around a mean (7.9). We expect price changes for different frequencies (for instance, one-day and two-day periods) to be random. Furthermore, the variances (7.10 and 7.11) at two different frequencies are related, and according to the following equations, the corresponding ratio (7.12) is normally distributed around zero:

Testing for random walks

How to do it...

The code is in the random_walk.ipynb file in this book's code bundle:

  1. The imports are as follows:
    import dautil as dl
    import numpy as np
    import matplotlib.pyplot as plt
    import ch7util
  2. Calculate the ratios for our stocks:
    ratios = []
    
    for symbol in ch7util.STOCKS:
        ohlc = dl.data.OHLC()
        P = ohlc.get(symbol)['Adj Close'].values
        N = len(P)
        mu = (np.log(P[-1]) - np.log(P[0]))/N
        var_a = 0
        var_b = 0
    
        for k in range(1, N):
            var_a = (np.log(P[k]) - np.log(P[k - 1]) - mu) ** 2
            var_a = var_a / N
    
        for k in range(1, N//2):
            var_b = (np.log(P[2 * k]) - np.log(P[2 * k - 2]) - 2 * mu) ** 2
            var_b = var_b / N
    
        ratios.append(np.sqrt(N) * (var_b/var_a - 1))
  3. Plot the ratios, which we expect to be close to zero (7.12):
    _, ax = plt.subplots()
    dl.plotting.bar(ax, ch7util.STOCKS, ratios)
    ax.set_title('Random Walk Test')
    ax.set_ylabel('Ratio')

Refer to the following screenshot for the end result:

How to do it...

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset