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/

    Cant sort data by indicator value. Sorted function is not working as expected

    General Code/Help
    1
    1
    83
    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.
    • Eduardo De La Garza
      Eduardo De La Garza last edited by

      Hello. I have the following strategy but I cant manage to sort the data I have by a certain indicator value. It seems that the list always stays the same. Im not sure what I'm doing wrong. The pertinent code is in the rebalance_portfolio function. I also tried sorting the list in place with list.sort(lambda x: ...)

      class SP500Rotation(bt.Strategy):
          params = dict(
              ...
          )
      
      def __init__(self):
          self.inds = collections.defaultdict(dict)
          self.stocks = self.datas[1:]
          self.current_holdings = []
      
          self.idx_mav = bt.ind.SMA(self.data0, period=self.p.idx_period)
          for d in self.stocks:
              self.inds[d]['roc'] = bt.ind.RateOfChange(period=self.p.roc_period)
              self.inds[d]['rsi'] = bt.ind.RSI_SMA(
                  safediv=True, period=self.p.rsi_period)
      
      def notify_timer(self, timer, when, *args, **kwargs):
          self.rebalance_portfolio()
      
      def rebalance_portfolio(self):
          inds = self.inds
          rankings = self.stocks
          rankings = sorted(rankings, key=lambda d: inds[d]["roc"][0], reverse=True) #This line
          rankings = rankings[:self.p.num_stocks]
      
          for holding in self.current_holdings:
              if holding not in rankings:
                  self.close(holding)
      
          for d in rankings:
              if not self.getposition(d).size:
                  self.order_target_percent(d, 1/self.p.num_stocks)
      
          self.current_holdings = rankings
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors