backtesting.py
backtesting.py copied to clipboard
using the barssince function to close a position after x bars
Hi,
I am trying to backtest a strategy that closes x bars after entry. Would you please provide a 'barssince' code example for this?
thank you!
Hello, here is one of example. (I am beginner of backtesting.py.)
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA, GOOG
class SmaCross(Strategy):
n1 = 10
n2 = 20
current_bar = 0
exit_bar = 20
def init(self):
close = self.data.Close
self.sma1 = self.I(SMA, close, self.n1)
self.sma2 = self.I(SMA, close, self.n2)
def next(self):
if crossover(self.sma1, self.sma2) and not self.position.is_long:
self.buy()
elif self.position.is_long:
if self.current_bar == 0:
self.current_bar = self.trades[0].entry_bar
else:
self.current_bar += 1
if self.current_bar >= self.trades[0].entry_bar + self.exit_bar:
self.position.close()
self.current_bar = 0
bt = Backtest(GOOG, SmaCross,
cash=10000, commission=.002,
exclusive_orders=True)
output = bt.run()
bt.plot()
print(output)
thank you for replying - I appreciate it.. I have found a way to do it also, but not using barssince.. here's one you might like:
import backtesting from backtesting import Strategy, Backtest import datetime
class CanStrat(Strategy):
def init(self):
super().init()
self.signal = self.I(SIGNAL)
def next(self):
super().next()
if self.signal == 1:
if not self.position:
self.buy(size=0.99)
if len(self.trades) > 0:
if self.data.index[-1] - self.trades[-1].entry_time > datetime.timedelta(days=8):
self.trades[-1].close()
bt = Backtest(df, CanStrat, cash=100_000, margin=1, exclusive_orders=True) stat = bt.run() stat
Example you can change "condition" as you like. "condition" is needed to be sequence (Series etc).
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA, GOOG
import backtesting.lib as lib
import pandas as pd
import datetime as dt
GOOG = GOOG[dt.datetime(2005,1,1):dt.datetime(2005,12,31)]
class SmaCross(Strategy):
n1 = 10
n2 = 20
def init(self):
close = self.data.Close
self.sma1 = self.I(SMA, close, self.n1)
self.sma2 = self.I(SMA, close, self.n2)
def next(self):
condition = self.sma1 < self.sma2
if crossover(self.sma1, self.sma2) and not self.position.is_long:
self.buy()
elif self.position.is_long and lib.barssince(condition) > 3:
self.position.close()
bt = Backtest(GOOG, SmaCross,
cash=10000, commission=.002,
exclusive_orders=True)
output = bt.run()
bt.plot()