Python Backtrader: Mark Doji CandleSticks - Example Indicator
Below is the script in python using the backtrader package for marking Doji CandleSticks on the chart. Ideally, a doji is a candlestick pattern where the open price is exactly the same as the close price. However, since such ideal conditions seldom exist, in the script, I have used a tolerance of 0.05% between the open and close price for identifying and marking doji.
import backtrader as bt # Create a Stratey class DojiTest(bt.Indicator):
alias = ('DD',) lines = ('doji',) params = ( ('tolerence', 0.05), # tolerence )
plotinfo = dict( subplot=False, plotlinelabels=True, ) plotlines = dict( doji=dict(marker='^', markersize=8.0, color='blue', fillstyle='full', ls='', ), )
def next(self): # red doji if ((self.datas[0].close[0] * (1 + (self.p.tolerence/100))) > self.datas[0].open[0]) and (self.datas[0].close[0]<self.datas[0].open[0]): self.lines.doji[0]= self.datas[0].high[0]
# green doji if ((self.datas[0].open[0] * (1 + (self.p.tolerence/100))) > self.datas[0].close[0]) and (self.datas[0].close[0]>self.datas[0].open[0]): self.lines.doji[0]= self.datas[0].high[0]
class MyStrategy(bt.Strategy): def __init__(self): # self.BB = bt.ind.BBands(self.data,period=20,devfactor=1.5) self.doji = DojiTest(self.data)
if __name__ == '__main__': cerebro = bt.Cerebro(stdstats=False) data = bt.feeds.YahooFinanceCSVData(dataname='AAPL.csv') cerebro.adddata(data) cerebro.addstrategy(MyStrategy) cerebro.run() cerebro.plot(style='candlestick') |
The script is using Cerebro engine of backtrader for plotting of custom indicators created in backtrader. A new indicator class named DojiTest has been written and implemented.