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

problems when ploting indicator

  • I import the indicator from outside backtrader. The indicator varies between 0 and real number. I do not want to show those 0s when ploting my indicator. The following picture shows what I get. Those sudden drops are al zeros. pretty ugly.
    I thought one way.

    bt.If(!=0, values, )

    But it seems there must be a real number for the second parameter in


    Hope somebody can help me. many thanks.
    Here is my full code.

    class LongShort(bt.Indicator):
        lines = ('my_signal',)
        plotlines = dict(
            my_signal=dict(_name='my_signal', color='blue', ls='-', _skipnan=True),
        def __init__(self):
            values=btind.SMA(, period=1)
            self.lines.my_signal=bt.If(!=0, values,values)
    class MyStrategy(bt.Strategy):
        def __init__(self):
    cerebro = bt.Cerebro(stdstats=False)
    data =CustomDataLoader(dataname=df_gold)
    # Plot the result


  • You could consider importing two indicators. One with the zeros you use for calculations. The other you remove the zeros and foward fill to that you will have a smooth line. You could use the second for plotting?

  • @da-zhang said in problems when ploting indicator:

    Try None:

    bt.If(!=0, values, None)

  • @ab_trader said in problems when ploting indicator:


    It cannot work. Can you find other ways?

      File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\", line 190, in once
        dst[i] = srca[i] if cond[i] else srcb[i]
    TypeError: must be real number, not NoneType

  • @run-out
    How to remove the zeros in the init part?

  • administrators

    The problem here is the definition:

    @da-zhang said in problems when ploting indicator:

    The indicator varies between 0 and real number

    This would seem to indicate that the indicator travels (like a stochastic, for example), between 0.0 and a given (may be open) upper limit. But IT IS NOT so. The real definition is:

    • It is a binary indicator with either 0.0 or a value which is not related in any way to a possible previous 0.0, but actually to the previous non-zero values.

    That indicator needs rework to either remove the zeros or use them in a proper way.

Log in to reply