Help with starting my first code
-
Hello,
I am a newbee to backtrader and I am trying to backtest my strategy but whenever I start my code it gets stuck and I don't get any output. Can someone please help me here.
Thanks in advanceclass ABC(bt.Strategy):
alias = ('ABC',)# list of parameters which are configurable for the strategy params = dict( sma50=10, # period for the fast moving average pslow=30 # period for the slow moving average ) def log(self, txt, dt=None): ''' Logging function for this strategy''' dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): self.log(f'Initial portfolio value of {self.broker.get_value():.2f}\n') self.sma20 = bt.ind.SMA(period=20) # fast moving average self.sma50 = bt.ind.SMA(period=50) # slow moving average # self.stddev = self.data.close.rolling(window=20).std() self.stddev = bt.ind.StdDev(self.close,period=20) self.lower_band = self.sma20 - (2 * self.stddev) self.upper_band = self.sma20 + (2 * self.stddev) offset = 0.005 * self.data.close a = abs(self.sma50 - self.lower_band) b = abs(self.data.Low - self.lower_band) c = abs(self.data.close - self.lower_band) self.buy_sig = bt.And(a < offset, bt.Or(b < offset,c < offset)) def next(self): tar = 0 SL = 0 print("Scanning") if not self.position: # not in the market if self.buy_sig > 0: self.log(f'BUY {self.getsizing()} shares of {self.data._name} at {self.data.close[0]}') print('Entered Trade') if self.data.close[0] > self.data.close[-1]: # if fast crosses slow to the upside if self.sma50[0] > self.sma2[-3]: if self.sma50[-3] > self.sma2[-6]: if self.sma50[-6] < self.sma2[-9]: self.buy() # enter long tar = self.data.close[0] + 10 SL = self.data.close[0] + 10 elif self.data.close[0]>tar: self.sell() # exit long self.log(f'CLOSE LONG position of {self.position.size} shares ' f'of {self.data._name} at {self.data.close[0]:.2f}') # elif self.data.close[0]<SL: elif self.data.close[0] <SL: self.sell() # exit long self.log(f'CLOSE LONG position of {self.position.size} shares ' f'of {self.data._name} at {self.data.close[0]:.2f}') print('Do nothing')
-
@shubham You don't seem to be calling the Cerebro. If there is no call to Cerebro, there will be no output, its plain class.
-
@vypy1
I have a function called startBackTestEngine which calls the class above but still I am not able to get an output. I call the above class from this functiondef startBackTestEngine(strategyName): btdata = GenericCSVData(dataname='backtestEngine_ABC.csv', dtformat=('%Y-%m-%d'), datetime=0, high=5, low=6, open=4, close=8, volume=10, openinterest=-1, # fromdate=date(2021, 2, 16), # todate=date(2021, 2, 16) ) # Create Buy and Sell Signal Observers # Create cerebro Engine cerebro = bt.Cerebro() # Set Fixed Position Sizing cerebro.addsizer(bt.sizers.SizerFix, stake=20) # Add datafeed to Cerebro Engine cerebro.adddata(btdata) # Set Initial Trading Capital and Trading Commissions cerebro.broker.setcash(300000.0) cerebro.broker.setcommission(commission=0.002) # Add Trading Strategy to Cerebro cerebro.addstrategy(strategyName) # Add Buy Sell Signals Observer to Cerebro cerebro.addobserver(bt.observers.Value) # Add Trading Statistics Analyzer cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio') bt.observers.BuySell = BuySellSignal # Run Cerebro Engine start_portfolio_value = cerebro.broker.getvalue() cerebro.run() end_portfolio_value = cerebro.broker.getvalue() pnl = end_portfolio_value - start_portfolio_value print(f'Starting Portfolio Value: {start_portfolio_value:.2f}') print(f'Final Portfolio Value: {end_portfolio_value:.2f}') print(f'PnL: {pnl:.2f}') # Plot the Line Chart with Buy or Sell Signals cerebro.plot()
-
@shubham Personally my advice would be to spend time in the docs and copy/build simple backtests before taking this on.
-
@shubham To me the code itself is not clear. Where is the inheritance coming from to startbacktestengine? I mean what class is that?
Also where in the mail code have you mentioned this?
-
@vypy1 I simply call this backtesting function from my main as shown below:
startBackTestEngine(ABC)