AttributeError: type object 'timeAdjustment' has no attribute 'schedule'
-
Hi , I am trying to resample a one minute data set into one hour data set . However i noticed the timings of the trades i obtained were absurd. Hence i tried to create a calendar named "timeAdjustment" and input the market closing and finishing time etc .. However i get this error :
_, nexteos = self._calendar.schedule(dtime, self._tz) AttributeError: type object 'timeAdjustment' has no attribute 'schedule'
Below is my code , Can somebody pls give a reson and fix for the error ??
thanks# This is the Implementation for 9/30 Stratergy using python BackTrader import backtrader as bt from datetime import datetime import datetime as dt import pandas as pd import matplotlib.pyplot as plt from pandas_datareader import data as web class PullBack(bt.Strategy): def log(self, txt, dt=None): ''' Logging function fot this strategy''' dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): self.open = self.data.open self.high = self.data.high self.low = self.data.low self.close = self.data.close self.ema = bt.ind.ExponentialMovingAverage(self.data.close, period=9) self.wma = bt.ind.WeightedMovingAverage(self.data.close, period=30) self.order = None self.stop_order = None def next(self): #print("current portfolio value" + str(cerebro.broker.getvalue())) if not self.position: # Long Position if (self.ema[-1] > self.wma[-1]) and (self.data.high[-1] < self.ema[-1]) : #self.buy(size=100, exectype=bt.Order.StopLimit, price=self.data.high[-1]) self.order = self.buy(size=1, exectype=bt.Order.Limit, price=self.data.high[-1]) self.log('BUY PRICE CREATED , %.2f ' % self.data.high[-1]) risk = (self.data.high[-1] - self.data.low[-1]) self.log('Risk points , %.2f' % risk) # Place a stop loss order #self.sell(size=100, exectype=bt.Order.StopLimit, price=self.data.low[-1]) target_price = self.data.high[-1] + 2 * (self.data.high[-1] - self.data.low[-1]) self.log('TARGET PRICE ,%.2f ' % target_price) oc1 = self.sell(size=1, exectype=bt.Order.StopLimit, price=target_price) self.order = self.sell(size=1, exectype=bt.Order.Stop, price=self.data.low[-1], plimit=self.data.low[-1] , oco=oc1) elif (self.ema[-1] < self.wma[-1]) and (self.data.close[-1] > self.ema[-1] ) : self.order = self.sell(size=1,exectype=bt.Order.Limit,price=self.data.low[-1]) #Stop loss target_price = self.data.low[-1] - 2 * (self.data.high[-1] - self.data.low[-1]) self.order = self.sell(size=1,exectype=bt.Order.StopLimit,price=target_price) self.log('Short Sell initiated , %.2f' % self.data.low[-1]) def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: return if order.status in [order.Completed]: if order.isbuy(): self.log('BUY EXECUTED, %.2f' % order.executed.price) elif order.issell(): self.log('Sell order EXECUTED, %.2f' % order.executed.price) elif order.status in [order.Cancelled]: self.log('Order Canceled at price, %.2f' %order.price) elif order.status in [ order.Margin, order.Rejected]: self.log('Order Rejected or Margin error') self.order = None class timeAdjustment(): params = dict( holidays=[ dt.date(2018, 1, 26), dt.date(2018, 2, 13), dt.date(2018, 3, 2), dt.date(2018, 3, 29), dt.date(2018, 3, 30), dt.date(2018, 5, 1), dt.date(2018, 8, 15), dt.date(2018, 8, 22), dt.date(2018, 9, 13), dt.date(2018, 9, 18), dt.date(2018,10,2), dt.date(2018,10,18), dt.date(2018,11,8), dt.date(2018,11,23), dt.date(2018,12,2) ], earlydays=[ (dt.date(2018, 11, 7), dt.time(17, 31), dt.time(18, 31)) ], open=dt.time(9, 30), close=dt.time(15, 30), ) #Variable for our starting cash startcash = 100000 #Create an instance of cerebro cerebro = bt.Cerebro() #Add our strategy cerebro.addstrategy(PullBack) nifty_futures="C:\\Nikhil Media\\Education & Skills\\Stratergies_Codes\\inputs\\CleanedDir\\NiftyFutures\\NIFTY_F1.csv" data = bt.feeds.GenericCSVData( headers=True, dataname=nifty_futures, # 20200313 fromdate=datetime(2019, 1, 1), #year-month-date todate=datetime(2019, 12, 31), nullvalue=0.0, dtformat=("%Y%m%d"), tmformat=('%H:%M'), datetime=1, time=2, open=3, high=4, low=5, close=6, timeframe=bt.TimeFrame.Minutes ) cerebro.resampledata(data,timeframe=bt.TimeFrame.Minutes,compression=60,name='60_min_bar') cerebro.addcalendar(timeAdjustment) # Set our desired cash start cerebro.broker.setcash(startcash) # Add the analyzers we are interested in cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta") cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn") cerebro.broker.setcommission(commission=0.0005) # Run over everything strategies=cerebro.run() #Get final portfolio Value portvalue = cerebro.broker.getvalue() print("final and last port value: "+str(portvalue)) pnl = portvalue - startcash #Print out the final result print('Final Portfolio Value: ${}'.format(portvalue)) print('P/L: ${}'.format(pnl)) #Finally plot the end results cerebro.plot(style='candlestick',fmt_x_data = ('%Y-%m-%d %H:%M:%S'))
-
Try this -
class timeAdjustment(bt.TradingCalendar): # other stuff you have
-
@ab_trader thanks for the assist , I added the trading calender
class timeAdjustment(bt.TradingCalendar): params = dict( holidays=[ dt.date(2018, 1, 26), dt.date(2018, 2, 13), dt.date(2018, 3, 2), dt.date(2018, 3, 29), dt.date(2018, 3, 30), dt.date(2018, 5, 1), dt.date(2018, 8, 15), dt.date(2018, 8, 22), dt.date(2018, 9, 13), dt.date(2018, 9, 18), dt.date(2018,10,2), dt.date(2018,10,18), dt.date(2018,11,8), dt.date(2018,11,23), dt.date(2018,12,2) ], earlydays=[ (dt.date(2018, 11, 7), dt.time(17, 31), dt.time(18, 31)) ], open=dt.time(9, 30), close=dt.time(15, 30), )
However i am getting another error in this file
[Running] python -u "c:\Nikhil Media\Education & Skills\Stratergies_Codes\930_stratergies.py" Traceback (most recent call last): File "c:\Nikhil Media\Education & Skills\Stratergies_Codes\930_stratergies.py", line 148, in <module> strategies=cerebro.run() File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\cerebro.py", line 1127, in run runstrat = self.runstrategies(iterstrat) File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\cerebro.py", line 1298, in runstrategies self._runnext(runstrats) File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\cerebro.py", line 1542, in _runnext drets.append(d.next(ticks=False)) File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\feed.py", line 407, in next ret = self.load() File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\feed.py", line 523, in load retff = ff(self, *fargs, **fkwargs) File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\resamplerfilter.py", line 518, in __call__ onedge, docheckover = self._dataonedge(data) # for subdays File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\resamplerfilter.py", line 338, in _dataonedge if self._eoscheck(data, exact=True): File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\resamplerfilter.py", line 188, in _eoscheck self._eosset() File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\resamplerfilter.py", line 183, in _eosset self._nexteos, self._nextdteos = self.data._getnexteos() File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\feed.py", line 232, in _getnexteos _, nexteos = self._calendar.schedule(dtime, self._tz) File "C:\Users\Tejas\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\tradingcal.py", line 186, in schedule day += ONEDAY OverflowError: date value out of range [Done] exited with code=1 in 213.538 seconds
can you help me understand why i am getting this error ?? and also sugest a fix
-
Based on your posts:
- backtest period is 01/01/2019 to 12/31/2019
- trading calendar is set for 2018
You may want to align these two items.
-
Thanks again @ab_trader . I aligned the values as pointed by you . I get an chart plot . However i still have the issue where time increments are not proper . Despite me giving the start time and end time as 9 30 and 15 30 IST . The time in the graph starts from 10 : 00 and ends at 23 : 59 00.
Am i doing something else incorectly ?
-
Will sharing my trading data set Help ??