不调用库,计算MACD,KDJ,ADX,RSI指标,python
时间: 2023-08-02 18:23:12 浏览: 155
利用python编写macd、kdj、rsi、ma等指标.pdf
计算技术指标需要一定的数学和编程基础,下面是一些常见指标的计算方法和Python代码实现:
1. MACD指标
MACD指标是由两条指数移动平均线(EMA)和一条信号线组成的,计算方法如下:
- 计算12日EMA和26日EMA
$EMA_{12}=前一日EMA_{12}×11/13+今日收盘价×2/13$
$EMA_{26}=前一日EMA_{26}×25/27+今日收盘价×2/27$
- 计算DIF线
$DIF=EMA_{12}-EMA_{26}$
- 计算DEA线
$DEA=前一日DEA×8/10+今日DIF×2/10$
- 计算MACD线
$MACD=(DIF-DEA)×2$
Python代码实现:
```python
def MACD(data, fast=12, slow=26, signal=9):
ema_fast = data['Close'].ewm(span=fast).mean()
ema_slow = data['Close'].ewm(span=slow).mean()
dif = ema_fast - ema_slow
dea = dif.ewm(span=signal).mean()
macd = (dif - dea) * 2
return dif, dea, macd
```
2. KDJ指标
KDJ指标是一种反映股票价格波动趋势的技术指标,计算方法如下:
- 计算当日的RSV值
$RSV=\frac{收盘价-最低价}{最高价-最低价}×100$
- 计算当日的K值、D值和J值
$K=前一日K×2/3+今日RSV×1/3$
$D=前一日D×2/3+今日K×1/3$
$J=3K-2D$
Python代码实现:
```python
def KDJ(data, n=9):
high = data['High'].rolling(n).max()
low = data['Low'].rolling(n).min()
rsv = (data['Close'] - low) / (high - low) * 100
k = rsv.ewm(com=2).mean()
d = k.ewm(com=2).mean()
j = 3 * k - 2 * d
return k, d, j
```
3. ADX指标
ADX指标是一个复合指标,由+DI和-DI两条线和ADX线组成,计算方法如下:
- 计算+DI和-DI
$TR=max(H-L, |H-前一日收盘价|, |L-前一日收盘价|)$
$+DM=H-前一日高点$
$-DM=前一日低点-L$
$+DI=+DM÷TR×100$
$-DI=-DM÷TR×100$
- 计算DX
$DX=|+DI--DI|÷(+DI+-DI)×100$
- 计算ADX
$ADX=前一日ADX×13/14+今日DX×1/14$
Python代码实现:
```python
def ADX(data, n=14):
h, l, c = data['High'], data['Low'], data['Close']
tr = pd.DataFrame({'tr': np.nan}, index=data.index)
tr['tr'] = np.max([h-l, np.abs(h-c.shift()), np.abs(l-c.shift())], axis=0)
tr['+dm'] = (h - h.shift()).where((h - h.shift()) > (l.shift() - l), 0)
tr['-dm'] = (l.shift() - l).where((l.shift() - l) > (h - h.shift()), 0)
tr['+di'] = tr['+dm'].rolling(n).sum() / tr['tr'].rolling(n).sum() * 100
tr['-di'] = tr['-dm'].rolling(n).sum() / tr['tr'].rolling(n).sum() * 100
tr['dx'] = np.abs(tr['+di'] - tr['-di']) / (tr['+di'] + tr['-di']) * 100
tr['adx'] = tr['dx'].ewm(alpha=1/n, min_periods=n).mean() * 100
return tr['+di'], tr['-di'], tr['adx']
```
4. RSI指标
RSI指标是通过比较一段时间内股票的平均涨幅和平均跌幅,来判断股票是否处于超买或超卖状态,计算方法如下:
- 计算当日涨跌幅
$delta=收盘价-前一日收盘价$
- 计算当日上涨和下跌的平均值
$gain=\max(delta,0)$
$loss=\max(-delta,0)$
$AvgGain=\frac{\sum_{i=1}^n gain_i}{n}$
$AvgLoss=\frac{\sum_{i=1}^n loss_i}{n}$
- 计算RSI
$RS=\frac{AvgGain}{AvgLoss}$
$RSI=100-\frac{100}{1+RS}$
Python代码实现:
```python
def RSI(data, n=14):
delta = data['Close'].diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(n).mean()
avg_loss = loss.rolling(n).mean()
rs = avg_gain / avg_loss
rsi = 100 - 100 / (1 + rs)
return rsi
```
以上是常见技术指标的计算方法和Python实现,需要注意不同的股票和交易品种可能需要不同的参数,需要根据实际情况进行调整。
阅读全文