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

I want to apply multiple filters to a stock universe of 193 stocks



  • I have already added 193 stocks using cerebro.adddata.

    class OandaCSVData(bt.feeds.GenericCSVData):
    params = (
    # ('nullvalue', float('NaN')),
    ('dtformat', '%Y-%m-%d %H:%M:%S'),
    ('datetime', -1),
    ('Open', 1),
    ('High', 2),
    ('Low', 3),
    ('Close', 4),
    ('Volume', 5),
    )

    for i in tickers:
    datalist.append(('/home/het/Desktop/Stocks1/'+ i + '.csv',i))

    #Loop through the list adding to cerebro.
    for i in range(len(datalist)):
    data = OandaCSVData(dataname=datalist[i][0])
    cerebro.adddata(data, name=datalist[i][1])

    Now I want to apply filters, these filters should be applied every day to all 193 stocks to generate a trade sheet before the trading day

    On the trading day, I want to apply two filters using Volume and High Data. The stocks which pass these filters will be sold (it's a shorting strategy) and the same stocks would be bought at the end of the day.

    Can anyone help me, how do I apply these filters?



  • I guess by filters you mean indicators and not data filters. This is an example having a list of indicators (in this case SimpleMovingAverage applied on close), one per data feed.

    class TestStrategy(bt.Strategy):
    
        params = (
            ('maperiod', 15),
        )
    
        def __init__(self):
            self.smas = []
            for d in self.datas:
                self.smas.append(bt.indicators.SimpleMovingAverage(d.lines.close, period=self.params.maperiod))
    


  • @momentum Another error I faced was when I am feeding the data using the same code as above, it is feeding nan values.

    Values of all (Open High Low Close Volume Date) lines are coming out to be nan.

    Here is how my all 193 CSV files look:

    Open	High	Low	Close	Volume	Date
    

    0 46.13 46.88 45.94 46.5 232344 2006-09-20 00:00:00
    1 47.55 48.38 46.93 47.68 645560 2006-09-21 00:00:00
    2 47.44 48 46.43 46.63 195088 2006-09-22 00:00:00
    3 46.54 47.25 46.31 46.63 435563 2006-09-25 00:00:00
    4 46.8 47.25 46.5 47.1 332472 2006-09-26 00:00:00
    5 46.5 48.38 46.5 47.72 673968 2006-09-27 00:00:00
    6 47.85 48.38 47.44 48.07 347461 2006-09-28 00:00:00
    7 48.38 50.49 47.63 50.49 1912768 2006-09-29 00:00:00
    8 52.27 53.02 49.69 50.12 1212384 2006-10-03 00:00:00
    9 50.36 52.63 49.5 52.41 1972424 2006-10-04 00:00:00
    10 53.63 55.03 52.69 55.03 1221296 2006-10-05 00:00:00
    11 57.15 57.68 52.95 53.31 2171560 2006-10-06 00:00:00
    12 53.63 55.78 50.85 55.24 1283579 2006-10-09 00:00:00
    13 55.88 56.93 51.51 52.82 926056 2006-10-10 00:00:00
    14 54 54.75 52.16 52.65 1091808 2006-10-11 00:00:00
    15 53.06 54.17 52.59 53.68 512992 2006-10-12 00:00:00
    16 54.19 54.94 52.88 53.21 519664 2006-10-13 00:00:00
    17 53.81 54.38 52.52 52.69 497160 2006-10-16 00:00:00
    18 52.88 53.21 51.45 51.69 347733 2006-10-17 00:00:00
    19 51.68 52.13 50.68 51.34 230928 2006-10-18 00:00:00
    20 51.75 54.38 51 52.24 820824 2006-10-19 00:00:00
    21 52.48 54.38 52.01 52.65 487909 2006-10-20 00:00:00



  • Haven't tested it, but I think your csv file looks more like the following.

    params = (
    # ('nullvalue', float('NaN')),
    ('dtformat', '%Y-%m-%d %H:%M:%S'),
    ('datetime', 5),
    ('Open', 0),
    ('High', 1),
    ('Low', 2),
    ('Close', 3),
    ('Volume', 4),
    )
    

  • administrators

    @het-dagli said in I want to apply multiple filters to a stock universe of 193 stocks:

    Can anyone help me, how do I apply these filters?

    Even if @momentum has already been providing some help, I would suggest that you start by helping yourself. If you cannot see this at the TOP of each page in the community, you are likely going to miss many other details like the ordering of your data.

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

    This will help you in communicating with others and the others in understanding what you post.



  • @momentum I tried with your ordering of Indices, but still, the values are nan.



  • @backtrader Okay, I got it now. Sorry for not acknowledging it before.
    Can you help me why I am getting nan values while importing the data?



  • @backtrader Here is my full code

    '''
    import backtrader as bt
    from datetime import datetime

    class mainStrategy(bt.Strategy):

    def __init__(self):
       for x in self.data.close:
           print(x)
    
    
    
    
    def next(self):
        pass
    

    class customCSV(bt.feeds.GenericCSVData):
    params = (
    #('nullvalue', 0),
    ('Open', 1),
    ('High', 2),
    ('Low', 3),
    ('Close', 4),
    ('Volume', 5),
    ('dtformat', '%Y-%m-%d %H:%M:%S'),
    ('datetime', 6),
    #('timeframe',bt.TimeFrame.Days)
    )

    #Variable for our starting cash
    startcash = 10000

    #Create an instance of cerebro
    cerebro = bt.Cerebro()

    #Add our strategy
    cerebro.addstrategy(mainStrategy)

    data = customCSV(dataname="/home/het/Desktop/Stocks1/DATA.csv")
    cerebro.adddata(data)

    Set our desired cash start

    cerebro.broker.setcash(startcash)

    Run over everything

    cerebro.run()

    #Get final portfolio Value
    portvalue = cerebro.broker.getvalue()
    pnl = portvalue - startcash

    #Print out the final result
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))

    '''



  • @het-dagli said in I want to apply multiple filters to a stock universe of 193 stocks:

    @backtrader Here is my full code

    import backtrader as bt
    from datetime import datetime
    
    
    class mainStrategy(bt.Strategy):
    
    
        def __init__(self):
           for x in self.data.close:
               print(x)
    
    
    
    
        def next(self):
            pass
    
    class customCSV(bt.feeds.GenericCSVData):
            params = (
            #('nullvalue', 0),
            ('Open', 1),
            ('High', 2),
            ('Low', 3),
            ('Close', 4),
            ('Volume', 5),
            ('dtformat', '%Y-%m-%d %H:%M:%S'),
            ('datetime', 6),
            #('timeframe',bt.TimeFrame.Days)
        )
    
    
    #Variable for our starting cash
    startcash = 10000
    
    #Create an instance of cerebro
    cerebro = bt.Cerebro()
    
    #Add our strategy
    cerebro.addstrategy(mainStrategy)
    
    
    
    
    data = customCSV(dataname="/home/het/Desktop/Stocks1/DATA.csv")
    cerebro.adddata(data)
    
    # Set our desired cash start
    cerebro.broker.setcash(startcash)
    
    # Run over everything
    cerebro.run()
    
    #Get final portfolio Value
    portvalue = cerebro.broker.getvalue()
    pnl = portvalue - startcash
    
    
    #Print out the final result
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))
    
    


  • @momentum

    Hi, how do you access the smas in your self.smas list with reference to data name?
    Like how to you know which data was used to calculate smas[0] in later codes?

    The backtrader.indicators.sma.MovingAverageSimple object doesnt have a _name.



  • @yi-fang use dictionary instead of the list:

    self.smas = {}
    for d in self.datas:
        self.sma['d._name'] = bt.indicators.SimpleMovingAverage(d.close, period=self.p.maperiod)
    


  • @ab_trader

    Thank you for your reply, originally I thought indicator carries the information of which data it was calculated upon. Even if it was another indicator, the original data info should be pass by. Guess I was wrong


  • administrators

    @yi-fang said in I want to apply multiple filters to a stock universe of 193 stocks:

    Even if it was another indicator, the original data info should be pass by.

    An indicator can have many inputs and these can belong to multiple data feeds, indicators and ...


 

});