112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213 | def hurst_dfa(
data: pd.DataFrame | pd.Series,
*,
window: int = 240,
price_col: str = "close",
min_scale: int = 4,
max_scale: int | None = None,
n_scales: int = 10,
log_price: bool = True,
) -> pd.Series:
window = validate_positive_int(window, name="window")
min_scale = validate_positive_int(min_scale, name="min_scale")
n_scales = validate_positive_int(n_scales, name="n_scales")
if window < 8:
raise ValueError(f"window must be >= 8, got {window}")
if max_scale is None:
max_scale_eff = max(min_scale, window // 4)
else:
max_scale_eff = validate_positive_int(max_scale, name="max_scale")
max_scale_eff = min(max_scale_eff, window // 2)
if max_scale_eff < min_scale:
raise ValueError(f"max_scale must be >= min_scale, got max_scale={max_scale_eff}, min_scale={min_scale}")
x = get_price_series(data, price_col=price_col).astype(float)
if log_price:
x = np.log(x.where(x > 0))
out = pd.Series(np.nan, index=x.index, dtype=float)
out.name = f"hurst_dfa_{window}"
if len(x) < window:
return out
scales = np.unique(
np.floor(
np.logspace(
np.log10(float(min_scale)),
np.log10(float(max_scale_eff)),
int(n_scales),
)
).astype(int)
)
scales = scales[(scales >= min_scale) & (scales <= max_scale_eff)]
if scales.size < 2:
return out
x_arr = x.to_numpy(dtype=float)
windows = np.lib.stride_tricks.sliding_window_view(x_arr, window_shape=window)
mean_win = np.nanmean(windows, axis=1, keepdims=True)
prof = np.nancumsum(windows - mean_win, axis=1)
log_s = np.log(scales.astype(float))
f_mat = np.full((prof.shape[0], scales.size), np.nan, dtype=float)
for j, s in enumerate(scales.tolist()):
m = window // int(s)
if m < 2:
continue
y = prof[:, : m * s].reshape(prof.shape[0], m, s)
t = np.arange(s, dtype=float)
t_mean = t.mean()
t_centered = t - t_mean
denom = float(np.sum(t_centered**2))
if denom == 0.0:
continue
y_mean = np.nanmean(y, axis=2, keepdims=True)
slope = np.nansum(t_centered[None, None, :] * (y - y_mean), axis=2, keepdims=True) / denom
intercept = y_mean - slope * t_mean
trend = slope * t[None, None, :] + intercept
res = y - trend
f_mat[:, j] = np.sqrt(np.nanmean(res**2, axis=(1, 2)))
log_f = np.log(f_mat)
valid_scale = np.isfinite(log_s)
valid_scale &= np.isfinite(log_f).all(axis=0)
if valid_scale.sum() < 2:
return out
xs = log_s[valid_scale]
ys = log_f[:, valid_scale]
x_mean = xs.mean()
x_centered = xs - x_mean
x_var = float(np.sum(x_centered**2))
if x_var == 0.0:
return out
y_mean = ys.mean(axis=1, keepdims=True)
cov = np.sum((ys - y_mean) * x_centered[None, :], axis=1)
hurst = cov / x_var
out.iloc[window - 1 :] = hurst
return out
|