自适应均线系统 python_Python熊猫考夫曼自适应移动平均值(KAMA)---熊猫或Cython中的递归计算...
时间: 2023-06-24 10:06:47 浏览: 323
Python软件包:解析延拓的Padé近似法和最大熵法
自适应均线(Adaptive Moving Average,AMA)是一种根据市场波动情况自动调整权重的移动平均线。Python中可以使用Pandas和Cython进行递归计算。
首先,我们需要定义KAMA计算的公式:
![KAMA公式](https://img-blog.csdn.net/20180407161745629?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ2V0dGVuZGVl/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80)
其中:
- sc = 2 / (fast+1) - 2 / (slow+1)
- fc = 2 / (period+1)
- er = abs(close - prev_close)
- weight = pow((er * (sc * (fast - slow) + slow) + prev_er * (fc * (period - 1))), 2)
- ama = prev_ama + weight * (close - prev_ama)
然后,我们可以使用Pandas实现递归计算:
```python
import pandas as pd
def kama(close, period=10, fast=2, slow=30):
df = pd.DataFrame({'close': close})
df['volatility'] = abs(df['close'] - df['close'].shift(1))
er = df['volatility'].rolling(period).sum() / df['volatility'].rolling(period).count()
sc = 2 / (fast + 1) - 2 / (slow + 1)
fc = 2 / (period + 1)
df['weight'] = pow((er * (sc * (fast - slow) + slow) + df['volatility'].shift(period - 1) * (fc * (period - 1))), 2)
df['ama'] = df['close'].rolling(period).mean()
for i in range(period, len(df)):
df['ama'][i] = df['ama'][i - 1] + df['weight'][i] * (df['close'][i] - df['ama'][i - 1])
return df['ama']
```
使用方法:
```python
import numpy as np
import matplotlib.pyplot as plt
close = np.random.rand(100)
ama = kama(close)
plt.plot(close)
plt.plot(ama)
plt.show()
```
我们也可以使用Cython来提高运行速度:
```python
%load_ext cython
%%cython
import pandas as pd
import numpy as np
cimport numpy as np
def kama_cy(np.ndarray[np.float64_t, ndim=1] close, int period=10, int fast=2, int slow=30):
cdef int i
cdef int N = len(close)
cdef np.ndarray[np.float64_t, ndim=1] volatility = np.zeros(N)
cdef np.ndarray[np.float64_t, ndim=1] er = np.zeros(N)
cdef np.ndarray[np.float64_t, ndim=1] weight = np.zeros(N)
cdef np.ndarray[np.float64_t, ndim=1] ama = np.zeros(N)
for i in range(1, N):
volatility[i] = abs(close[i] - close[i-1])
for i in range(period, N):
er[i] = np.sum(volatility[i-period+1:i+1]) / period
sc = 2 / (fast + 1) - 2 / (slow + 1)
fc = 2 / (period + 1)
for i in range(period, N):
weight[i] = pow((er[i] * (sc * (fast - slow) + slow) + volatility[i - period] * (fc * (period - 1))), 2)
ama[period-1] = np.mean(close[:period])
for i in range(period, N):
ama[i] = ama[i - 1] + weight[i] * (close[i] - ama[i - 1])
return ama
```
使用方法:
```python
import numpy as np
import matplotlib.pyplot as plt
close = np.random.rand(100)
ama = kama_cy(close)
plt.plot(close)
plt.plot(ama)
plt.show()
```
阅读全文