Backtrader Community

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

    Check if ticker tradeable before all datafeeds are available

    Indicators/Strategies/Analyzers
    strategy prenext datafeed
    1
    2
    224
    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.
    • M
      mike_q last edited by

      Hi, community,

      I have a Buy&Hold strategy which keeps the same portfolio weight during the whole strategy life. However, I want to start a strategy before all data feeds available. For example:
      Allocation SPY - 50% and TLT -50%

      • SPY is available on 01-01-1990
      • TLT is available after 2004
        So in this situation, before 2004, I want to adjust allocation to SPY - 100% and once TLT is available, then use target allocation: SPY - 50% and TLT -50%

      Below is a strategy I refer to. Do you know how to check if ticker is available for a given date. I think the best option is to implement such check during prenext call

      import strategies
      import logging
      import backtrader as bt
      from datetime import datetime
      import sys
      
      logging.basicConfig(level=logging.INFO,
                          format='%(asctime)s - %(name)s/%(funcName)s - %(levelname)s - %(message)s',
                          datefmt='%Y-%b-%d %H:%M:%S',
                          stream=sys.stdout)
      logger = logging.getLogger(__name__)
      
      
      class BuyHold(bt.Strategy):
          params = dict(allocation=None, rebalance_frequency=None)
      
          def __init__(self):
              self.allocation = self.params._get('allocation')
              logger.info(f'Set portfolio allocation to {self.allocation}')
              print('Date during init', self.data.datetime.datetime().date())
              for d in self.datas:
                  print(f"stock: {d._name}, length: {len(d.array)}")
      
          def prenext(self):
              self.tradable_allocation()
              self.next()
      
          def tradable_allocation(self):
              tradable_alloc = dict()
              # for ticker in self.allocation:
              # if ticker is NOT tradable, then allocate asset weight to other ticker
      
              self.allocation = tradable_alloc
      
          def start(self):
              self.val_start = self.broker.get_cash()
              logger.info(f'Starting Portfolio Value: {self.broker.getvalue():.2f}')
      
          def next(self):
              for ticker in self.allocation:
                  logger.debug(f'Execute Rebalance for {ticker} to {self.allocation[ticker]} allocation.')
                  self.order_target_percent(ticker, target=self.allocation[ticker])
              self.allocation = self.params._get('allocation')  # Reset allocation on each step
      
          def stop(self):
              logger.info(f'Final Portfolio Value: {self.broker.getvalue():.2f}')
      
      
      START_CASH = 10000.0
      START_DATE = datetime(year=1990, month=12, day=2)
      END_DATE = datetime(year=2005, month=12, day=31)
      weights = dict(SPY=0.5, TLT=0.5)
      
      if __name__ == '__main__':
          cerebro = bt.Cerebro()
          for ticker in weights:
              data = bt.feeds.YahooFinanceData(dataname=ticker,
                                               fromdate=START_DATE,
                                               todate=END_DATE)
              cerebro.adddata(data)
      
          cerebro.broker.setcash(START_CASH)
      
          # Run over everything
          cerebro.addstrategy(BuyHold, allocation=weights)
          results = cerebro.run()
      
      
      1 Reply Last reply Reply Quote 0
      • M
        mike_q last edited by

        I found a way to check if data is available for a given date.

        data = self.getdatabyname(ticker)
        current_date = self.data.datetime.datetime().date()
        if date == bt.num2date(data.datetime[0]).date():
          print(f'data is available for {ticker}')
        
        1 Reply Last reply Reply Quote 1
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors