DFA法计算的Hurst指数全部正确的python代码,包括单维EXCEL数据的读取代码
时间: 2024-03-15 12:45:41 浏览: 243
好的,以下是一份可以读取单维EXCEL数据并计算DFA法的Hurst指数的Python代码:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def dfa(X, nvals=None, overlap=True, order=1, debug_plot=False):
"""
Detrended Fluctuation Analysis
A method for determining the statistical self-affinity of a signal. The
signal is sub-sampled into boxes of size n. In each box, a least-squares
polynomial is fit, and the local variance of the detrended data is
computed. This is averaged over all boxes and normalized by the total
variance of the signal.
Parameters
----------
X : ndarray
One-dimensional time series.
nvals : ndarray or None, optional (default=None)
Array of box sizes. Default is np.logspace(0.7, np.log10(N/4), 20),
where N is the length of the time series.
overlap : bool, optional (default=True)
If True, boxes overlap by half. If False, boxes are separated by
exactly nvals[i] points.
order : int, optional (default=1)
Order of polynomial used to fit data in each box.
debug_plot : bool, optional (default=False)
If True, plot intermediate results for debugging purposes.
Returns
-------
alpha : float
DFA exponent.
"""
X = np.asarray(X)
N = len(X)
if nvals is None:
nvals = np.logspace(0.7, np.log10(N/4), 20).astype(int)
else:
nvals = np.asarray(nvals)
overlap = bool(overlap)
# Compute the profile y(i) of the time series, integrated from the
# beginning.
Y = np.cumsum(X - np.mean(X))
# Compute the mean profile <y>_{i,n}.
if overlap:
step = nvals // 2
else:
step = nvals
K = len(step)
ymean = np.zeros(K, dtype=float)
for k in range(K):
n = nvals[k]
if overlap:
start = np.arange(0, N-n, step[k])
else:
start = range(0, N-n+1, step[k])
local_means = [np.mean(Y[i:i+n]) for i in start]
ymean[k] = np.mean(local_means)
# Compute the root-mean-square fluctuation about the mean profile
# F(n) for each box size.
F = np.zeros(K, dtype=float)
for k in range(K):
n = nvals[k]
if overlap:
start = np.arange(0, N-n, step[k])
else:
start = range(0, N-n+1, step[k])
local_means = [np.mean(Y[i:i+n]) for i in start]
X = Y[start] - local_means
C = np.cumsum(X - ymean[k])
F[k] = np.sqrt(np.mean(C**2))
# Fit F(n) to a power law and return the exponent.
coeffs = np.polyfit(np.log(nvals), np.log(F), order)
alpha = coeffs[0]
if debug_plot:
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes[0]
ax.plot(Y)
ax.set_title('Integrated signal')
ax = axes[1]
ax.loglog(nvals, F, 'bo-', label='F(n)')
ax.loglog(nvals, np.exp(coeffs[1]) * nvals**coeffs[0], 'r--',
label='Fit')
ax.set_title('DFA plot')
ax.legend(loc='best')
ax.set_xlabel('Box size (n)')
ax.set_ylabel('RMS fluctuation (F)')
plt.tight_layout()
plt.show()
return alpha
# 读取Excel数据
data = pd.read_excel('data.xlsx', sheet_name='Sheet1')
X = data['Column1'].values
# 计算Hurst指数
hurst = dfa(X)
print('Hurst指数为:', hurst)
```
以上代码中的 `dfa()` 函数实现了DFA算法,可以计算出输入时间序列的Hurst指数。您可以将自己的Excel数据文件名替换掉代码中的 `data.xlsx`,并将数据列名替换掉 `X = data['Column1'].values` 中的 `'Column1'`,然后直接运行代码即可得到Hurst指数的计算结果。
阅读全文
相关推荐













