For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

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
    

Log in to reply
 

});