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



  • 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

Log in to reply
 

});