Python 量化投资实战教程(4) —KDJ 策略-Python 实用宝典

# Python 量化投资实战教程(4) —KDJ 策略

Python 量化投资原来这么简单(2) —MACD策略(+26.9%)

Python 量化投资原来这么简单(3) —A股回测MACD策略

• RSV = （收盘价-N周期最低价）/（N周期最高价-N周期最低价）*100
• K值 = RSV的N周期加权移动平均值
• D值 = K值的N周期加权移动平均值
• J值 = 3K-2D

## 1.准备

Windows环境下打开Cmd(开始—运行—CMD)，苹果系统环境下请打开Terminal(command+空格输入Terminal)，准备开始输入命令安装依赖。

`pip install backtrader`

## 2.单一KDJ策略

• RSV = （收盘价-N周期最低价）/（N周期最高价-N周期最低价）*100
• K值 = RSV的N周期加权移动平均值
• D值 = K值的N周期加权移动平均值
• J值 = 3K-2D

```        # 9个交易日内最高价
self.high_nine = bt.indicators.Highest(self.data.high, period=9)
# 9个交易日内最低价
self.low_nine = bt.indicators.Lowest(self.data.low, period=9)
# 计算rsv值
self.rsv = 100 * bt.DivByZero(
self.data_close - self.low_nine, self.high_nine - self.low_nine, zero=None
)
# 计算rsv的3周期加权平均值，即K值
self.K = bt.indicators.EMA(self.rsv, period=3)
# D值=K值的3周期加权平均值
self.D = bt.indicators.EMA(self.K, period=3)
# J=3*K-2*D
self.J = 3 * self.K - 2 * self.D```

```    # Python 实用宝典
def next(self):
self.log("Close, %.2f" % self.dataclose[0])
if self.order:
return

if not self.position:
# J - D 值
condition1 = self.J[-1] - self.D[-1]
condition2 = self.J[0] - self.D[0]
if condition1 < 0 and condition2 > 0:

else:
condition = (self.dataclose[0] - self.bar_executed_close) / self.dataclose[0]
if condition > 0.1 or condition < -0.1:
self.log("SELL CREATE, %.2f" % self.dataclose[0])
self.order = self.sell()```

```    # Python 实用宝典
def next(self):
self.log("Close, %.2f" % self.dataclose[0])
if self.order:
return

condition1 = self.J[-1] - self.D[-1]
condition2 = self.J[0] - self.D[0]
if not self.position:
# J - D 值
if condition1 < 0 and condition2 > 0:

else:
if condition1 > 0 or condition2 < 0:
self.log("SELL CREATE, %.2f" % self.dataclose[0])
self.order = self.sell()```

## 3.多策略回测

```        # MACD策略参数
me1 = EMA(self.data, period=12)
me2 = EMA(self.data, period=26)
self.macd = me1 - me2
self.signal = EMA(self.macd, period=9)
bt.indicators.MACDHisto(self.data)```

```        # 计算rsv的3周期加权平均值，即K值
self.K = bt.indicators.EMA(self.rsv, period=3, plot=False)
# D值=K值的3周期加权平均值
self.D = bt.indicators.EMA(self.K, period=3, plot=False)```

```        if not self.position:
# 买入基于MACD策略
condition1 = self.macd[-1] - self.signal[-1]
condition2 = self.macd[0] - self.signal[0]
if condition1 < 0 and condition2 > 0:

else:
# 卖出基于KDJ策略
condition1 = self.J[-1] - self.D[-1]
condition2 = self.J[0] - self.D[0]
if condition1 > 0 or condition2 < 0:
self.log("SELL CREATE, %.2f" % self.dataclose[0])
self.order = self.sell()```

​Python实用宝典 ( pythondict.com )

### 评论：

1 条评论，访客：0 条，站长：0 条

• 好评：(100%)
• 中评：(0%)
• 差评：(0%)

### 最新评论

1. catiglu发布于：
评分：