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

Strategy with Signals

  • I read through "strategy with signals" section of the documentation. However, I don't really understand how to code using those signals.

    Let say I would like to have a strategy that :

    1. goes into a long position if today's closing price is lower than yesterday's
    2. goes into a short position if today's closing price is higher than yesterday's

    How do I use the signal? Do I still have to use self.sell and Thankss :)

  • administrators

    You are referring to: Docs - Strategy with Signals

    No. You don't have to use sell or buy. The signals tell the system to execute operations.

    A Signal is basically an Indicator. It simply has to deliver values which are 0, >= 1 or <= -1 depending on the intended usage (a single Signal delivering the three values can be used for long/short strategies). A signal of that type is for example a moving average cross over

    class MySignal(bt.Signal):
        params = dict(p1=10, p2=30)
        def __init__(self):
            self.lines.signal = bt.ind.CrossOver(bt.ind.SMA(period=self.p.p1), bt.ind.SMA(period=self.p.p2))

    And you only have to insert the signal in the system with:

    cerebro.addsignal(bt.signal.SIGNAL_LONGSHORT, MySignal

    If you want finer control you can override bt.SignalStrategy as is actually done in the example in the HomePage

        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))

    You can add multiple signals for each possible condition (LONG, SHORT, EXITLONG) ... it's all about experimenting.

  • Thanks @backtrader

Log in to reply