Fixed Holding Period: Selling After 10 Bars
-
Here are some brief points about my problem:
l am trying to exit all positions after holding them for a period of 10 bars (not days).
I have looked through the package site and the forums. But, most of the materials I find seem to cover date-time based exits, not bar-based exits. The only pipeline I found for a bar-based exit didn't work for my multiple feed problem:
I managed to "panel" bit the code from the bar-based exit. It executes smoothly. It buys the correct stocks. However, the problem is: it mixes up the exit signals for the stocks.
Here is the complete code I am using:
# Trading Strategy class FixedExitStrategy(bt.Strategy): def __init__(self): pass def start(self): self.size = None def next(self): for i, d in enumerate(self.getdatanames()): pos = self.getposition(data=self.getdatabyname(d)) if not pos.size: if self.getdatabyname(d).signal[0] != self.getdatabyname(d).signal[-1]: if self.getdatabyname(d).signal[0] == 1: self.size = self.getdatabyname(d).position_size[0] self.buy(data=self.getdatabyname(d), size=self.size) self.bought_bar = len(self) if pos.size: self.bars_since_purchase = len(self) - self.bought_bar if self.bars_since_purchase == 10: self.close(data=self.getdatabyname(d), size=self.size)
-
it seems that you are using the same
bought_bar
andbars_since_purchase
variables for all data feeds instead of keeping those attributes per data feed.Something like:
class FixedExitStrategy(bt.Strategy): def __init__(self): pass def start(self): self.bought_bars={d:0 for d in self.getdatanames()} self.bought_sizes={d:0 for d in self.getdatanames()} def next(self): for i, d in enumerate(self.getdatanames()): data = self.getdatabyname(d) pos = self.getposition(data=data) if not pos.size: if data.signal[0] != data.signal[-1]: if data.signal[0] == 1: self.bought_sizes[d] = data.position_size[0] self.buy(data=data, size=self.bought_sizes[d]) self.bought_bars[d] = len(self) if pos.size: if (len(self) - self.bought_bars[d]) == 10: self.close(data=data, size=self.bought_sizes[d])
And I'm not sure where the
self.getdatabyname(d).position_size
is coming from - sorry. -
Thank you for the help. It works properly now.