Thank you for your answer.
I should have asked my question in a different way. I do know how to keep a reference in a class to a value but somehow it was not working in my code. Your answer opened my eyes: since I know how to program, the cause of error must have been somewhere else, not in the referencing method, so I could correct the code.
Latest posts made by tizenhet
RE: Buying price in next()
Buying price in next()
could you please give an example how 'to keep a reference to the order notified in notify_order, to later use it in next' (@backtrader)?
I would like to do calculations with the buying price in the next() method.
Thank you in advance!
Position size changes without buy or sell order
I have run backtest for different time frames and noticed that sometimes some of the stocks get 'virtual' positions without having bought them before.
This is what I have in next() for buying:
def next(self): portvalue = cerebro.broker.getvalue() availablecash=cerebro.broker.getcash() dt=self.datetime.date() for i, d in enumerate(self.datas): dn =d._name pos = self.getposition(d).size print(dt,dn,"Size:",pos) if pos==0: if d.volume==-1: if booleanvalue==True: dec_,int_=math.modf(allocation*portvalue/d.close) print(dn,'at $',round(d.close,2),'BUY CREATE, Size:',int_, 'Cash Spent to Buy:',round(d.close*int_,2)) self.buy(data=d, size=int_) self.order = self.buy()
(Please note that I add to cerebro a data set, in which buy and sell signals are indicated by the modified volume values, that's why I use the condition d.volume==-1.)
If I run the backtest for the period 31 Jul 2018 - 20 Aug 2018, 2 stocks are purchased during the first 4 days:
2018-07-31 NM.V Size: 0 2018-07-31 PAT.V Size: 0 2018-08-01 NM.V Size: 0 2018-08-01 PAT.V Size: 0 PAT.V at $ 1.71 BUY CREATE, Size: 14619.0 Cash Spent to Buy: 24998.49 2018-08-02 NM.V Size: 0 NM.V at $ 1.54 BUY CREATE, Size: 16067.0 Cash Spent to Buy: 24743.18 2018-08-02 PAT.V Size: 14619.0 2018-08-03 NM.V Size: 16067.0 2018-08-03 PAT.V Size: 14619.0
But if I run the backtest for only 31 Jul 2018 - 17 Aug 2018, only one stock is bought but the position size of an other is also changing (and that's why is not purchased, since the condition pos==0 is false):
2018-07-31 NM.V Size: 0 2018-07-31 PAT.V Size: 0 2018-08-01 NM.V Size: 0 2018-08-01 PAT.V Size: 0 PAT.V at $ 1.71 BUY CREATE, Size: 14619.0 Cash Spent to Buy: 24998.49 2018-08-02 NM.V Size: 1 2018-08-02 PAT.V Size: 14619.0 2018-08-03 NM.V Size: 1 2018-08-03 PAT.V Size: 14619.0
Please help me how it can happen.