There is no issue with the code. Data wasn't clean hence causing the issue. Once I run the code with clean data, it worked.
Thanks
Best posts made by Sabir Jana
-
RE: Rebalancing - Conservative Formula
-
RE: Can get backtrader to buy on the 1st of the month
@run-out Thank you!!! understood the mistake at my end and got it now. I highly appreciate your on-time help. Many thanks again.
-SJ
Latest posts made by Sabir Jana
-
RE: Can get backtrader to buy on the 1st of the month
@run-out Thank you!!! understood the mistake at my end and got it now. I highly appreciate your on-time help. Many thanks again.
-SJ -
RE: ZeroDivisionError: float division by zero
@run-out Thank you! I see you have responded on a similar issue on another thread. Let me check that our and only if needed, will open an issue.
Thanks
SJ -
RE: Can get backtrader to buy on the 1st of the month
@ab_trader
Hello, I too facing the timer issue, it doesn't trigger not only for this simple buy and hold but anywhere I tried. The pandas feed I am using has datetime index, I also tried tz_localize('UTC')prices.index = prices.index.tz_localize('UTC') prices.info() DatetimeIndex: 2792 entries, 2009-01-02 00:00:00+00:00 to 2020-05-19 00:00:00+00:00 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 open 2792 non-null float64 1 high 2792 non-null float64 2 low 2792 non-null float64 3 close 2792 non-null float64 4 volume 2792 non-null float64 prices.head() open high low close volume date 2009-01-02 00:00:00+00:00 145.625000 145.625000 140.475006 50.516472 9012080.0 2009-01-05 00:00:00+00:00 142.500000 148.087006 142.462006 52.332775 11241232.0 2009-01-06 00:00:00+00:00 147.500000 148.750000 143.169006 52.143211 11563864.0 2009-01-07 00:00:00+00:00 146.393997 149.694000 143.199997 52.991051 22538352.0 2009-01-09 00:00:00+00:00 148.261993 158.324997 146.250000 53.698215 40182160.0
I appreciate any help!!
-
RE: ZeroDivisionError: float division by zero
@Ronny-Li said in ZeroDivisionError: float division by zero:
inv = [bt.DivByZero(bt.LineNum(1), v) for v in vs]
Hello Ronny, Thanks a ton!! it worked.
If I may share another issue faced by me is monthly rebalancing. The workaround I do to resample data for monthly frequency and run the backtest. I tried below code to trigger monthly rebalancing on daily price series however looking at the log I understand it's not working. Appreciate help/ pointersclass Strategy(bt.Strategy): params = dict( selcperc=0.15, # percentage of stocks to select from the universe rperiod=1, # period for the returns calculation, default 1 period vperiod=126, # lookback period for volatility - default 36 periods mperiod=126, # lookback period for momentum - default 12 periods reserve=0.05, # 5% reserve capital when=bt.timer.SESSION_END, #SESSION_START, timer=True, monthdays=[1], monthcarry=True ) def log(self, arg): print('{} {}'.format(self.datetime.date(), arg)) def __init__(self): # bt.indicators.Stochastic(self.datas[0], safediv=True) # calculate 1st the amount of stocks that will be selected self.selnum = int(len(self.datas) * self.p.selcperc) # allocation perc per stock # reserve kept to make sure orders are not rejected due to # margin. Prices are calculated when known (close), but orders can only # be executed next day (opening price). Price can gap upwards self.perctarget = (1.0 - self.p.reserve) / self.selnum # returns, volatilities and momentums rs = [bt.ind.PctChange(d, period=self.p.rperiod) for d in self.datas] # safediv safezero vs = [bt.ind.StdDev(ret, period=self.p.vperiod) for ret in rs] ms = [bt.ind.ROC(d, period=self.p.mperiod) for d in self.datas] # simple rank formula: (momentum * net payout) / volatility # the highest ranked: low vol, large momentum, large payout # self.ranks = {d: d.npy * m / v for d, v, m in zip(self.datas, vs, ms)} self.ranks = {d: m / v for d, v, m in zip(self.datas, vs, ms)} # self.add_timer( # when=self.p.when, # monthdays=self.p.monthdays, # monthcarry=self.p.monthcarry # ) # Add a timer which will be called on the 1st trading day of the month self.add_timer( bt.timer.SESSION_END, # when it will be called monthdays=[1], # called on the 1st day of the month monthcarry=self.p.monthcarry, # called on the 2nd day if the 1st is holiday ) def notify_timer(self, timer, when, *args, **kwargs): if self._getminperstatus() < 0: self.rebalance() def rebalance(self): # sort data and current rank ranks = sorted( self.ranks.items(), # get the (d, rank), pair key=lambda x: x[1][0], # use rank (elem 1) and current time "0" reverse=True, # highest ranked 1st ... please ) # put top ranked in dict with data as key to test for presence rtop = dict(ranks[:self.selnum]) # For logging purposes of stocks leaving the portfolio rbot = dict(ranks[self.selnum:]) # prepare quick lookup list of stocks currently holding a position posdata = [d for d, pos in self.getpositions().items() if pos] # remove those no longer top ranked # do this first to issue sell orders and free cash for d in (d for d in posdata if d not in rtop): self.log('Leave {} - Rank {:.2f}'.format(d._name, rbot[d][0])) self.order_target_percent(d, target=0.0) # rebalance those already top ranked and still there for d in (d for d in posdata if d in rtop): self.log('Rebal {} - Rank {:.2f}'.format(d._name, rtop[d][0])) self.order_target_percent(d, target=self.perctarget) del rtop[d] # remove it, to simplify next iteration # issue a target order for the newly top ranked stocks # do this last, as this will generate buy orders consuming cash for d in rtop: self.log('Enter {} - Rank {:.2f}'.format(d._name, rtop[d][0])) self.order_target_percent(d, target=self.perctarget) def next(self): self.notify_timer(self, self.p.timer, self.p.when)
Execution Log:
Starting Portfolio Value: 100000.00 2014-07-07 Enter CONCOR.NS - Rank 46.67 2014-07-07 Enter AUROPHARMA.NS - Rank 43.93 2014-07-07 Enter SHREECEM.NS - Rank 42.47 2014-07-07 Enter LT.NS - Rank 38.76 2014-07-07 Enter PFC.NS - Rank 36.94 2014-07-07 Enter SBIN.NS - Rank 36.59 2014-07-07 Enter ASHOKLEY.NS - Rank 35.69 2014-07-07 Enter MOTHERSUMI.NS - Rank 34.47 2014-07-07 Enter EICHERMOT.NS - Rank 34.41 2014-07-07 Enter PNB.NS - Rank 34.04 2014-07-07 Enter PGHH.NS - Rank 33.73 2014-07-07 Enter TITAN.NS - Rank 32.30 2014-07-07 Enter BPCL.NS - Rank 31.73 2014-07-08 Leave ASHOKLEY.NS - Rank 28.06 2014-07-08 Leave TITAN.NS - Rank 27.23 2014-07-08 Rebal AUROPHARMA.NS - Rank 35.99 2014-07-08 Rebal BPCL.NS - Rank 31.08 2014-07-08 Rebal CONCOR.NS - Rank 38.02 2014-07-08 Rebal LT.NS - Rank 36.04 2014-07-08 Rebal MOTHERSUMI.NS - Rank 30.61 2014-07-08 Rebal PFC.NS - Rank 31.57 2014-07-08 Rebal PGHH.NS - Rank 32.45 2014-07-08 Rebal PNB.NS - Rank 30.18 2014-07-08 Rebal SBIN.NS - Rank 33.78 2014-07-08 Rebal SHREECEM.NS - Rank 40.49 2014-07-08 Enter EICHERMOT.NS - Rank 33.64 2014-07-08 Enter BAJAJHLDNG.NS - Rank 32.01 2014-07-08 Enter AXISBANK.NS - Rank 30.54 2014-07-09 Leave AUROPHARMA.NS - Rank 26.37 2014-07-09 Rebal AXISBANK.NS - Rank 30.17 2014-07-09 Rebal BAJAJHLDNG.NS - Rank 29.87 2014-07-09 Rebal BPCL.NS - Rank 32.39 2014-07-09 Rebal CONCOR.NS - Rank 37.63 2014-07-09 Rebal LT.NS - Rank 34.93 2014-07-09 Rebal MOTHERSUMI.NS - Rank 29.34 2014-07-09 Rebal PFC.NS - Rank 30.32 2014-07-09 Rebal PGHH.NS - Rank 30.47 2014-07-09 Rebal PNB.NS - Rank 30.50 2014-07-09 Rebal SBIN.NS - Rank 35.63 2014-07-09 Rebal SHREECEM.NS - Rank 38.99 2014-07-09 Enter EICHERMOT.NS - Rank 31.73 2014-07-09 Enter ICICIBANK.NS - Rank 28.64 2014-07-10 Leave BAJAJHLDNG.NS - Rank 29.43 2014-07-10 Leave ICICIBANK.NS - Rank 27.20 2014-07-10 Rebal AXISBANK.NS - Rank 31.25 2014-07-10 Rebal BPCL.NS - Rank 33.67 2014-07-10 Rebal CONCOR.NS - Rank 40.36 2014-07-10 Rebal LT.NS - Rank 34.31 2014-07-10 Rebal MOTHERSUMI.NS - Rank 33.70 2014-07-10 Rebal PFC.NS - Rank 34.81 2014-07-10 Rebal PGHH.NS - Rank 29.82 2014-07-10 Rebal PNB.NS - Rank 30.65 2014-07-10 Rebal SBIN.NS - Rank 35.79 2014-07-10 Rebal SHREECEM.NS - Rank 39.86 2014-07-10 Enter EICHERMOT.NS - Rank 30.94 2014-07-10 Enter PAGEIND.NS - Rank 30.30 2014-07-10 Enter ADANIPORTS.NS - Rank 29.64 2014-07-11 Leave ADANIPORTS.NS - Rank 21.94 2014-07-11 Leave PFC.NS - Rank 26.35 2014-07-11 Leave PNB.NS - Rank 26.56 2014-07-11 Rebal AXISBANK.NS - Rank 30.62 2014-07-11 Rebal BPCL.NS - Rank 32.29 2014-07-11 Rebal CONCOR.NS - Rank 34.57 2014-07-11 Rebal LT.NS - Rank 30.98 2014-07-11 Rebal MOTHERSUMI.NS - Rank 30.25 2014-07-11 Rebal PGHH.NS - Rank 28.42 2014-07-11 Rebal SBIN.NS - Rank 31.46 2014-07-11 Rebal SHREECEM.NS - Rank 37.59 2014-07-11 Enter EICHERMOT.NS - Rank 30.97 2014-07-11 Enter PAGEIND.NS - Rank 28.64 2014-07-11 Enter IOC.NS - Rank 28.58 2014-07-11 Enter AUROPHARMA.NS - Rank 28.29 2014-07-11 Enter HINDPETRO.NS - Rank 27.17 2014-07-14 Leave IOC.NS - Rank 26.02 2014-07-14 Leave MOTHERSUMI.NS - Rank 26.31 2014-07-14 Rebal AUROPHARMA.NS - Rank 30.59 2014-07-14 Rebal AXISBANK.NS - Rank 34.12 2014-07-14 Rebal BPCL.NS - Rank 31.61 2014-07-14 Rebal CONCOR.NS - Rank 34.03 2014-07-14 Rebal HINDPETRO.NS - Rank 27.88 2014-07-14 Rebal LT.NS - Rank 34.89 2014-07-14 Rebal PGHH.NS - Rank 28.22 2014-07-14 Rebal SBIN.NS - Rank 31.84 2014-07-14 Rebal SHREECEM.NS - Rank 38.14 2014-07-14 Enter EICHERMOT.NS - Rank 31.50 2014-07-14 Enter PFC.NS - Rank 29.32 2014-07-14 Enter PNB.NS - Rank 28.90 2014-07-14 Enter HAVELLS.NS - Rank 27.97 2014-07-15 Leave HAVELLS.NS - Rank 29.65 2014-07-15 Rebal AUROPHARMA.NS - Rank 34.18 2014-07-15 Rebal AXISBANK.NS - Rank 38.14 2014-07-15 Rebal BPCL.NS - Rank 32.98 2014-07-15 Rebal CONCOR.NS - Rank 36.38 2014-07-15 Rebal HINDPETRO.NS - Rank 29.95 2014-07-15 Rebal LT.NS - Rank 38.46 2014-07-15 Rebal PFC.NS - Rank 32.38 2014-07-15 Rebal PGHH.NS - Rank 30.71 2014-07-15 Rebal PNB.NS - Rank 31.95 2014-07-15 Rebal SBIN.NS - Rank 36.52 2014-07-15 Rebal SHREECEM.NS - Rank 37.98 2014-07-15 Enter EICHERMOT.NS - Rank 34.44 2014-07-15 Enter MOTHERSUMI.NS - Rank 30.71 2014-07-16 Leave PFC.NS - Rank 28.23 2014-07-16 Rebal AUROPHARMA.NS - Rank 37.10 2014-07-16 Rebal AXISBANK.NS - Rank 39.30 2014-07-16 Rebal BPCL.NS - Rank 32.91 2014-07-16 Rebal CONCOR.NS - Rank 38.53 2014-07-16 Rebal HINDPETRO.NS - Rank 30.86 2014-07-16 Rebal LT.NS - Rank 37.69 2014-07-16 Rebal MOTHERSUMI.NS - Rank 35.12 2014-07-16 Rebal PGHH.NS - Rank 31.92 2014-07-16 Rebal PNB.NS - Rank 31.67 2014-07-16 Rebal SBIN.NS - Rank 36.63 2014-07-16 Rebal SHREECEM.NS - Rank 38.88 2014-07-16 Enter EICHERMOT.NS - Rank 33.98 2014-07-16 Enter ADANIPORTS.NS - Rank 31.71 2014-07-17 Leave ADANIPORTS.NS - Rank 31.33 2014-07-17 Leave PGHH.NS - Rank 28.79 2014-07-17 Rebal AUROPHARMA.NS - Rank 36.68 2014-07-17 Rebal AXISBANK.NS - Rank 39.47 2014-07-17 Rebal BPCL.NS - Rank 33.75 2014-07-17 Rebal CONCOR.NS - Rank 40.51 2014-07-17 Rebal HINDPETRO.NS - Rank 31.85 2014-07-17 Rebal LT.NS - Rank 39.13 2014-07-17 Rebal MOTHERSUMI.NS - Rank 35.79 2014-07-17 Rebal PNB.NS - Rank 32.22 2014-07-17 Rebal SBIN.NS - Rank 38.27 2014-07-17 Rebal SHREECEM.NS - Rank 39.25 2014-07-17 Enter EICHERMOT.NS - Rank 36.00 2014-07-17 Enter HAVELLS.NS - Rank 34.63 2014-07-17 Enter ULTRACEMCO.NS - Rank 32.15 2014-07-18 Leave HINDPETRO.NS - Rank 28.44 2014-07-18 Leave PNB.NS - Rank 29.86 2014-07-18 Leave ULTRACEMCO.NS - Rank 27.88 2014-07-18 Rebal AUROPHARMA.NS - Rank 37.18 2014-07-18 Rebal AXISBANK.NS - Rank 41.21 2014-07-18 Rebal BPCL.NS - Rank 32.85 2014-07-18 Rebal CONCOR.NS - Rank 40.39 2014-07-18 Rebal HAVELLS.NS - Rank 36.26 2014-07-18 Rebal LT.NS - Rank 37.78 2014-07-18 Rebal MOTHERSUMI.NS - Rank 35.56 2014-07-18 Rebal SBIN.NS - Rank 36.24 2014-07-18 Rebal SHREECEM.NS - Rank 38.80 2014-07-18 Enter EICHERMOT.NS - Rank 36.03 2014-07-18 Enter ICICIBANK.NS - Rank 30.90 2014-07-18 Enter ASHOKLEY.NS - Rank 30.70 2014-07-18 Enter ADANIPORTS.NS - Rank 30.63 2014-07-21 Leave ASHOKLEY.NS - Rank 29.98 2014-07-21 Rebal ADANIPORTS.NS - Rank 30.28 2014-07-21 Rebal AUROPHARMA.NS - Rank 33.30 2014-07-21 Rebal AXISBANK.NS - Rank 42.66 2014-07-21 Rebal BPCL.NS - Rank 31.95 2014-07-21 Rebal CONCOR.NS - Rank 40.64 2014-07-21 Rebal HAVELLS.NS - Rank 33.77 2014-07-21 Rebal ICICIBANK.NS - Rank 30.98 2014-07-21 Rebal LT.NS - Rank 36.36 2014-07-21 Rebal MOTHERSUMI.NS - Rank 34.23 2014-07-21 Rebal SBIN.NS - Rank 35.12 2014-07-21 Rebal SHREECEM.NS - Rank 40.04 2014-07-21 Enter EICHERMOT.NS - Rank 35.67 2014-07-21 Enter PAGEIND.NS - Rank 30.67 2014-07-22 Leave ADANIPORTS.NS - Rank 30.48 2014-07-22 Leave BPCL.NS - Rank 30.13 2014-07-22 Rebal AUROPHARMA.NS - Rank 35.39 2014-07-22 Rebal AXISBANK.NS - Rank 44.50 2014-07-22 Rebal CONCOR.NS - Rank 44.00 2014-07-22 Rebal HAVELLS.NS - Rank 34.87 2014-07-22 Rebal ICICIBANK.NS - Rank 33.02 2014-07-22 Rebal LT.NS - Rank 35.56 2014-07-22 Rebal MOTHERSUMI.NS - Rank 34.47 2014-07-22 Rebal SBIN.NS - Rank 35.92 2014-07-22 Rebal SHREECEM.NS - Rank 37.68 2014-07-22 Enter EICHERMOT.NS - Rank 35.59 2014-07-22 Enter PNB.NS - Rank 31.50 2014-07-22 Enter PFC.NS - Rank 30.66 2014-07-22 Enter ASHOKLEY.NS - Rank 30.55 2014-07-23 Leave PFC.NS - Rank 30.53 2014-07-23 Rebal ASHOKLEY.NS - Rank 31.39 2014-07-23 Rebal AUROPHARMA.NS - Rank 31.51 2014-07-23 Rebal AXISBANK.NS - Rank 42.79 2014-07-23 Rebal CONCOR.NS - Rank 41.76 2014-07-23 Rebal HAVELLS.NS - Rank 31.93 2014-07-23 Rebal ICICIBANK.NS - Rank 33.48 2014-07-23 Rebal LT.NS - Rank 35.85 2014-07-23 Rebal MOTHERSUMI.NS - Rank 30.82 2014-07-23 Rebal PNB.NS - Rank 31.00 2014-07-23 Rebal SBIN.NS - Rank 35.45 2014-07-23 Rebal SHREECEM.NS - Rank 37.84 2014-07-23 Enter EICHERMOT.NS - Rank 33.90 2014-07-23 Enter BPCL.NS - Rank 31.62 2014-07-24 Leave AUROPHARMA.NS - Rank 28.30 2014-07-24 Rebal ASHOKLEY.NS - Rank 32.42 2014-07-24 Rebal AXISBANK.NS - Rank 40.71 2014-07-24 Rebal BPCL.NS - Rank 33.21 2014-07-24 Rebal CONCOR.NS - Rank 42.58 2014-07-24 Rebal HAVELLS.NS - Rank 32.82 2014-07-24 Rebal ICICIBANK.NS - Rank 31.19 2014-07-24 Rebal LT.NS - Rank 35.29 2014-07-24 Rebal MOTHERSUMI.NS - Rank 30.00 2014-07-24 Rebal PNB.NS - Rank 30.52 2014-07-24 Rebal SBIN.NS - Rank 35.13 2014-07-24 Rebal SHREECEM.NS - Rank 34.77 2014-07-24 Enter EICHERMOT.NS - Rank 32.88 2014-07-24 Enter PFC.NS - Rank 29.63 2014-07-25 Leave PFC.NS - Rank 27.90 2014-07-25 Rebal ASHOKLEY.NS - Rank 29.14 2014-07-25 Rebal AXISBANK.NS - Rank 40.14 2014-07-25 Rebal BPCL.NS - Rank 30.27 2014-07-25 Rebal CONCOR.NS - Rank 42.54 2014-07-25 Rebal HAVELLS.NS - Rank 33.57 2014-07-25 Rebal ICICIBANK.NS - Rank 28.78 2014-07-25 Rebal LT.NS - Rank 35.62 2014-07-25 Rebal MOTHERSUMI.NS - Rank 29.60 2014-07-25 Rebal PNB.NS - Rank 29.44 2014-07-25 Rebal SBIN.NS - Rank 33.82 2014-07-25 Rebal SHREECEM.NS - Rank 37.58 2014-07-25 Enter EICHERMOT.NS - Rank 34.59 2014-07-25 Enter PETRONET.NS - Rank 29.75 2014-07-28 Leave ASHOKLEY.NS - Rank 26.90 2014-07-28 Rebal AXISBANK.NS - Rank 37.76 2014-07-28 Rebal BPCL.NS - Rank 27.34 2014-07-28 Rebal CONCOR.NS - Rank 37.34 2014-07-28 Rebal HAVELLS.NS - Rank 32.27 2014-07-28 Rebal ICICIBANK.NS - Rank 28.04 2014-07-28 Rebal LT.NS - Rank 32.41 2014-07-28 Rebal MOTHERSUMI.NS - Rank 33.21 2014-07-28 Rebal PETRONET.NS - Rank 29.41 2014-07-28 Rebal PNB.NS - Rank 31.49 2014-07-28 Rebal SBIN.NS - Rank 32.93 2014-07-28 Rebal SHREECEM.NS - Rank 39.10 2014-07-28 Enter EICHERMOT.NS - Rank 35.07 2014-07-28 Enter PFC.NS - Rank 27.19 2014-07-30 Leave BPCL.NS - Rank 28.06 2014-07-30 Leave LT.NS - Rank 26.83 2014-07-30 Rebal AXISBANK.NS - Rank 40.11 2014-07-30 Rebal CONCOR.NS - Rank 40.12 2014-07-30 Rebal HAVELLS.NS - Rank 30.97 2014-07-30 Rebal ICICIBANK.NS - Rank 31.50 2014-07-30 Rebal MOTHERSUMI.NS - Rank 34.60 2014-07-30 Rebal PETRONET.NS - Rank 30.49 2014-07-30 Rebal PFC.NS - Rank 31.60 2014-07-30 Rebal PNB.NS - Rank 37.99 2014-07-30 Rebal SBIN.NS - Rank 34.20 2014-07-30 Rebal SHREECEM.NS - Rank 40.88 2014-07-30 Enter EICHERMOT.NS - Rank 36.10 2014-07-30 Enter ASHOKLEY.NS - Rank 32.29 2014-07-30 Enter TITAN.NS - Rank 29.98 2014-07-31 Leave TITAN.NS - Rank 30.74 2014-07-31 Rebal ASHOKLEY.NS - Rank 33.71 2014-07-31 Rebal AXISBANK.NS - Rank 41.55 2014-07-31 Rebal CONCOR.NS - Rank 39.78 2014-07-31 Rebal HAVELLS.NS - Rank 37.30 2014-07-31 Rebal ICICIBANK.NS - Rank 34.95 2014-07-31 Rebal MOTHERSUMI.NS - Rank 38.18 2014-07-31 Rebal PETRONET.NS - Rank 35.87 2014-07-31 Rebal PFC.NS - Rank 36.63 2014-07-31 Rebal PNB.NS - Rank 41.66 2014-07-31 Rebal SBIN.NS - Rank 34.58 2014-07-31 Rebal SHREECEM.NS - Rank 44.88 2014-07-31 Enter EICHERMOT.NS - Rank 37.48 2014-07-31 Enter PGHH.NS - Rank 31.19 2014-08-01 Leave PGHH.NS - Rank 31.49 2014-08-01 Rebal ASHOKLEY.NS - Rank 33.93 2014-08-01 Rebal AXISBANK.NS - Rank 44.33 2014-08-01 Rebal CONCOR.NS - Rank 36.67 2014-08-01 Rebal HAVELLS.NS - Rank 32.24 2014-08-01 Rebal ICICIBANK.NS - Rank 34.48 2014-08-01 Rebal MOTHERSUMI.NS - Rank 35.42 2014-08-01 Rebal PETRONET.NS - Rank 37.81 2014-08-01 Rebal PFC.NS - Rank 34.10 2014-08-01 Rebal PNB.NS - Rank 41.39 2014-08-01 Rebal SBIN.NS - Rank 34.42 2014-08-01 Rebal SHREECEM.NS - Rank 44.25 2014-08-01 Enter EICHERMOT.NS - Rank 37.08 2014-08-01 Enter MARUTI.NS - Rank 34.32 2014-08-04 Leave HAVELLS.NS - Rank 29.66 2014-08-04 Rebal ASHOKLEY.NS - Rank 36.26 2014-08-04 Rebal AXISBANK.NS - Rank 43.75 2014-08-04 Rebal CONCOR.NS - Rank 36.85 2014-08-04 Rebal ICICIBANK.NS - Rank 36.91 2014-08-04 Rebal MARUTI.NS - Rank 31.97 2014-08-04 Rebal MOTHERSUMI.NS - Rank 37.13 2014-08-04 Rebal PETRONET.NS - Rank 33.84 2014-08-04 Rebal PFC.NS - Rank 33.88 2014-08-04 Rebal PNB.NS - Rank 43.70 2014-08-04 Rebal SBIN.NS - Rank 36.44 2014-08-04 Rebal SHREECEM.NS - Rank 42.08 2014-08-04 Enter EICHERMOT.NS - Rank 38.96 2014-08-04 Enter TATAMTRDVR.NS - Rank 31.49 2014-08-05 Leave PETRONET.NS - Rank 30.15 2014-08-05 Leave TATAMTRDVR.NS - Rank 31.60 2014-08-05 Rebal ASHOKLEY.NS - Rank 37.32 2014-08-05 Rebal AXISBANK.NS - Rank 47.66 2014-08-05 Rebal CONCOR.NS - Rank 37.98 2014-08-05 Rebal ICICIBANK.NS - Rank 39.26 2014-08-05 Rebal MARUTI.NS - Rank 34.96 2014-08-05 Rebal MOTHERSUMI.NS - Rank 39.71 .......
-
RE: ZeroDivisionError: float division by zero
Please accept my apology for bad formatting.
-
ZeroDivisionError: float division by zero
Hi, Very frequently I struggled with float division by zero error. It goes away only after removing multiple tickers data. I went thru existing threads and suggested solutions to supply ```
safediv or safezerohowever this parameter is not valid for all indicators. Appreciate any help! Attached is the code
class Strategy(bt.Strategy):
params = dict(
selcperc=0.15, # percentage of stocks to select from the universe
rperiod=1, # period for the returns calculation, default 1 period
vperiod=252, # lookback period for volatility - default 36 periods
mperiod=126, # lookback period for momentum - default 12 periods
reserve=0.05, # 5% reserve capital
when=bt.timer.SESSION_START,
timer=True,
monthdays=[1],
monthcarry=True
)def log(self, arg): print('{} {}'.format(self.datetime.date(), arg)) def __init__(self):
bt.indicators.Stochastic(self.datas[0], safediv=True)
# calculate 1st the amount of stocks that will be selected self.selnum = int(len(self.datas) * self.p.selcperc) # allocation perc per stock # reserve kept to make sure orders are not rejected due to # margin. Prices are calculated when known (close), but orders can only # be executed next day (opening price). Price can gap upwards self.perctarget = (1.0 - self.p.reserve) / self.selnum # returns, volatilities and momentums rs = [bt.ind.PctChange(d, period=self.p.rperiod) for d in self.datas] # safediv safezero vs = [bt.ind.StdDev(ret, period=self.p.vperiod) for ret in rs] ms = [bt.ind.ROC(d, period=self.p.mperiod) for d in self.datas] # simple rank formula: (momentum * net payout) / volatility # the highest ranked: low vol, large momentum, large payout
self.ranks = {d: d.npy * m / v for d, v, m in zip(self.datas, vs, ms)}
self.ranks = {d: m / v for d, v, m in zip(self.datas, vs, ms)} self.add_timer( when=self.p.when, monthdays=self.p.monthdays, monthcarry=self.p.monthcarry ) def notify_timer(self, timer, when, *args, **kwargs): if self._getminperstatus() < 0: self.rebalance() def rebalance(self): # sort data and current rank ranks = sorted( self.ranks.items(), # get the (d, rank), pair key=lambda x: x[1][0], # use rank (elem 1) and current time "0" reverse=True, # highest ranked 1st ... please ) # put top ranked in dict with data as key to test for presence rtop = dict(ranks[:self.selnum]) # For logging purposes of stocks leaving the portfolio rbot = dict(ranks[self.selnum:]) # prepare quick lookup list of stocks currently holding a position posdata = [d for d, pos in self.getpositions().items() if pos] # remove those no longer top ranked # do this first to issue sell orders and free cash for d in (d for d in posdata if d not in rtop): self.log('Leave {} - Rank {:.2f}'.format(d._name, rbot[d][0])) self.order_target_percent(d, target=0.0) # rebalance those already top ranked and still there for d in (d for d in posdata if d in rtop): self.log('Rebal {} - Rank {:.2f}'.format(d._name, rtop[d][0])) self.order_target_percent(d, target=self.perctarget) del rtop[d] # remove it, to simplify next iteration # issue a target order for the newly top ranked stocks # do this last, as this will generate buy orders consuming cash for d in rtop: self.log('Enter {} - Rank {:.2f}'.format(d._name, rtop[d][0])) self.order_target_percent(d, target=self.perctarget) def next(self): self.notify_timer(self, self.p.timer, self.p.when)
Error
C:\ProgramData\Anaconda3\lib\site-packages\backtrader\cerebro.py in run(self, **kwargs) 1125 # let's skip process "spawning" 1126 for iterstrat in iterstrats: -> 1127 runstrat = self.runstrategies(iterstrat) 1128 self.runstrats.append(runstrat) 1129 if self._dooptimize: C:\ProgramData\Anaconda3\lib\site-packages\backtrader\cerebro.py in runstrategies(self, iterstrat, predata) 1291 self._runonce_old(runstrats) 1292 else: -> 1293 self._runonce(runstrats) 1294 else: 1295 if self.p.oldsync: C:\ProgramData\Anaconda3\lib\site-packages\backtrader\cerebro.py in _runonce(self, runstrats) 1650 ''' 1651 for strat in runstrats: -> 1652 strat._once() 1653 strat.reset() # strat called next by next - reset lines 1654 C:\ProgramData\Anaconda3\lib\site-packages\backtrader\lineiterator.py in _once(self) 295 296 for indicator in self._lineiterators[LineIterator.IndType]: --> 297 indicator._once() 298 299 for observer in self._lineiterators[LineIterator.ObsType]: C:\ProgramData\Anaconda3\lib\site-packages\backtrader\linebuffer.py in _once(self) 629 self.preonce(0, self._minperiod - 1) 630 self.oncestart(self._minperiod - 1, self._minperiod) --> 631 self.once(self._minperiod, self.buflen()) 632 633 self.oncebinding() C:\ProgramData\Anaconda3\lib\site-packages\backtrader\linebuffer.py in once(self, start, end) 753 def once(self, start, end): 754 if self.bline: --> 755 self._once_op(start, end) 756 elif not self.r: 757 if not self.btime: C:\ProgramData\Anaconda3\lib\site-packages\backtrader\linebuffer.py in _once_op(self, start, end) 770 771 for i in range(start, end): --> 772 dst[i] = op(srca[i], srcb[i]) 773 774 def _once_time_op(self, start, end): ZeroDivisionError: float division by zero
-
RE: Rebalancing - Conservative Formula
There is no issue with the code. Data wasn't clean hence causing the issue. Once I run the code with clean data, it worked.
Thanks -
RE: Rebalancing - Conservative Formula
It looks like a data issue, I get this when I change the frequency from daily to monthly.