Improving Backtrader Random Python Internet Study Notes

Daniel Rodriguez
Apr 22, 2018 · 3 min read
def __init__(self):
...
self.ma1 = bt.indicators.SMA(self.datas[0],
period=self.p.period
)
self.ma2 = bt.indicators.SMA(self.datas[1],
period=self.p.period
)
...
# Not yet ... we MIGHT BUY if ...
if (self.ma1[0]-self.ma1[-1])/self.ma1[-1]>(self.ma2[0]-self.ma2[-1])/self.ma2[-1]:
...
...
# Already in the market ... we might sell
if (self.ma1[0]-self.ma1[-1])/self.ma1[-1]<=(self.ma2[0]-self.ma2[-1])/self.ma2[-1]:
...
def __init__(self):
...
# Let's create the moving averages as before
ma1 = bt.ind.SMA(self.data0, period=self.p.period)
ma2 = bt.ind.SMA(self.data1, period=self.p.period)
# Use line delay notation (-x) to get a ref to the -1 point
ma1_pct = ma1 / ma1(-1) - 1.0 # ma1 percentage part
ma2_pct = ma2 / ma2(-1) - 1.0 # ma2 percentage part
self.buy_sig = ma1_pct > ma2_pct # buy signal
self.sell_sig = ma1_pct <= ma2_pct # sell signal
def next(self):
...
# Not yet ... we MIGHT BUY if ...
if self.buy_sig:
...
...
# Already in the market ... we might sell
if self.sell_sig:
...
def __init__(self):
...
# Let's create the moving averages as before
ma1 = bt.ind.SMA(self.data0, period=self.p.period)
ma2 = bt.ind.SMA(self.data1, period=self.p.period)
ma1_pct = bt.ind.PctChange(ma1, period=1) # ma1 percentage part
ma2_pct = bt.ind.PctChange(ma2, period=1) # ma2 percentage part
self.buy_sig = ma1_pct > ma2_pct # buy signal
self.sell_sig = ma1_pct <= ma2_pct # sell signal

Daniel Rodriguez

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade