For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

how to test multi data



  • dear all:
    I am a fresher.
    I want to test multi stock use same strategy.
    how to write the test function?
    the following is framework... anybody can share some code ?thanks.

    main:#add multi data
    cerebro.adddata(data1)
    cerebro.adddata(data2)
    cerebro.adddata(data3)

    def init(self):
    self.sma = bt.indicators.SimpleMovingAverage( self.datas, 30)
    def next(self):
    if self.dataclose > self.sma:
    self.buy()



  • Note: Please use backticks ``` to post your code, otherwise its hard to read.

    Here is the example of how to use BT with multi data.

    https://www.backtrader.com/blog/posts/2017-04-09-multi-example/multi-example/



  • code_text
    if __name__ == '__main__':
        cerebro.adddata(data1)
        cerebro.adddata(data2)
        cerebro.adddata(data3)
    
    def init(self):
        self.sma = bt.indicators.SimpleMovingAverage( self.datas, 30)
    def next(self):
        if self.dataclose > self.sma:
            self.buy()
    


  • Let's assume for the moment you have created three datas and successfully added them in to cerebro, and also assume that the init and next are properly in a strategy class, which was properly added to cerebro....

    You are going to have trouble with the self. sma.

    self.sma = bt.indicators.SimpleMovingAverage( self.datas, 30)

    self.datas is a list of the datas you have added, so it will not know what to calculate the sma on. Ideally you should create a dictionary of the sma's calculated for each data.

    self.sma_dict = dict()
    for d in self.datas:
        self.sma_dict[d] = bt.indicators.SimpleMovingAverage(d, period=30)
    

    Make sure you add in the 'period=' keyword.

    Now you have a dictionary that you can call in next as follows:

    def next(self):  
        for d in self.datas:
            if d.close[0] > self.sma_dict[d][0]:
                self.buy(d)
    

    Something like that.



  • @run-out thanks.


Log in to reply
 

});