Navigation

    Backtrader Community

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

    tewhaile

    @tewhaile

    1
    Reputation
    2
    Profile views
    2
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    tewhaile Unfollow Follow

    Best posts made by tewhaile

    • Orders not being executed on a 1 minute data.

      I have an intraday data for SPY for 11/2020. I'm using a simple test code with a GoldenCross strategy to buy when crossing up and sell when the faster crosses down. I tested the strategy with a daily data pulled using bt.feeds.YahooFinanceData. The only thing I did for is to replace the data to use my CSV using bt.feeds.GenericCSVData with parameters set as

      data = bt.feeds.GenericCSVData(
          dataname = 'SPY_1_M_01_11_2020-29_11_2020.csv', 
          fromdate = params['fromdate'], 
          todate = params['todate'],
          dtformat = ('%m/%d/%Y %H:%M:%S'),
          period = bt.TimeFrame.Minutes,
          compression = 1,
          datetime = 0,
          open = 1,
          high = 2,
          low = 3,
          close = 4,
          volume = 5,
          openinterest = -1,
          )
      

      the CSV looks like :

      timedate          open    high    low    close          volume
      11/2/20 9:30	330.187	330.188	329.947	 330.038	   4.79
      11/2/20 9:31	330.038	330.438	329.538	 329.677	   5.49
      

      The strategy is :

      import math
      import backtrader as bt
      from params import params
      
      class GoldenCross(bt.Strategy):
          def __init__(self):
              self.fast_sma = bt.indicators.MovingAverageSimple(self.data.close, period = params['fast'])
              self.slow_sma = bt.indicators.MovingAverageSimple(self.data.close, period = params['slow'])
      
              self.crossover = bt.indicators.CrossOver(self.fast_sma, self.slow_sma)
              self.order = None
      
          def next(self):
              amount_to_invest = params['order_percentage'] * self.broker.cash
              self.size = math.floor(amount_to_invest/self.data.close[0])
      
              if self.order:
                  return
      
              if self.position.size == 0:
                  if self.crossover > 0:
                      print('Buy\t{}\tshares of {} at\t{}'.format(self.size, params['ticker'], self.data.close[0]))
                      self.buy(size = self.size)
      
              if self.position.size > 0:
                  if self.crossover < 0:
                      print('Sell\t{}\tshares of {} at\t{}'.format(self.position.size, params['ticker'], self.data.close[0]))
                      self.close()
      

      And I run it from the main module as:

      import backtrader as bt
      from params import params
      from strategies.GoldenCross import GoldenCross
      
      cerebro = bt.Cerebro()
      
      cerebro.broker.set_cash(params['portfolio_size'])
      
      print('Start Portfolio Value: %.2f' % cerebro.broker.get_value())
      
      # data = bt.feeds.YahooFinanceData(
      #     dataname = params['ticker'], 
      #     fromdate = params['fromdate'], 
      #     todate = params['todate'],
      #     )
      
      data = bt.feeds.GenericCSVData(
          dataname = 'SPY_1_M_01_11_2020-29_11_2020.csv', 
          fromdate = params['fromdate'], 
          todate = params['todate'],
          dtformat = ('%m/%d/%Y %H:%M:%S'),
          period = bt.TimeFrame.Minutes,
          compression = 1,
          datetime = 0,
          open = 1,
          high = 2,
          low = 3,
          close = 4,
          volume = 5,
          openinterest = -1,
          )
      
      cerebro.adddata(data)
      cerebro.addsizer(bt.sizers.FixedSize, stake=500)
      
      cerebro.addstrategy(GoldenCross)
      
      cerebro.run()
      cerebro.plot()
      
      print('Final Portfolio Value: %.2f' % cerebro.broker.get_value())
      

      when I run it, i get the output which shows the printout of the logs from the strategy but i just doesn't actually buy or close the position.

      Output:

      user-> python3 run.py
      Start Portfolio Value: 100000.00
      Buy     54      shares of SPY at        363.858
      Buy     54      shares of SPY at        363.758
      Buy     54      shares of SPY at        363.978
      Buy     54      shares of SPY at        363.907
      Buy     54      shares of SPY at        363.867
      Buy     55      shares of SPY at        363.027
      Final Portfolio Value: 100000.00
      

      The code works just fine when using the

      data = bt.feeds.YahooFinanceData(
           dataname = params['ticker'], 
           fromdate = params['fromdate'], 
           todate = params['todate'],
           )
      

      and actually executes the buy and sell, just not with the minute data.

      posted in General Code/Help
      T
      tewhaile

    Latest posts made by tewhaile

    • Pivot Point Crossover does not show in plot.

      I'm trying to get a crossover signal for Pivot Points. I used the recomendation from the documentation to stop automatically plotting the non-resampled data based on the suggestion: "The indicator will try to automatically plo to the non-resampled data. To disable this behavior use the following during construction:

      _autoplot=False
      

      "

      but I cannot seem to get the crossover indicator to show on the graph. I tried enabling the possible parameters for the plotinfo of the crossover indicator as:

      self.pivotSignalP.plotinfo.plot = True
      self.pivotSignalP.plotinfo.subplot = True
      

      But it doesn't seem to work.

      My Data is an intraday 1 minute data and the pivot points are generated based on a resampled data with timeframe = bt.TimeFrame.Days

      My code is:

      import backtrader as bt
      from datetime import datetime as dt
      
      plotStart = dt(2020, 11, 11, 9, 30)
      plotEnd = dt(2020, 11, 11, 12, 0)
      dataTimeFrame = bt.TimeFrame.Minutes
      compression = 1
      
      class PivotPoint(bt.Strategy):
          params = dict(
              pivot = bt.indicators.PivotPoint,
              cross = bt.indicators.CrossOver,
              emovav = bt.indicators.ExponentialMovingAverage,
          )
      
          def __init__(self):
              self.pivots = self.p.pivot(self.data1)
              self.pivots.autoplot = False
              self.pivotSignalP = self.p.cross(self.data1.open, self.pivots.lines.p)
              self.pivotSignalP.plotinfo.plotname = "Pivot P Crossover"
      
              self.ema9 = self.p.emovav(self.data0, period = 9)
              self.ema21 = self.p.emovav(self.data0, period = 21)
              self.emaSignal = self.p.cross(self.ema9, self.ema21)
              self.emaSignal.plotinfo.plotname = "EMA Crossover"
        
          def next(self):
             if self.order:
                 return
             if not self.position:
                 if self.emaSignal > 0:
                     self.buy()
             else:
                 if self.emaSignal < 0:
                     self.close()
      
      cerebro = bt.Cerebro(stdstats = False)
      
      cerebro.addobserver(bt.observers.BuySell, barplot = True, bardist = 0.0001)
      cerebro.addobserver(bt.observers.Value)
      cerebro.addobserver(bt.observers.Trades)
      
      data = bt.feeds.GenericCSVData(
          dataname = 'SPY_11_2020_1M.txt',
          name = 'SPY',
          datetime = 0,
          dtformat = ('%m/%d/%Y %H:%M'),
          timeframe = dataTimeFrame,
          compression = compression,
          fromdate = dt(2020, 11, 10),
          todate = plotEnd,
          open = 1,
          high = 2,
          low = 3,
          close = 4,
          volume = 5,
          openinterest = -1,
      )
      cerebro.adddata(data)
      data1 = cerebro.resampledata(data, timeframe = bt.TimeFrame.Days)
      data1.plotinfo.plot = False
      
      cerebro.broker.setcash(100000.0)
      startValue = cerebro.broker.get_value()
      print('Start Portfolio Value: %.2f' % startValue)
      
      cerebro.addstrategy(PivotPoint)
      
      cerebro.run()
      cerebro.plot(style = 'candle', barup = 'green', bardown = 'red', start= plotStart, end= plotEnd, volume = True)
      
      endValue = cerebro.broker.get_value()
      pl = 100 * (endValue - startValue) / startValue
      print('\lFinal Portfolio Value: {}\t\t\t P\L: {}%'.format(round(endValue, 2), round(pl, 2)))
      
      
      posted in General Code/Help
      T
      tewhaile
    • Orders not being executed on a 1 minute data.

      I have an intraday data for SPY for 11/2020. I'm using a simple test code with a GoldenCross strategy to buy when crossing up and sell when the faster crosses down. I tested the strategy with a daily data pulled using bt.feeds.YahooFinanceData. The only thing I did for is to replace the data to use my CSV using bt.feeds.GenericCSVData with parameters set as

      data = bt.feeds.GenericCSVData(
          dataname = 'SPY_1_M_01_11_2020-29_11_2020.csv', 
          fromdate = params['fromdate'], 
          todate = params['todate'],
          dtformat = ('%m/%d/%Y %H:%M:%S'),
          period = bt.TimeFrame.Minutes,
          compression = 1,
          datetime = 0,
          open = 1,
          high = 2,
          low = 3,
          close = 4,
          volume = 5,
          openinterest = -1,
          )
      

      the CSV looks like :

      timedate          open    high    low    close          volume
      11/2/20 9:30	330.187	330.188	329.947	 330.038	   4.79
      11/2/20 9:31	330.038	330.438	329.538	 329.677	   5.49
      

      The strategy is :

      import math
      import backtrader as bt
      from params import params
      
      class GoldenCross(bt.Strategy):
          def __init__(self):
              self.fast_sma = bt.indicators.MovingAverageSimple(self.data.close, period = params['fast'])
              self.slow_sma = bt.indicators.MovingAverageSimple(self.data.close, period = params['slow'])
      
              self.crossover = bt.indicators.CrossOver(self.fast_sma, self.slow_sma)
              self.order = None
      
          def next(self):
              amount_to_invest = params['order_percentage'] * self.broker.cash
              self.size = math.floor(amount_to_invest/self.data.close[0])
      
              if self.order:
                  return
      
              if self.position.size == 0:
                  if self.crossover > 0:
                      print('Buy\t{}\tshares of {} at\t{}'.format(self.size, params['ticker'], self.data.close[0]))
                      self.buy(size = self.size)
      
              if self.position.size > 0:
                  if self.crossover < 0:
                      print('Sell\t{}\tshares of {} at\t{}'.format(self.position.size, params['ticker'], self.data.close[0]))
                      self.close()
      

      And I run it from the main module as:

      import backtrader as bt
      from params import params
      from strategies.GoldenCross import GoldenCross
      
      cerebro = bt.Cerebro()
      
      cerebro.broker.set_cash(params['portfolio_size'])
      
      print('Start Portfolio Value: %.2f' % cerebro.broker.get_value())
      
      # data = bt.feeds.YahooFinanceData(
      #     dataname = params['ticker'], 
      #     fromdate = params['fromdate'], 
      #     todate = params['todate'],
      #     )
      
      data = bt.feeds.GenericCSVData(
          dataname = 'SPY_1_M_01_11_2020-29_11_2020.csv', 
          fromdate = params['fromdate'], 
          todate = params['todate'],
          dtformat = ('%m/%d/%Y %H:%M:%S'),
          period = bt.TimeFrame.Minutes,
          compression = 1,
          datetime = 0,
          open = 1,
          high = 2,
          low = 3,
          close = 4,
          volume = 5,
          openinterest = -1,
          )
      
      cerebro.adddata(data)
      cerebro.addsizer(bt.sizers.FixedSize, stake=500)
      
      cerebro.addstrategy(GoldenCross)
      
      cerebro.run()
      cerebro.plot()
      
      print('Final Portfolio Value: %.2f' % cerebro.broker.get_value())
      

      when I run it, i get the output which shows the printout of the logs from the strategy but i just doesn't actually buy or close the position.

      Output:

      user-> python3 run.py
      Start Portfolio Value: 100000.00
      Buy     54      shares of SPY at        363.858
      Buy     54      shares of SPY at        363.758
      Buy     54      shares of SPY at        363.978
      Buy     54      shares of SPY at        363.907
      Buy     54      shares of SPY at        363.867
      Buy     55      shares of SPY at        363.027
      Final Portfolio Value: 100000.00
      

      The code works just fine when using the

      data = bt.feeds.YahooFinanceData(
           dataname = params['ticker'], 
           fromdate = params['fromdate'], 
           todate = params['todate'],
           )
      

      and actually executes the buy and sell, just not with the minute data.

      posted in General Code/Help
      T
      tewhaile