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

How to generate CrossAbove or CrossBelow signal

  • I am trying to test a logic/ strategy where
    if price of instrument 1 crosses above a threshold (fixed value 1)
    then enter long position in instrument 2
    if price of instrument crosses below a threshold (fixed value 2)
    then cover long position in instrument 2
    I want to know how to write Cross_Above or Cross_Below signal.
    In there are two classes on upcross and belowcross, but not sure how to use them. Any help is appreciated. Thanks

  • administrators

    An early example which uses CrossOver is here:

    Replacing it with CrossUp will only generate positive signals and replacing it with CrossDown will generate only negative signals.

    The main page contains a SignalStrategy based approach which goes only long. In this case CrossOver is also used to use the positive signals as entry signals and the negative as exit signals.

        from datetime import datetime
        import backtrader as bt
        class SmaCross(bt.SignalStrategy):
            params = (('pfast', 10), ('pslow, 30'))
            def __init__(self):
                sma1, sma2 = bt.ind.SMA(period=self.p.pfast), bt.ind.SMA(period=self.p.pslow)
                self.signal_add(bt.SIGNAL_LONG, bt.ind.CrossOver(sma1, sma2))
        cerebro = bt.Cerebro()
        data = bt.feeds.YahooFinanceData(dataname='YHOO', fromdate=datetime(2011, 1, 1),
                                         todate=datetime(2012, 12, 31))

    There is a full sigsmacross extending that sample in the sources.

    You could add to signals rather than 1:

    • For LONG: CrossUp
    • For exiting the LONG position: CrossDown

    The kselrsi sample contains a usage of both CrossUp and CrossDown

    In any case the best to see how they operate would be to simply add them to the code and see the signals plotted.

  • Thanks for the reply, I will test and post results soon

Log in to reply