Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. amit.kehat
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    • Profile
    • Following 0
    • Followers 0
    • Topics 3
    • Posts 3
    • Best 0
    • Groups 0

    amit.kehat

    @amit.kehat

    0
    Reputation
    3
    Profile views
    3
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    amit.kehat Unfollow Follow

    Latest posts made by amit.kehat

    • Inccorrect execution trade prices in backtesting

      Hello,
      I run backtesting on a data I downloaded using the IB API.
      The data looks like this:

      datetime,open,high,low,close,volume
      2022-04-11 16:30:00,168.75,169.03,167.72,167.77,25499.41
      2022-04-11 16:35:00,167.76,168.52,167.28,167.31,17522.58
      2022-04-11 16:40:00,167.3,167.87,167.19,167.76,14410.43
      2022-04-11 16:45:00,167.75,168.12,167.55,167.77,11796.48
      2022-04-11 16:50:00,167.78,167.94,167.24,167.29,10563.56
      2022-04-11 16:55:00,167.3,167.38,166.88,167.0,10632.27
      2022-04-11 17:00:00,166.98,167.33,166.8,166.95,11671.17
      2022-04-11 17:05:00,166.94,167.27,166.7,166.96,10099.4
      

      From some reason that I don't understand, the entry and exit prices in the backtesting's trades and the data have a big missmatch.

      Cerebro configuration:

      data = bt.feeds.PandasData( dataname = historicalDataDF,
                   fromdate = datetime.datetime(2021, 7, 9),
                   todate = datetime.datetime(2022, 7, 8)
                                  )
      
          cerebro = bt.Cerebro()
          cerebro.adddata(data)
          cerebro.addsizer(bt.sizers.PercentSizer, percents = 90) 
          cerebro.addwriter(bt.WriterFile, out = 'outputs/temp.csv', csv = True)              
          cerebro.broker.setcash(10000.0)
          print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
          cerebro.addstrategy(HMAStrategy)
          cerebro.run()
          cerebro.plot(style='candlestick')
          print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      

      The commands of buy / sell in the strategy is pretty streight forward:

      if enterLongCondition:
                  self.buy(size=10, exectype=bt.Order.Limit, price=self.datas[0].close[0])
      if enterShortCondition:
                  self.sell(size=10, exectype=bt.Order.Limit, price=self.datas[0].close[0])
      

      Some examples to show my problem:

      1. First trade in the backtesting is short position @ $167.05 on 2022-04-18 16:55:00.
        The input data of this bar from the csv file:
      2022-04-18 16:45:00,165.36,165.59,164.9,165.23,10051.64
      2022-04-18 16:50:00,165.24,165.34,164.33,164.39,10852.86
      2022-04-18 16:55:00,164.42,164.59,164.15,164.49,10548.83
      2022-04-18 17:00:00,164.48,165.08,164.09,164.86,10931.75
      2022-04-18 17:05:00,164.88,165.13,164.56,164.59,8418.83
      

      The writter output data:
      Screenshot 2022-07-09 184144.png
      The OHLC of this bar, the bar before and the bar after has values around 164-165.
      Also in the chart, I see the execution position far above the actual price:
      Screenshot 2022-07-09 184508.png
      Why the execution price is so different?

      1. Next 2 trades in the backtest are buy order to close the first short trade @ $161.85 on 2022-04-19 16:30:00 and another short position @ 167.15 on 2022-04-19 16:40:00.
        The input data of this bar from the csv file:
      2022-04-18 22:50:00,164.1,164.61,163.98,164.38,11467.36
      2022-04-18 22:55:00,164.38,165.12,164.32,165.11,16132.13
      2022-04-19 16:30:00,165.0,165.14,164.32,164.47,20037.18
      2022-04-19 16:35:00,164.47,164.74,163.91,164.01,15490.55
      2022-04-19 16:40:00,164.01,164.68,163.91,164.37,11028.66
      2022-04-19 16:45:00,164.37,164.74,164.12,164.58,9502.68
      

      The writter output data:
      Screenshot 2022-07-09 185937.png
      The OHLC of this bar, the bar before and the bar after has values around 164-165.
      Also in the chart, I see the execution position far above and below the actual price:
      Screenshot 2022-07-09 185758.png

      I hope that I managed to show my issue and gave all the required information. If something is missing, please tell and I will add.
      I saw some posts that related to similar issue, but I couldn't find any solution in any of them, so I post my own.

      Thanks,
      Amit

      posted in Indicators/Strategies/Analyzers
      amit.kehat
      amit.kehat
    • IndexError: array index out of range in next()

      Hello,

      I am facing the next issue.
      This is my code:

      class ShortSuperTrend(bt.Indicator):
          lines = ('ShortSuperTrendUp',)
      
          params = (('atr_period', 14), ('Multiplier', 0.6), )
      
          def __init__(self):
            self.atr = bt.talib.ATR(self.datas[0].high, self.datas[0].low, self.datas[0].close, timeperiod=self.params.atr_period)
            self.up = self.datas[0].low - (self.params.Multiplier * self.atr)
            self.up1 = self.up(-1)
            #self.lines.ShortSuperTrendUp = self.up1
               
          def next(self):
            self.up = bt.If(self.datas[0].close[-1] > self.up, bt.Max(self.up, self.up1), self.up[0])
      

      When using indexing with () in the __init__() I am getting the next error:

      TypeError: 'list' object is not callable

      The assignment in the next() function produce the next error:

      IndexError: array index out of range

      My wish is to update self.up with the expression's results for each candle.

      posted in Indicators/Strategies/Analyzers
      amit.kehat
      amit.kehat
    • Strategy optimization never finishes

      Re: Optstrategy

      HI,

      When trying to use the optstrategy method, it never finish... run forever. No error is observed.
      My code:

      from datetime import datetime
      import backtrader as bt
      import matplotlib.pyplot as plt
      %matplotlib inline
      
      class SmaCross(bt.Strategy):
          
          params = (('fast', 10),
                    ('slow', 30)
                   )
          
          def __init__(self):
              self.sma_fast = bt.ind.SMA(period = self.params.fast)
              self.sma_slow = bt.ind.SMA(period = self.params.slow)
              self.crossover = bt.ind.CrossOver(self.sma_fast, self.sma_slow)
      
      
          def start(self): #runs after the init in the beginning
              pass
              
          def next(self): #runs in each iteration
              if self.position.size == 0:
                  if self.sma_fast > self.sma_slow:
                      self.buy()
              elif self.position.size != 0:
                  if self.sma_fast < self.sma_slow:
                      self.sell()
          
          def stop(self): #runs at the end
              pass
      
      contract_history = pd.read_csv('APPL-hourly.csv')
      contract_history['dt'] = pd.to_datetime(contract_history['date'])
      contract_history = contract_history.set_index('dt')
      data_pd = bt.feeds.PandasData(dataname = contract_history, fromdate = datetime(2020, 11, 11),
                                      todate = datetime(2020,12,1))
      
              
      cerebro = bt.Cerebro()
      cerebro.adddata(data_pd)
      cerebro.addsizer(bt.sizers.PercentSizer, percents = 90)
      
      cerebro.optstrategy(SmaCross, fast = (5, 10), slow = (20, 25))
      cerebro.run()
      
      
      
      

      Does someone maybe know how to resolve this issue?

      Thanks,
      Amit

      posted in General Code/Help
      amit.kehat
      amit.kehat