In [1]:
import numpy as np
import pandas as pd

import statsmodels
from statsmodels.tsa.stattools import coint
import statsmodels.api as stat
import statsmodels.tsa.stattools as ts

import matplotlib.pyplot as plt
from nsepy import get_history
from datetime import date
In [2]:
S1 = get_history(symbol = "NIFTY", 
                        start = date(2010,1,1), 
                        end = date(2020,9,3), index=True)
<matplotlib.axes._subplots.AxesSubplot at 0x1112be96730>

A time series can then be characterised in the following manner:

  • H < 0.5 : The time series is mean reverting
  • H = 0.5 : The time series is a Geometric Brownian Motion
  • H > 0.5 : The time series is trending
In [3]:
from numpy import cumsum, log, polyfit, sqrt, std, subtract
from numpy.random import randn

def hurst(ts):
    """Returns the Hurst Exponent of the time series vector ts"""
    # Create the range of lag values
    lags = range(2, 100)

    # Calculate the array of the variances of the lagged differences
    tau = [sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags]

    # Use a linear fit to estimate the Hurst Exponent
    poly = polyfit(log(lags), log(tau), 1)

    # Return the Hurst exponent from the polyfit output
    return poly[0]*2.0
In [4]:
# Create a Gometric Brownian Motion
gbm = log(cumsum(randn(100000))+1000)
In [5]:
#Calculate Hurst Exponent for GBM
print("Hurst(GBM):   %s" % hurst(gbm))
Hurst(GBM):   0.49734726774168514
In [6]:
# Create a Mean-Reverting Series
mr = log(randn(100000)+1000)
In [7]:
#Calculate Hurst Exponent for MR
print("Hurst(MR):    %s" % hurst(mr))
Hurst(MR):    -0.0003620954823916043
In [8]:
# Create a Trending Series
tr = log(cumsum(randn(100000)+1)+1000)
In [9]:
print("Hurst(TR):    %s" % hurst(tr))
Hurst(TR):    0.9559633702762489
In [10]:
print("Hurst(Nifty):    %s" % hurst(S1[['Close']]))
Hurst(Nifty):    [0.47880703]
In [ ]:
In [ ]: