Invicto69 commited on
Commit
edba830
·
verified ·
1 Parent(s): 7997e91

Update strategies.py

Browse files
Files changed (1) hide show
  1. 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
- class SMC_test(Strategy):
8
- swing_hl = 10
9
- def init(self):
10
- super().init()
11
-
12
- self.smc_b = self.I(self.smc_buy, data=self.data.df, swing_hl=self.swing_hl)
13
- self.smc_s = self.I(self.smc_sell, data=self.data.df, swing_hl=self.swing_hl)
14
-
15
-
16
- def next(self):
17
- price = self.data.Close[-1]
18
- current_time = self.data.index[-1]
19
-
20
- if self.smc_b[-1] == 1:
21
- self.buy(sl=.95 * price, tp=1.05 * price)
22
- if self.smc_s[-1] == -1:
23
- self.sell(tp=.95 * price, sl=1.05 * price)
24
-
25
- # Additionally, set aggressive stop-loss on trades that have been open
26
- # for more than two days
27
- for trade in self.trades:
28
- if current_time - trade.entry_time > pd.Timedelta('2 days'):
29
- if trade.is_long:
30
- trade.sl = max(trade.sl, self.data.Low[-1])
31
- else:
32
- trade.sl = min(trade.sl, self.data.High[-1])
33
-
34
-
35
- def smc_buy(self, data, swing_hl):
36
- return SMC(data, swing_hl).backtest_buy_signal()
37
-
38
- def smc_sell(self, data, swing_hl):
39
- return SMC(data, swing_hl).backtest_sell_signal()
40
-
41
- class SMC_ema(SignalStrategy, TrailingStrategy):
42
- ema1 = 9
43
- ema2 = 21
44
- close_on_crossover = False
45
-
46
- def init(self):
47
- super().init()
48
-
49
- self.smc_b = self.I(self.smc_buy, self.data.df)
50
- self.smc_s = self.I(self.smc_sell, self.data.df)
51
-
52
-
53
- close = self.data.Close
54
-
55
- self.ma1 = self.I(EMA, close, self.ema1)
56
- self.ma2 = self.I(EMA, close, self.ema2)
57
-
58
-
59
- def next(self):
60
- price = self.data.Close[-1]
61
- current_time = self.data.index[-1]
62
-
63
- if self.smc_b[-1] == 1 and self.ma1 > self.ma2:
64
- self.buy(sl=.95 * price, tp=1.05 * price)
65
- if self.smc_s[-1] == -1 and self.ma1 < self.ma2:
66
- self.sell(tp=.95 * price, sl=1.05 * price)
67
-
68
- # Additionally, set aggressive stop-loss on trades that have been open
69
- # for more than two days
70
- for trade in self.trades:
71
- if current_time - trade.entry_time > pd.Timedelta('2 days'):
72
- if trade.is_long:
73
- trade.sl = max(trade.sl, self.data.Low[-1])
74
- else:
75
- trade.sl = min(trade.sl, self.data.High[-1])
76
-
77
- # Close the trade if there is a moving average crossover in opposite direction
78
- if self.close_on_crossover:
79
- for trade in self.trades:
80
- if trade.is_long and self.ma1 < self.ma2:
81
- trade.close()
82
- if trade.is_short and self.ma1 > self.ma2:
83
- trade.close()
84
-
85
- def smc_buy(self, data):
86
- return SMC(data).backtest_buy_signal()
87
-
88
- def smc_sell(self, data):
89
- return SMC(data).backtest_sell_signal()
90
-
91
- def smc_plot_backtest(data, filename, swing_hl, **kwargs):
92
- bt = Backtest(data, SMC_test, **kwargs)
93
- bt.run(swing_hl=swing_hl)
94
- print('runned')
95
- return bt.plot(filename=filename, open_browser=False)
96
-
97
- def smc_ema_plot_backtest(data, filename, ema1, ema2, closecross, **kwargs):
98
- bt = Backtest(data, SMC_ema, **kwargs)
99
- bt.run(ema1=ema1, ema2=ema2, close_on_crossover=closecross)
100
- return bt.plot(filename=filename, open_browser=False)
101
-
102
-
103
- if __name__ == "__main__":
104
- data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
105
- bt = Backtest(data, SMC_ema, commission=.002)
106
-
107
- bt.run(ema1 = 9, ema2 = 21, close_on_crossover=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()