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/

    Days to Weeks resampling

    Indicators/Strategies/Analyzers
    1
    3
    303
    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.
    • Matheus Pires
      Matheus Pires last edited by

      Hi guys!

      I've been struggling to solve a problem involving resampling from daily to weekly data. My issue is that I need to generate my trading signals for an asset using the close price of a given week, and this signal should be available right after the market closes so that I could execute this order on the following week open price.

      EXAMPLE: Signal to buy 50 AAPL shares triggered on friday's close, and order executed on monday's opening.

      However, the way I'm implementing "resampledata" makes the weekly close price of the asset only available on the first day of the following week.

      EXAMPLE: Signal to buy 50 AAPL shares should be issued on friday's close, but is being triggered only on monday's close, to be executed on tuesday's opening.

      I generated a daily log of the week's closing price, and as you can check out below, the transition from one close price to the following one is being done from friday to monday, instead of thursday to friday.

      Starting Portfolio Value: 100000.00
      2006-01-09, Close, 3666.99
      2006-01-10, Close, 3666.99
      2006-01-11, Close, 3666.99
      2006-01-12, Close, 3666.99
      2006-01-13, Close, 3666.99  <--- Friday
      2006-01-16, Close, 3629.25  <--- Monday
      2006-01-17, Close, 3629.25
      2006-01-18, Close, 3629.25
      

      If you guys wanna check the script I used to generate the logs, check out below:

      # Create a Stratey
      class TestStrategy(bt.Strategy):
      
          def log(self, txt, dt=None):
              ''' Logging function fot this strategy'''
              dt = dt or self.datas[0].datetime.date(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
      
      
      
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
      
              if self.dataclose[0] < self.dataclose[-1]:
                  # current close less than previous close
      
                  if self.dataclose[-1] < self.dataclose[-2]:
                      # previous close less than the previous close
      
                      # BUY, BUY, BUY!!! (with all possible default parameters)
                      self.log('BUY CREATE, %.2f' % self.dataclose[0])
                      self.buy()
      
      # Create a cerebro entity
      cerebro = bt.Cerebro(stdstats = False)
      
      # Add a strategy
      cerebro.addstrategy(TestStrategy)
      
      # Datas are in a subfolder of the samples.
      
      datapath = 'datas/2006-day-001.txt'
      
      # Create a Data Feed
      data = btfeeds.BacktraderCSVData(dataname=datapath, timeframe = bt.TimeFrame.Days)
      
      # Add the Data Feed to Cerebro
      cerebro.adddata(data)
      cerebro.resampledata(data, timeframe = bt.TimeFrame.Weeks, compression = 1)
      
      # Set our desired cash start
      cerebro.broker.setcash(100000.0)
      
      # Print out the starting conditions
      print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Run over everything
      strats = cerebro.run(runonce = False)
      
      # Print out the final result
      print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Plot the result
      cerebro.plot(style = 'bar', volume = False)
      
      strat0 = strats[0]
      

      Thanks in advance!!

      1 Reply Last reply Reply Quote 0
      • Matheus Pires
        Matheus Pires last edited by

        
        I've made a mistake while copying and paste the code, the first lines of the "next" function should be:
        
            def next(self):
                # Simply log the closing price of the series from the reference
                self.log('Close, %.2f' % self.datas[1].close[0])
        1 Reply Last reply Reply Quote 0
        • Matheus Pires
          Matheus Pires last edited by

          Problem solved:

          The issue was that I haven't assigned a calendar to cerebro with a corresponding session start/end, so it assumed the session lasted the whole 24h (I guess).

          Anyways I just needed to add an instance of MyCalendar to cerebro:

          class MyCalendar(bt.TradingCalendar):
              params = {
                  'open': time(9, 0),
                  'close': time(18, 0),
              }
          
          1 Reply Last reply Reply Quote 2
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors