用DFA法计算的Hurst指数全部正确的python代码,需要单维EXCEL数据的读取代码
时间: 2024-03-15 12:46:53 浏览: 148
以下是用DFA法计算Hurst指数的Python代码,并包含单维EXCEL数据的读取代码:
```python
import numpy as np
import pandas as pd
def dfa(x, nvals=None, overlap=True):
"""
Detrended Fluctuation Analysis (DFA).
Parameters
----------
x : array_like, shape (n_samples,)
One-dimensional time series.
nvals : array_like, optional (default=None)
Values of n to use. If None, nvals will be logarithmically spaced between
10 and len(x)//4 (inclusive).
overlap : bool, optional (default=True)
If True, windows are allowed to overlap.
Returns
-------
alpha : float
The slope of the line fit to the log of the fluctuation function.
"""
x = np.asarray(x, dtype=np.float64)
if x.ndim != 1:
raise ValueError("x must be one-dimensional.")
if nvals is None:
nvals = np.logspace(1, int(np.log2(len(x) // 4)), base=2, dtype=int)
else:
nvals = np.asarray(nvals, dtype=int)
if np.any(nvals > len(x) // 2):
raise ValueError("Maximum n is len(x) // 2.")
if overlap:
step = 1
else:
step = nvals[0]
F = np.zeros_like(nvals, dtype=np.float64)
for i, n in enumerate(nvals):
w = np.ones(n, dtype=np.float64)
w /= np.sqrt(np.sum(w))
if overlap:
y = np.convolve(x, w, mode='valid')
else:
y = [np.mean(x[j:j+n]) for j in range(0, len(x)-n+1, n)]
yi = np.cumsum(y - np.mean(y))
fi = np.sqrt(np.sum(yi**2)) / np.sqrt(n)
F[i] = fi
p = np.polyfit(np.log(nvals), np.log(F), deg=1)
return p[0]
# 读取单维EXCEL数据
data = pd.read_excel('data.xlsx', sheet_name='Sheet1')
x = data.iloc[:, 0].values
# 计算Hurst指数
hurst = dfa(x)
print("Hurst exponent: {:.3f}".format(hurst))
```
其中,`data.xlsx`为包含单维数据的EXCEL文件,`Sheet1`为数据所在的工作表。你可以将数据按照一列的方式存储在EXCEL文件中,然后通过`pandas`库的`read_excel`函数读取数据。读取后,将数据存储在`x`变量中,再调用`dfa`函数计算Hurst指数即可。
阅读全文