考夫曼均线python代码
时间: 2023-10-12 15:08:53 浏览: 140
以下是使用Python实现考夫曼均线的代码示例:
```python
import numpy as np
def KaufmanEfficiencyRatio(prices, period=10):
roc = np.abs(np.diff(prices))
m = np.zeros(period-1)
n = len(prices)
er = np.zeros(n)
for i in range(period-1, n):
m = 0.0
for j in range(period):
m += roc[i-j]
er[i] = m / np.sum(np.abs(prices[i-period+1:i+1]))
return er
def KaufmanAdaptiveMovingAverage(prices, period=10, fast=2, slow=30):
er = KaufmanEfficiencyRatio(prices, period)
sc = (er*(2.0/(fast+1)-2.0/(slow+1))+2.0/(slow+1))**2.0
kama = np.zeros_like(prices)
n = len(prices)
first = True
for i in range(n):
if er[i] != 0:
if first:
kama[i] = prices[i]
first = False
else:
kama[i] = kama[i-1] + sc[i]*(prices[i]-kama[i-1])
else:
kama[i] = kama[i-1]
return kama
```
这段代码定义了两个函数:`KaufmanEfficiencyRatio` 和 `KaufmanAdaptiveMovingAverage`。前者计算考夫曼效率比率(KER),后者使用 KER 计算考夫曼自适应移动平均线(KAMA)。
使用示例:
```python
import yfinance as yf
symbol = "AAPL"
data = yf.download(symbol, start="2020-01-01", end="2021-12-31")
prices = data["Adj Close"].values
kama = KaufmanAdaptiveMovingAverage(prices)
# 可以将 KAMA 和原始价格绘制在同一张图上进行比较
import matplotlib.pyplot as plt
plt.plot(prices)
plt.plot(kama)
plt.legend(["Prices", "KAMA"])
plt.show()
```