Make calcul with indicator
-
Hi BackTrader !!!
How are you ?
Could you explain to me how can I use the line values to use them in math formuler ?class MyStrategy(bt.Strategy): params = dict(period=20) def __init__(self): self.movav = btind.SimpleMovingAverage(self.data, period=self.p.period) self.test = ((self.movav.lines.sma(0) - self.movav.lines.sma(-2)) / 2 def next(self): if self.movav.lines.sma[0] > self.data.lines.close[0]: print('Simple Moving Average is greater than the closing price')
Regards
-
You are actually doing it.
self.movav.lines.sma[0] > self.data.lines.close[0]
is an mathematic operation of comparing the current barssma-value
over current barsclose value
. Itsa>b
. -
@cgi1 said in Make calcul with indicator:
a
Hi cgi1
thanks for your help.I would like to do something like this :
def __init__(self): self.sma0 = btind.MovAv.SMA(self.data, period=12) self.sma1 = ((self.sma0.lines.sma(0) - self.sma0.lines.sma(1)) / 2) def next(self): print(" sma1: %s" %( self.sma1[0]))
but the result I 've is "nan"
sma1: nan
sma1: nan
sma1: nan
sma1: nan
sma1: nan -
The value is
nan
if you access a value which could not be calculated from the indicator. (e.g. the first 199 bars of an EMA200). -
I would like to play with the indicator. @backtrader How can I do it ?
I'm have a lots of fun working with this plateforme.Regards,
-
@GwadaMan Replace
self.sma0.lines.sma(1)
withself.sma0.lines.sma(-1)
. You think you're referencing the past, but positive numbers reference the future, not the past, and strategies should never reference the future, for obvious reasons. This is probably why you are gettingnan
. Make that change and see if it fixes the problem. -
Hi Curtis,
Thank you very much for the correction. It works !!!
We can close this case.
Regards, -
@GwadaMan said in Make calcul with indicator:
def __init__(self): self.sma0 = btind.MovAv.SMA(self.data, period=12) self.sma1 = ((self.sma0.lines.sma(0) - self.sma0.lines.sma(1)) / 2)
A couple of comments for potential simplifications (some may for sure see it as more complex)
self.sma0 = btind.MovAv.SMA(self.data, period=12)
This can be usually simplified to:
self.sma0 = btind.MovAv.SMA(period=12)
When no specific data is specified, the 1st data of wherever the calculation is being made is implied.
self.sma1 = ((self.sma0.lines.sma(0) - self.sma0.lines.sma(-1)) / 2)
can be also be simplified to:
self.sma1 = ((self.sma0.lines.sma - self.sma0.lines.sma(-1)) / 2)
where there is no need to specify the
(0)
, because the reference is implicit in the operationAlthough @ntguardian is right and
(1)
points to the future, this can be used for real reasons. For example to push values from the future into the past as it is done in theIchimoku
indicator. For example:... self.l.chikou_span = self.data.close(self.p.chikou) ...
This says that the current value of
chikou_span
has to be that of the futureclose
(self.p.chikou has a default positive value of26
)