Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Abnormal behavior of the CrossOver class

    General Code/Help
    2
    5
    33
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • D
      dmitry.prokopiev last edited by

      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) - sell

      import 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:

      1. BTC, M5, Start: 2021-01-31 22:35:00 End: 2021-02-01 18:00:00
      2. BTC, M5, Start: 2021-01-31 22:40:00 End: 2021-02-01 18:00:00

      We see such results:

      1. OK
        d185d025-0abe-47a3-beb5-f09c3c20d346-image.png

      2. Where is BUY?!
        2cf4bb0a-bca5-45ad-acdb-0ad0df53ae1c-image.png

      It looked more complicated in the code - I simplified everything as much as possible for an example.

      vladisld 1 Reply Last reply Reply Quote 0
      • vladisld
        vladisld @dmitry.prokopiev last edited by

        @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.

        D 1 Reply Last reply Reply Quote 2
        • D
          dmitry.prokopiev @vladisld last edited by

          @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?

          vladisld 1 Reply Last reply Reply Quote 0
          • vladisld
            vladisld @dmitry.prokopiev last edited by

            @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/

            D 1 Reply Last reply Reply Quote 2
            • D
              dmitry.prokopiev @vladisld last edited by

              @vladisld Uh ... Thnx, I forgot about the lot size.

              1 Reply Last reply Reply Quote 1
              • 1 / 1
              • First post
                Last post
              Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
              $(document).ready(function () { app.coldLoad(); }); }