Abnormal behavior of the CrossOver class
-
Hi All,
Can someone comments, I don't understand behavior of the class CrossOver.
Simple strategy:
if EMA (30) Сrosses UP WMA(30) - buy
if EMA (30) Сrosses Down WMA(30) - sellimport sys import backtrader as bt from datetime import datetime, timedelta import backtrader.indicators as btind import backtrader.feeds as btfeed from backtrader_plotting import Bokeh from backtrader_plotting.schemes import Tradimo import argparse import logging logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format='%(asctime)s [%(levelname)s][module: %(module)s.py] %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) class MyTradimo(Tradimo): def _set_params(self): super()._set_params() # Disable the output of Volume on the displayed chart self.volume=False class CommFixed(bt.CommInfoBase): params = ( ('stocklike', False), ('commtype', bt.CommInfoBase.COMM_FIXED), ) class TestedStrategy(bt.SignalStrategy): def __init__(self): self.order = None self.ema = btind.ExponentialMovingAverage(self.data.close) self.lwma = btind.WeightedMovingAverage(self.data.close) self.buysell = btind.CrossOver(self.lwma, self.ema) def next(self): if self.buysell < 0: self.sell(exectype=bt.Order.Market) elif self.buysell > 0: self.buy(exectype=bt.Order.Market) def parse_args(pargs=None): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Sample for Signal concepts') parser.add_argument('--data', required=False, default='csv/BTCUSD_M5_2021_01_28__21_35-2021_02_02__21_25.csv', help='Specific data to be read in') parser.add_argument('--fromdate', required=False, default=None, help='Starting date in YYYY-MM-DD[THH:MM:SS] format') if pargs is not None: return parser.parse_args(pargs) return parser.parse_args() def runstrat(args=None): args = parse_args(args) if args.fromdate: fmtstr = '%Y-%m-%d' dtsplit = args.fromdate.split('T') if len(dtsplit) > 1: fmtstr += 'T%H:%M:%S' start_date = datetime.strptime(args.fromdate, fmtstr) else: start_date = datetime(2021,1,31,23,00) end_date = datetime(2021,2,1,18,00) logger.info("Start: {} End: {}".format(start_date, end_date)) data = btfeed.GenericCSVData( dataname='BTCUSD_M5_2021_01_28__21_40-2021_02_02__21_35.csv', dtformat=('%Y.%m.%d %H:%M:%S'), timeframe=bt.TimeFrame.Minutes, compression=5, fromdate=start_date, todate=end_date, ) cerebro = bt.Cerebro(stdstats=False) cerebro.adddata(data) cerebro.addstrategy(TestedStrategy) cerebro.broker.setcash(1000) cerebro.broker.addcommissioninfo(CommFixed, "CommFixed") cerebro.addobserver(bt.observers.BuySell) cerebro.run() b = Bokeh(style='bar', tabs='multi', scheme=MyTradimo()) cerebro.plot(b) if __name__ == '__main__': runstrat()
We are doing two tests:
- BTC, M5, Start: 2021-01-31 22:35:00 End: 2021-02-01 18:00:00
- BTC, M5, Start: 2021-01-31 22:40:00 End: 2021-02-01 18:00:00
We see such results:
-
OK
-
Where is BUY?!
It looked more complicated in the code - I simplified everything as much as possible for an example.
-
@dmitry-prokopiev said in Abnormal behavior of the CrossOver class:
cerebro.broker.setcash(1000)
It probably makes sense to increase the cash available for the broker.
-
@vladisld thnx, worked.
But I don't understand what the relationship is cash on the broker and not open BUY position ...
Could you tell me why this is so ?! Or what to read in the documentation?
-
@dmitry-prokopiev said in Abnormal behavior of the CrossOver class:
what the relationship is cash on the broker and not open BUY position
there was not enough cash for the broker to buy even a single contract at that price level ( cash = 1000 < price = 33550).
@dmitry-prokopiev said in Abnormal behavior of the CrossOver class:
what to read in the documentation
probably this one: https://www.backtrader.com/docu/broker/
-
@vladisld Uh ... Thnx, I forgot about the lot size.