forked from mementum/backtrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacd-settings.py
289 lines (221 loc) · 10.3 KB
/
macd-settings.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2023 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import datetime
import random
import backtrader as bt
BTVERSION = tuple(int(x) for x in bt.__version__.split('.'))
class FixedPerc(bt.Sizer):
'''This sizer simply returns a fixed size for any operation
Params:
- ``perc`` (default: ``0.20``) Perc of cash to allocate for operation
'''
params = (
('perc', 0.20), # perc of cash to use for operation
)
def _getsizing(self, comminfo, cash, data, isbuy):
cashtouse = self.p.perc * cash
if BTVERSION > (1, 7, 1, 93):
size = comminfo.getsize(data.close[0], cashtouse)
else:
size = cashtouse // data.close[0]
return size
class TheStrategy(bt.Strategy):
'''
This strategy is loosely based on some of the examples from the Van
K. Tharp book: *Trade Your Way To Financial Freedom*. The logic:
- Enter the market if:
- The MACD.macd line crosses the MACD.signal line to the upside
- The Simple Moving Average has a negative direction in the last x
periods (actual value below value x periods ago)
- Set a stop price x times the ATR value away from the close
- If in the market:
- Check if the current close has gone below the stop price. If yes,
exit.
- If not, update the stop price if the new stop price would be higher
than the current
'''
params = (
# Standard MACD Parameters
('macd1', 12),
('macd2', 26),
('macdsig', 9),
('atrperiod', 14), # ATR Period (standard)
('atrdist', 3.0), # ATR distance for stop price
('smaperiod', 30), # SMA Period (pretty standard)
('dirperiod', 10), # Lookback period to consider SMA trend direction
)
def notify_order(self, order):
if order.status == order.Completed:
pass
if not order.alive():
self.order = None # indicate no order is pending
def __init__(self):
self.macd = bt.indicators.MACD(self.data,
period_me1=self.p.macd1,
period_me2=self.p.macd2,
period_signal=self.p.macdsig)
# Cross of macd.macd and macd.signal
self.mcross = bt.indicators.CrossOver(self.macd.macd, self.macd.signal)
# To set the stop price
self.atr = bt.indicators.ATR(self.data, period=self.p.atrperiod)
# Control market trend
self.sma = bt.indicators.SMA(self.data, period=self.p.smaperiod)
self.smadir = self.sma - self.sma(-self.p.dirperiod)
def start(self):
self.order = None # sentinel to avoid operrations on pending order
def next(self):
if self.order:
return # pending order execution
if not self.position: # not in the market
if self.mcross[0] > 0.0 and self.smadir < 0.0:
self.order = self.buy()
pdist = self.atr[0] * self.p.atrdist
self.pstop = self.data.close[0] - pdist
else: # in the market
pclose = self.data.close[0]
pstop = self.pstop
if pclose < pstop:
self.close() # stop met - get out
else:
pdist = self.atr[0] * self.p.atrdist
# Update only if greater than
self.pstop = max(pstop, pclose - pdist)
DATASETS = {
'yhoo': '../../datas/yhoo-1996-2014.txt',
'orcl': '../../datas/orcl-1995-2014.txt',
'nvda': '../../datas/nvda-1999-2014.txt',
}
def runstrat(args=None):
args = parse_args(args)
cerebro = bt.Cerebro()
cerebro.broker.set_cash(args.cash)
comminfo = bt.commissions.CommInfo_Stocks_Perc(commission=args.commperc,
percabs=True)
cerebro.broker.addcommissioninfo(comminfo)
dkwargs = dict()
if args.fromdate is not None:
fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
dkwargs['fromdate'] = fromdate
if args.todate is not None:
todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
dkwargs['todate'] = todate
# if dataset is None, args.data has been given
dataname = DATASETS.get(args.dataset, args.data)
data0 = bt.feeds.YahooFinanceCSVData(dataname=dataname, **dkwargs)
cerebro.adddata(data0)
cerebro.addstrategy(TheStrategy,
macd1=args.macd1, macd2=args.macd2,
macdsig=args.macdsig,
atrperiod=args.atrperiod,
atrdist=args.atrdist,
smaperiod=args.smaperiod,
dirperiod=args.dirperiod)
cerebro.addsizer(FixedPerc, perc=args.cashalloc)
# Add TimeReturn Analyzers for self and the benchmark data
cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='alltime_roi',
timeframe=bt.TimeFrame.NoTimeFrame)
cerebro.addanalyzer(bt.analyzers.TimeReturn, data=data0, _name='benchmark',
timeframe=bt.TimeFrame.NoTimeFrame)
# Add TimeReturn Analyzers fot the annuyl returns
cerebro.addanalyzer(bt.analyzers.TimeReturn, timeframe=bt.TimeFrame.Years)
# Add a SharpeRatio
cerebro.addanalyzer(bt.analyzers.SharpeRatio, timeframe=bt.TimeFrame.Years,
riskfreerate=args.riskfreerate)
# Add SQN to qualify the trades
cerebro.addanalyzer(bt.analyzers.SQN)
cerebro.addobserver(bt.observers.DrawDown) # visualize the drawdown evol
results = cerebro.run()
st0 = results[0]
for alyzer in st0.analyzers:
alyzer.print()
if args.plot:
pkwargs = dict(style='bar')
if args.plot is not True: # evals to True but is not True
npkwargs = eval('dict(' + args.plot + ')') # args were passed
pkwargs.update(npkwargs)
cerebro.plot(**pkwargs)
def parse_args(pargs=None):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Sample for Tharp example with MACD')
group1 = parser.add_mutually_exclusive_group(required=True)
group1.add_argument('--data', required=False, default=None,
help='Specific data to be read in')
group1.add_argument('--dataset', required=False, action='store',
default=None, choices=DATASETS.keys(),
help='Choose one of the predefined data sets')
parser.add_argument('--fromdate', required=False,
default='2005-01-01',
help='Starting date in YYYY-MM-DD format')
parser.add_argument('--todate', required=False,
default=None,
help='Ending date in YYYY-MM-DD format')
parser.add_argument('--cash', required=False, action='store',
type=float, default=50000,
help=('Cash to start with'))
parser.add_argument('--cashalloc', required=False, action='store',
type=float, default=0.20,
help=('Perc (abs) of cash to allocate for ops'))
parser.add_argument('--commperc', required=False, action='store',
type=float, default=0.0033,
help=('Perc (abs) commision in each operation. '
'0.001 -> 0.1%%, 0.01 -> 1%%'))
parser.add_argument('--macd1', required=False, action='store',
type=int, default=12,
help=('MACD Period 1 value'))
parser.add_argument('--macd2', required=False, action='store',
type=int, default=26,
help=('MACD Period 2 value'))
parser.add_argument('--macdsig', required=False, action='store',
type=int, default=9,
help=('MACD Signal Period value'))
parser.add_argument('--atrperiod', required=False, action='store',
type=int, default=14,
help=('ATR Period To Consider'))
parser.add_argument('--atrdist', required=False, action='store',
type=float, default=3.0,
help=('ATR Factor for stop price calculation'))
parser.add_argument('--smaperiod', required=False, action='store',
type=int, default=30,
help=('Period for the moving average'))
parser.add_argument('--dirperiod', required=False, action='store',
type=int, default=10,
help=('Period for SMA direction calculation'))
parser.add_argument('--riskfreerate', required=False, action='store',
type=float, default=0.01,
help=('Risk free rate in Perc (abs) of the asset for '
'the Sharpe Ratio'))
# Plot options
parser.add_argument('--plot', '-p', nargs='?', required=False,
metavar='kwargs', const=True,
help=('Plot the read data applying any kwargs passed\n'
'\n'
'For example:\n'
'\n'
' --plot style="candle" (to plot candles)\n'))
if pargs is not None:
return parser.parse_args(pargs)
return parser.parse_args()
if __name__ == '__main__':
runstrat()