Created
September 18, 2023 16:28
-
-
Save ili3p/aed2b493dfa5dd670a5904eb998354b0 to your computer and use it in GitHub Desktop.
Fast Hurst exponent calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import numpy as np | |
from numba import jit | |
def calc_hurst(series: pd.Series, n_wins: int = 300): | |
changes = series.diff().dropna().astype(np.float32).values | |
max_w = changes.shape[0] - 1 | |
win_sizes = np.linspace(np.log10(10), np.log10(max_w), num=n_wins) | |
win_sizes = np.unique(np.power(10, win_sizes).astype(np.int16)) | |
rs = _calc(changes, win_sizes) | |
hurst, const = np.polyfit(np.log10(win_sizes), np.log10(rs), 1) | |
rs /= np.power(10, const) | |
return hurst, win_sizes, rs | |
@jit(nopython=True) | |
def _calc(changes, win_sizes): | |
rs = np.empty_like(win_sizes, dtype=np.float32) | |
for k, ws in enumerate(win_sizes): | |
total: float = 0.0 | |
n: int = changes.shape[0]-ws+1 | |
for i in range(0, n): | |
Z = (changes[i:i+ws] - changes[i:i+ws].mean()).cumsum() | |
R = max(Z) - min(Z) | |
S = changes[i:i+ws].std() | |
total += R/S | |
rs[k] = total/n | |
return rs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment