Files
strategy-lab/to_explore/pyquantnews/26_HurstExponent.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

5.8 KiB

No description has been provided for this image

This notebook analyzes the Hurst exponent of the S&P 500 index to measure market trends and randomness. It loads historical S&P 500 data using the OpenBB SDK and calculates the Hurst exponent for various time lags. The Hurst exponent helps in understanding the nature of time series, whether it is mean-reverting, trending, or a random walk. This information is valuable for financial analysts and quant traders for making informed decisions. Additionally, it plots rolling volatility to observe changes in market volatility over time.

In [ ]:
import pandas as pd
import numpy as np
In [ ]:
from openbb_terminal.sdk import openbb

Load historical S&P 500 data from 2000 to 2019 using the OpenBB SDK and select the adjusted close prices

In [ ]:
df = openbb.stocks.load("^GSPC", start_date="2000-01-01", end_date="2019-12-31")["Adj Close"]

Plot the S&P 500 adjusted close prices to visualize the historical data

In [ ]:
df.plot(title="S&P 500")
In [ ]:
def get_hurst_exponent(ts, max_lag=20):
    """Calculate the Hurst exponent of a time series
    
    Parameters
    ----------
    ts : np.ndarray
        Time series data
    max_lag : int, optional
        Maximum lag to consider, by default 20
    
    Returns
    -------
    float
        Estimated Hurst exponent
    
    Notes
    -----
    The Hurst exponent is used to determine the 
    long-term memory of time series data.
    """

    # Define the range of lags to be used in the calculation
    lags = range(2, max_lag)

    # Calculate the standard deviation of differences for each lag
    tau = [np.std(np.subtract(ts[lag:], ts[:-lag])) for lag in lags]

    # Perform a linear fit to estimate the Hurst exponent
    return np.polyfit(np.log(lags), np.log(tau), 1)[0]

Calculate and print the Hurst exponent for various lags using the full dataset

In [ ]:
for lag in [20, 100, 250, 500, 1000]:
    hurst_exp = get_hurst_exponent(df.values, lag)
    print(f"{lag} lags: {hurst_exp:.4f}")

Select a shorter series from 2005 to 2007 and calculate the Hurst exponent for various lags

In [ ]:
shorter_series = df.loc["2005":"2007"].values
for lag in [20, 100, 250, 500]:
    hurst_exp = get_hurst_exponent(shorter_series, lag)
    print(f"{lag} lags: {hurst_exp:.4f}")

Calculate rolling volatility using a 30-day window and plot the results to observe changes over time

In [ ]:
rv = df.rolling(30).apply(np.std)
rv.plot()

Calculate and print the Hurst exponent for various lags using the rolling volatility data

In [ ]:
for lag in [20, 100, 250, 500, 1000]:
    hurst_exp = get_hurst_exponent(rv.dropna().values, lag)
    print(f"{lag} lags: {hurst_exp:.4f}")

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.