-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Why I am having many trades even if exclusive_orders=True #1036
-
Hello everyone, i am backtesting an SMA strategy, i want to implement the following logic : It will be a buy only strategy, we trigger a buy signal if crossover(self.sma1, self.sma2)
, if crossover(self.sma2, self.sma1)
I want to reduce my last position to 80%, i did that using self.position.close(portion = 0.8)
, the problem is that i don't want many orders at the same time.
Here is my code :
class SmaCross(Strategy):
n1 = 10
n2 = 50
def init(self):
close = self.data.Close
ref = self.data.ref
self.sma1 = self.I(SMA, ref, self.n1)
self.sma2 = self.I(SMA, ref, self.n2)
def next(self):
if crossover(self.sma1, self.sma2):
self.buy()
elif crossover(self.sma2, self.sma1):
self.position.close(portion = 0.8)
bt = Backtest(df,SmaCross,cash=1000,commission=0.000,margin=0.84,exclusive_orders=True)
output1=bt.run()
bt.plot()
exclusive_orders =True, and i cannot understand why i am having sometimes two trades at same time.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
I wasn't able to run your code; not sure what your data frame column ref
is, but it looks as if you might be misinterpreting multiple sell signals, not buy signals. Here is a colab notebook with your example but using the GOOG dataframe provided with backtesting.py
As you can see from the _trades
dataframe the trades were entered at the same time, then 80% were sold at the first exit signal and then the remainder was sold at the second trade.
(SideNote, backtesting.py uses only whole shares, no fractional shares. This trips up a lot of people at first. If you want to simulate something more precise then give your simulation more initial capital or divide the price dataframe by 1000)
So in the first buy you bought 6 shares then sold 80% rounded to the nearest whole share (5 shares sold leaving 1) and then on the next trigger, you sold the last share you had. This then repeats for the next buy and next buy etc.
imageHope this helps.
https://colab.research.google.com/drive/1dp3P6JqAZhzEoH7tY0ib270LhWblKTC9?usp=sharing
Beta Was this translation helpful? Give feedback.