Sizer based on ATR
-
Hi!
I try to implement Sizer based on ATR using bt.indicators.ATR. As a result, I get an error which I don't know how to solve, please help to fix that.class AtrBasedPositionSize(bt.Sizer): # list of parameters which are configurable for the sizer params = (('period', 20), ('risk', 0.05), ('ATR_multiple', 1.5)) def _getsizing(self, comminfo, cash, data, isbuy): if(len(data)<=self.p.period): return 0 self.ticker_ATR = bt.indicators.ATR(data, period=self.p.period) position_size = int((self.p.risk * self.broker.getvalue()) // (self.p.ATR_multiple * self.ticker_ATR)) return position_size ... cerebro.addsizer(AtrBasedPositionSize)
ERROR:
position_size = int((self.p.risk * self.broker.getvalue()) // (self.p.ATR_multiple * self.ticker_ATR))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'LinesOperation' -
either self.p.ATR_multiple, or self.ticker_ATR is a LinesOperation object. LinesOperation must have a property for the value that you are looking for.
-
Define
self.ticker_ATR
in the sizer's__init__()
, then useself.ticker_ATR[0]
in_getsizing()
method. Should work.If you use
ATR
in your strategy for other needs, than you can define it on the strategy level once and call in the_getsizing()
method. -
@ab_trader thanks, that works!
-
@ab_trader said in Sizer based on ATR:
Define
self.ticker_ATR
in the sizer's__init__()
, then useself.ticker_ATR[0]
in_getsizing()
method. Should work.If you use
ATR
in your strategy for other needs, than you can define it on the strategy level once and call in the_getsizing()
method.Hi @ab_trader ,
I try to apply your advices but i have an error :
class LongOnly(bt.Sizer): def __init__(self): self.dataatr=bt.indicators.ATR(data, period=20) def _getsizing(self, comminfo, cash, data, isbuy): if isbuy: divide = math.floor(5000/self.dataatr[0]) self.p.stake = divide return self.p.stake # Sell situation position = self.broker.getposition(data) if not position.size: return 0 # do not sell if nothing is open return self.p.stake
self.lines.truehigh = Max(self.data.high, self.data.close(-1))
File "F:\Software\Python\Python3.6\lib\site-packages\backtrader\lineseries.py", line 461, in getattr
return getattr(self.lines, name)
AttributeError: 'Lines_LineSeries_LineSeriesStub' object has no attribute 'high'Can you help me please ?
Regards
Ludo