I kindly ask for some help to convert this indicator form pine-script to python backtrader lib.
Unfortunately I cam on my limit of my skills. Please have a look on the upper- and lower-band part which makes trouble.
Full Pine-Script Code:
//@version=5
//
// Copyright (C) 2017 CC BY, whentotrade / Lars von Thienen
// Source:
// Book: Decoding The Hidden Market Rhythm - Part 1: Dynamic Cycles (2017)
// Chapter 4: "Fine-tuning technical indicators for more details on the cRSI Indicator
//
// Usage:
// You need to derive the dominant cycle as input parameter for the cycle length as described in chapter 4.
//
// License:
// This work is licensed under a Creative Commons Attribution 4.0 International License.
// You are free to share the material in any medium or format and remix, transform, and build upon the material for any purpose,
// even commercially. You must give appropriate credit to the authors book and website, provide a link to the license, and indicate
// if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
//
indicator(title='RSI cyclic smoothed', shorttitle='cRSI')
timeframe_request(_symbol, _res, _src) => request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0])
domcycle = input.int(50, minval=10, title='Dominant Cycle Length')
smoothed = input.int(1, minval=1, title="Smoothed")
enable_long_trigger = input.bool(false, 'Long threshold', group = 'Signals', inline = "long")
long_trigger = input.int(68, '', minval=1, maxval=99, group = 'Signals', inline = "long")
enable_short_trigger = input.bool(false, 'Short threshold', group = 'Signals', inline = "short")
short_trigger = input.int(42, '', minval=1, maxval=99, group = 'Signals', inline = "short")
crsi_tf = input.timeframe("", "cRSi timeframe")
crsi_source = input.source(close, 'source')
crsi_source_ = timeframe_request('', crsi_tf, crsi_source)
crsi_ = 0.0
cyclelen = domcycle / 2
vibration = 10
leveling = 10.0
cyclicmemory = domcycle * 2
h1 = hline(30, color=color.silver, linestyle=hline.style_dashed)
h2 = hline(70, color=color.silver, linestyle=hline.style_dashed)
torque = 2.0 / (vibration + 1)
phasingLag = (vibration - 1) / 2.0
up = ta.ema(math.max(ta.change(crsi_source_), 0), cyclelen)
down = ta.ema(-math.min(ta.change(crsi_source_), 0), cyclelen)
rsi = ta.rsi(crsi_source_, cyclelen)
crsi_ := ta.ema( torque * (2 * rsi - rsi[phasingLag]) + (1 - torque) * nz(crsi_[1]) , smoothed )
crsi = request.security("", crsi_tf, crsi_) //Not necesarry for python
lmax = -999999.0
lmin = 999999.0
// Does it make sense to check if "999999.0 > lmax" and same with lmin?
for i = 0 to cyclicmemory - 1 by 1
if nz(crsi[i], -999999.0) > lmax
lmax := nz(crsi[i])
lmax
else
if nz(crsi[i], 999999.0) < lmin
lmin := nz(crsi[i])
lmin
//------------------------------------------------------------------
mstep = (lmax - lmin) / 100
aperc = leveling / 100
db = 0.0
for steps = 0 to 100 by 1
testvalue = lmin + mstep * steps
above = 0
below = 0
for m = 0 to cyclicmemory - 1 by 1
below += (crsi[m] < testvalue ? 1 : 0)
below
//Strange how you can divide in case below = 0?
ratio = below / cyclicmemory
if ratio >= aperc
db := testvalue
break
else
continue
ub = 0.0
for steps = 0 to 100 by 1
testvalue = lmax - mstep * steps
above = 0
for m = 0 to cyclicmemory - 1 by 1
above += (crsi[m] >= testvalue ? 1 : 0)
above
ratio = above / cyclicmemory
if ratio >= aperc
ub := testvalue
break
else
continue
lowband = plot(db, 'LowBand', color.new(color.aqua, 0))
highband = plot(ub, 'HighBand', color.new(color.aqua, 0))
plot(crsi, 'CRSI', color.new(color.fuchsia, 0))
Here we go with my python code:
import backtrader as bt
import backtrader.analyzers as btanalyzers
import backtrader.indicators as btind
import yfinance as yf
import matplotlib as plt
import numpy as np
import pandas as pd
from datetime import datetime
class CycledRSI(bt.Indicator):
lines = ('crsi',
'lower_band',
'upper_band',)
params = (
('domcycle', 44),
('smoothed', 1),
('leveling', 10.0)
)
def __init__(self):
src = self.data.close
domcycle = self.params.domcycle
smoothing = self.params.smoothed
leveling = self.params.leveling
cyclelen = int(domcycle / 2)
vibration = 10
torque = 2.0 / (vibration + 1)
phasingLag = int((vibration - 1) / 2.0)
rsi = bt.ind.RSI(src, period=cyclelen)
# Calculate CRSI
if len(rsi) > phasingLag:
crsi = torque * (2 * rsi - rsi(-phasingLag)) + (1 - torque) * self.l.crsi(-1)
else:
crsi = rsi
self.lines.crsi = crsi #return object
# Until here works fine to me. Problem start with from here
# Calculate lmax and lmin - not working yet
self.db = 0.0
self.ub = 100.0
lmax = -999999.0
lmin = 999999.0
cyclicmemory = int(domcycle * 2)
# I skipped this lines of code from pine script because they didn't made sense to me. But maybe you know better!
# for i = 0 to cyclicmemory - 1 by 1
# if nz(crsi[i], -999999.0) > lmax
# lmax := nz(crsi[i])
# lmax
# else
# if nz(crsi[i], 999999.0) < lmin
# lmin := nz(crsi[i])
# lmin
mstep = (lmax - lmin) / 100
aperc = leveling / 100
for steps in range(100):
testvalue = lmin + mstep * steps
for m in range(cyclicmemory-1):
if crsi[m] < testvalue: //Error: Array out of range!
below += 1
else:
below += 0
ratio = below / cyclicmemory
if ratio >= aperc:
self.db = testvalue
break
else:
continue
#another way to try upper-band not finish!
for steps in range(100):
testvalue = lmax - mstep * steps
for m in range(cyclicmemory-1):
above = np.sum(crsi >= testvalue)
ratio = above / cyclicmemory
if ratio >= aperc:
self.ub = testvalue
break
def next(self):
# next function can return values. Otherwise we need return a object.
self.lines.upper_band[0] = self.ub
self.lines.lower_band[0] = self.db
class MyTPstrat(bt.Strategy):
def __init__(self):
for data in self.datas:
crsi = CycledRSI(data)
[...]
cerebro = bt.Cerebro()
#for now just one asset
df = yf.download("BTC-USD", start='2023-02-01')
data = bt.feeds.PandasData(dataname=df)
cerebro.adddata(data)
#Strategy Settings
cerebro.addstrategy(MyTPstrat)
cerebro.broker.setcash(1000) # Set initial cash
cerebro.broker.setcommission(commission=(0.08/100)) # Set commission
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
#Plot
plt.rcParams['figure.figsize'] = [15, 10]
plt.rcParams.update({'font.size': 12})
cerebro.plot(iplot = False, )
Chart looks good but bands not working of cause.
enter image description here
I added some comments on line which not makes sense to me. But maybe there is a reason because of pine script “bugs” or it’s limit.
I tried different way to convert the upper and lower bands. The current code makes so most sense to me but probably need a little push in the logic.
I would appreciate if anybody can help me with the Error. It seems that I didn’t convert it correctly. 🙂
Dev-Joe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.