Custom Indicator Development in Python with backtrader

import backtrader as btclass DummyDifferenceDivider(bt.Indicator):
lines = ('diffdiv',) # output line (array)
params = (
('period', 1), # distance to previous data point
('divfactor', 2.0), # factor to use for the division
)
def __init__(self):
diff = self.data(0) - self.data(-self.p.period)
diffdiv = diff / self.p.divfactor
self.lines.diffdiv = diffdiv
abs(k - k(-1)) / 2
import backtrader as btclass MyStochastic1(bt.Indicator):
lines = ('k', 'd', 'mystoc',) # declare the output lines
params = (
('k_period', 14), # lookback period for highest/lowest
('d_period', 3), # smoothing period for d with the SMA
)

def __init__(self):
# declare the highest/lowest
highest = bt.ind.Highest(self.data, period=self.p.k_period)
lowest = bt.ind.Lowest(self.data, period=self.p.k_period)
# calculate and assign lines
self.lines.k = k = (self.data - lowest) / (highest - lowest)
self.lines.d = d = bt.ind.SMA(k, period=self.p.d_period)
self.lines.mystoc = abs(k - k(-1)) / 2.0
import backtrader as btclass MyStochastic2(bt.Indicator):
lines = ('k', 'd', 'mystoc',)
# manually counted period
# 14 for the fast moving k
# 3 for the slow moving d
# No extra for the previous k (-1) is needed because
# already buffers more than the 1 period lookback
# If we were doing d - d(-1), there is nothing making
# sure k(-1) is being buffered and an extra 1 would be needed
params = (
('k_period', 14), # lookback period for highest/lowest
('d_period', 3), # smoothing period for d with the SMA
)
def __init__(self):
self.addminperiod(self.p.k_period + self.p.d_period)

def next(self):
# Get enough data points to calculate k and do it
d = self.data.get(size=self.p.k_period)
hi = max(d)
lo = min(d)
self.lines.k[0] = k0 = (self.data[0] - lo) / (hi - lo)
# Get enough ks to calculate the SMA of k. Assign to d
last_ks = self.l.k.get(size=self.p.d_period)
self.lines.d[0] = sum(last_ks) / self.p.d_period
# Now calculate mystoc
self.lines.mystoc[0] = abs(k0 - self.l.k[-1]) / 2.0
The two custom Stochastic Indicators shown

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store