Update strategies.py
Browse files- strategies.py +178 -107
strategies.py
CHANGED
@@ -1,108 +1,179 @@
|
|
1 |
-
from backtesting import Backtest, Strategy
|
2 |
-
from backtesting.lib import SignalStrategy, TrailingStrategy
|
3 |
-
from indicators import SMC, EMA
|
4 |
-
from data_fetcher import fetch
|
5 |
-
import pandas as pd
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
if self.
|
23 |
-
self.
|
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 |
-
trade.
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
def
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
bt.plot()
|
|
|
1 |
+
from backtesting import Backtest, Strategy
|
2 |
+
from backtesting.lib import SignalStrategy, TrailingStrategy
|
3 |
+
from indicators import SMC, EMA
|
4 |
+
from data_fetcher import fetch
|
5 |
+
import pandas as pd
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
class SMC_test(Strategy):
|
9 |
+
swing_hl = 10
|
10 |
+
def init(self):
|
11 |
+
super().init()
|
12 |
+
|
13 |
+
# Setting smc buy and sell indicators.
|
14 |
+
self.smc_b = self.I(self.smc_buy, data=self.data.df, swing_hl=self.swing_hl)
|
15 |
+
self.smc_s = self.I(self.smc_sell, data=self.data.df, swing_hl=self.swing_hl)
|
16 |
+
|
17 |
+
def next(self):
|
18 |
+
price = self.data.Close[-1]
|
19 |
+
current_time = self.data.index[-1]
|
20 |
+
|
21 |
+
# If buy signal, set target 5% above price and stoploss 5% below price.
|
22 |
+
if self.smc_b[-1] == 1:
|
23 |
+
self.buy(sl=.95 * price, tp=1.05 * price)
|
24 |
+
# If sell signal, set targe 5% below price and stoploss 5% above price.
|
25 |
+
if self.smc_s[-1] == -1:
|
26 |
+
self.sell(tp=.95 * price, sl=1.05 * price)
|
27 |
+
|
28 |
+
# Additionally, set aggressive stop-loss on trades that have been open
|
29 |
+
# for more than two days
|
30 |
+
for trade in self.trades:
|
31 |
+
if current_time - trade.entry_time > pd.Timedelta('2 days'):
|
32 |
+
if trade.is_long:
|
33 |
+
trade.sl = max(trade.sl, self.data.Low[-1])
|
34 |
+
else:
|
35 |
+
trade.sl = min(trade.sl, self.data.High[-1])
|
36 |
+
|
37 |
+
def smc_buy(self, data, swing_hl):
|
38 |
+
return SMC(data, swing_hl).backtest_buy_signal_ob()
|
39 |
+
|
40 |
+
def smc_sell(self, data, swing_hl):
|
41 |
+
return SMC(data, swing_hl).backtest_sell_signal_ob()
|
42 |
+
|
43 |
+
|
44 |
+
class SMC_ema(SignalStrategy, TrailingStrategy):
|
45 |
+
ema1 = 9
|
46 |
+
ema2 = 21
|
47 |
+
close_on_crossover = False
|
48 |
+
|
49 |
+
def init(self):
|
50 |
+
super().init()
|
51 |
+
|
52 |
+
# Setting smc buy and sell indicators.
|
53 |
+
self.smc_b = self.I(self.smc_buy, self.data.df)
|
54 |
+
self.smc_s = self.I(self.smc_sell, self.data.df)
|
55 |
+
|
56 |
+
close = self.data.Close
|
57 |
+
|
58 |
+
# Setting up EMAs.
|
59 |
+
self.ma1 = self.I(EMA, close, self.ema1)
|
60 |
+
self.ma2 = self.I(EMA, close, self.ema2)
|
61 |
+
|
62 |
+
|
63 |
+
def next(self):
|
64 |
+
price = self.data.Close[-1]
|
65 |
+
current_time = self.data.index[-1]
|
66 |
+
|
67 |
+
# If buy signal and short moving average is above long moving average.
|
68 |
+
if self.smc_b[-1] == 1 and self.ma1 > self.ma2:
|
69 |
+
self.buy(sl=.95 * price, tp=1.05 * price)
|
70 |
+
# If sell signal and short moving average is below long moving average.
|
71 |
+
if self.smc_s[-1] == -1 and self.ma1 < self.ma2:
|
72 |
+
self.sell(tp=.95 * price, sl=1.05 * price)
|
73 |
+
|
74 |
+
# Additionally, set aggressive stop-loss on trades that have been open
|
75 |
+
# for more than two days
|
76 |
+
for trade in self.trades:
|
77 |
+
if current_time - trade.entry_time > pd.Timedelta('2 days'):
|
78 |
+
if trade.is_long:
|
79 |
+
trade.sl = max(trade.sl, self.data.Low[-1])
|
80 |
+
else:
|
81 |
+
trade.sl = min(trade.sl, self.data.High[-1])
|
82 |
+
|
83 |
+
# Close the trade if there is a moving average crossover in opposite direction
|
84 |
+
if self.close_on_crossover:
|
85 |
+
for trade in self.trades:
|
86 |
+
if trade.is_long and self.ma1 < self.ma2:
|
87 |
+
trade.close()
|
88 |
+
if trade.is_short and self.ma1 > self.ma2:
|
89 |
+
trade.close()
|
90 |
+
|
91 |
+
def smc_buy(self, data):
|
92 |
+
return SMC(data).backtest_buy_signal_ob()
|
93 |
+
|
94 |
+
def smc_sell(self, data):
|
95 |
+
return SMC(data).backtest_sell_signal_ob()
|
96 |
+
|
97 |
+
|
98 |
+
class SMCStructure(TrailingStrategy):
|
99 |
+
swing_window = 20
|
100 |
+
|
101 |
+
def init(self):
|
102 |
+
super().init()
|
103 |
+
self.smc_b = self.I(self.smc_buy, data=self.data.df, swing_hl=self.swing_window)
|
104 |
+
self.smc_s = self.I(self.smc_sell, data=self.data.df, swing_hl=self.swing_window)
|
105 |
+
self.set_trailing_sl(2)
|
106 |
+
# self.swing = self.I(self.nearest_swing, data=self.data.df, swing_hl)
|
107 |
+
|
108 |
+
def next(self):
|
109 |
+
price = self.data.Close[-1]
|
110 |
+
current_time = self.data.index[-1]
|
111 |
+
|
112 |
+
if self.smc_b[-1] == 1:
|
113 |
+
nearest = self.nearest_swing(self.data.df, self.swing_window)
|
114 |
+
target = price + ((price - nearest)* .414)
|
115 |
+
stoploss = price - (target-price)
|
116 |
+
# print(f"buy: {current_time}, {price}, {nearest}, {target}, {stoploss}")
|
117 |
+
try:
|
118 |
+
self.buy(sl=stoploss, tp=target)
|
119 |
+
except:
|
120 |
+
print('Buying failed')
|
121 |
+
if self.smc_s[-1] == 1:
|
122 |
+
nearest = self.nearest_swing(self.data.df, self.swing_window)
|
123 |
+
print(self.data.df.iloc[-1])
|
124 |
+
if nearest > price:
|
125 |
+
target = price - ((nearest - price) * .414)
|
126 |
+
stoploss = price + (price - target)
|
127 |
+
# print(f"sell: {current_time}, {price}, {nearest}, {target}, {stoploss}")
|
128 |
+
try:
|
129 |
+
self.sell(sl=stoploss, tp=target, limit=float(price))
|
130 |
+
except:
|
131 |
+
print("Selling failed")
|
132 |
+
|
133 |
+
# Additionally, set aggressive stop-loss on trades that have been open
|
134 |
+
# for more than two days
|
135 |
+
for trade in self.trades:
|
136 |
+
if current_time - trade.entry_time > pd.Timedelta('2 days'):
|
137 |
+
if trade.is_long:
|
138 |
+
trade.sl = max(trade.sl, self.data.Low[-1])
|
139 |
+
else:
|
140 |
+
trade.sl = min(trade.sl, self.data.High[-1])
|
141 |
+
|
142 |
+
def smc_buy(self, data, swing_hl):
|
143 |
+
return SMC(data, swing_hl).backtest_buy_signal_structure()
|
144 |
+
|
145 |
+
def smc_sell(self, data, swing_hl):
|
146 |
+
return SMC(data, swing_hl).backtest_sell_signal_structure()
|
147 |
+
|
148 |
+
def nearest_swing(self, data, swing_hl):
|
149 |
+
# Get swing high/low nearest to current price.
|
150 |
+
swings = SMC(data, swing_hl).swing_hl
|
151 |
+
swings = swings[~np.isnan(swings['Level'])]
|
152 |
+
return swings['Level'].iloc[-2]
|
153 |
+
|
154 |
+
|
155 |
+
def smc_plot_backtest(data, filename, swing_hl, **kwargs):
|
156 |
+
bt = Backtest(data, SMC_test, **kwargs)
|
157 |
+
bt.run(swing_hl=swing_hl)
|
158 |
+
return bt.plot(filename=filename, open_browser=False)
|
159 |
+
|
160 |
+
def smc_ema_plot_backtest(data, filename, ema1, ema2, closecross, **kwargs):
|
161 |
+
bt = Backtest(data, SMC_ema, **kwargs)
|
162 |
+
bt.run(ema1=ema1, ema2=ema2, close_on_crossover=closecross)
|
163 |
+
return bt.plot(filename=filename, open_browser=False)
|
164 |
+
|
165 |
+
def smc_structure_backtest(data, filename, swing_hl, **kwargs):
|
166 |
+
bt = Backtest(data, SMCStructure, **kwargs)
|
167 |
+
bt.run(swing_window=swing_hl)
|
168 |
+
return bt.plot(filename=filename, open_browser=False)
|
169 |
+
|
170 |
+
if __name__ == "__main__":
|
171 |
+
# data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
|
172 |
+
data = fetch('RELIANCE.NS', period='1mo', interval='15m')
|
173 |
+
# data = fetch('AXISBANK.NS', period='1mo', interval='15m')
|
174 |
+
# bt = Backtest(data, SMC_ema, commission=.002)
|
175 |
+
# bt.run(ema1 = 9, ema2 = 21, close_on_crossover=True)
|
176 |
+
bt = Backtest(data, SMCStructure, commission = .002, trade_on_close=True)
|
177 |
+
bt.run()
|
178 |
+
|
179 |
bt.plot()
|