For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Loop Multiple Conditions in Custom Indicator
-
QUESTION
How do I add multiple conditions in the for loop?
PROBLEM
I want to check if both open and close are above bollinger-mid. I know the below code is incorrect but hopefully it shows what I am trying to achieve.
INDICATOR
class OpenAndCloseAboveBBmid(bt.Indicator): lines = ('consecutive',) params = ( ('period', 15), # how many to consider ('ago', 0), # offset to start in the past ('bbperiod', 20), # offset to start in the past ('devfactor', 2), # offset to start in the past ) def __init__(self): self.bollband = bt.indicators.BollingerBands(self.data, period=self.p.bbperiod, devfactor=self.p.devfactor, plot=False) ### I KNOW THIS NEXT LINE WON'T WORK BUT IT SHOWS WHAT I AM TRYING TO ACHIEVE incs = [self.data.open(-i) > self.bollband.lines.mid(-i) and self.data.close(-i) > self.bollband.lines.mid(-i) for i in range(self.p.ago, self.p.ago + self.p.period)] self.lines.consecutive = bt.All(*incs)
-
bt.If
,bt.And
,bt.Or
-
@ab_trader Thanks for the info.
Working indicator with two conditions (open and close > bb.mid).
import backtrader as bt import backtrader.indicators as btind class AboveBBmid(bt.Indicator): lines = ('open', 'close') params = ( ('period', 15), # how many to consider ('ago', 0), # offset to start in the past ('bbperiod', 20), # offset to start in the past ('devfactor', 2), # offset to start in the past ) def __init__(self): self.bollband = bt.indicators.BollingerBands(self.data, period=self.p.bbperiod, devfactor=self.p.devfactor, plot=False) bar_open = [self.data.open(-i) > self.bollband.lines.mid(-i) for i in range(self.p.ago, self.p.ago + self.p.period)] self.lines.open = bt.All(*bar_open) bar_close = [self.data.close(-i) > self.bollband.lines.mid(-i) for i in range(self.p.ago, self.p.ago + self.p.period)] self.lines.close = bt.All(*bar_close) self.combined = bt.And(self.lines.open, self.lines.close)