-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
kdj_macd.py
151 lines (120 loc) · 4.55 KB
/
kdj_macd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""
Author: Charmve [email protected]
Date: 2023-02-13 23:24:15
LastEditors: Charmve [email protected]
LastEditTime: 2023-03-09 23:59:10
FilePath: /Qbot/pytrader/doc/04.kdj_with_macd/kdj_macd.py
Version: 1.0.1
Blogs: charmve.blog.csdn.net
Description:
Copyright (c) 2023 by Charmve, All Rights Reserved.
"""
import datetime
import os.path
import sys
import backtrader as bt
from backtrader.indicators import EMA
class KdjMacdStrategy(bt.Strategy):
def log(self, txt, dt=None):
""" Logging function fot this strategy"""
dt = dt or self.datas[0].datetime.date(0)
print("%s, %s" % (dt.isoformat(), txt))
@staticmethod
def percent(today, yesterday):
return float(today - yesterday) / today
def __init__(self):
self.dataclose = self.datas[0].close
self.volume = self.datas[0].volume
self.order = None
self.buyprice = None
self.buycomm = None
# 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, plot=False)
# D值=K值的3周期加权平均值
self.D = bt.indicators.EMA(self.K, period=3, plot=False)
# J=3*K-2*D
self.J = 3 * self.K - 2 * self.D
# 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)
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
self.log(
"BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f"
% (order.executed.price, order.executed.value, order.executed.comm)
)
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
self.bar_executed_close = self.dataclose[0]
else:
self.log(
"SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f"
% (order.executed.price, order.executed.value, order.executed.comm)
)
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log("Order Canceled/Margin/Rejected")
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log("OPERATION PROFIT, GROSS %.2f, NET %.2f" % (trade.pnl, trade.pnlcomm))
def next(self):
self.log("Close, %.2f" % self.dataclose[0])
if self.order:
return
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:
self.log("BUY CREATE, %.2f" % self.dataclose[0])
self.order = self.buy()
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()
if __name__ == "__main__":
cerebro = bt.Cerebro()
cerebro.addstrategy(KdjMacdStrategy)
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, "002859.csv")
# 加载数据到模型中
data = bt.feeds.GenericCSVData(
dataname=datapath,
fromdate=datetime.datetime(2010, 1, 1),
todate=datetime.datetime(2020, 4, 21),
dtformat="%Y%m%d",
datetime=2,
open=3,
high=4,
low=5,
close=6,
volume=10,
reverse=True,
)
cerebro.adddata(data)
cerebro.broker.setcash(10000)
cerebro.addsizer(bt.sizers.FixedSize, stake=100)
cerebro.broker.setcommission(commission=0.005)
print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
cerebro.run()
print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
cerebro.plot()