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

Accessing last monday's value



  • I am trying to learn trading and using backtrader. I am trying to use a simple strategy which will look at close value on previous monday on each monday. My code below checks if current day is monday and if so, then prints last monday's close price. Thus, I just use dataclose[-5] to get previous monday's value (dataclose is line which stores close values). The issue with this approach is that if someday's data is missing, then this becomes incorrect. What is a better way to do this. I guess, we can save every monday's value in a variable which can be accessed later. Is there a better/alternative way?

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    #import datetime  # For datetime objects
    from datetime import datetime, timedelta
    import os.path  # To manage paths
    import sys  # To find out the script name (in argv[0])
    import pandas as pd
    import quandl
    import numpy as np
    import os
    
    
    # Import the backtrader platform
    import backtrader as bt
    import backtrader.feeds as btfeeds
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    %matplotlib inline
    
    def MakeArbitraryData(fromDate, ToDate):
        fromDateObj = datetime.strptime(fromDate,'%Y-%m-%d')
        toDateObj = datetime.strptime(toDate,'%Y-%m-%d')
        Delta = toDateObj - fromDateObj
        DateRange = [fromDateObj + timedelta(days=i) for i in range(Delta.days+1)] #create list of days
        WeekDays = [day.isoformat() for day in DateRange if day.isoweekday() not in [6,7]] # removing weekends
        nDays = len(WeekDays)
        A = np.random.randint(1,100,size=(nDays,4)) #create nDays X 4 matrix of random integers
        Apd = pd.DataFrame(data=A,columns=['Open','High','Close','Low'])
        Apd['Date']=pd.Series(WeekDays,dtype='datetime64[ns]')
        Apd = Apd.set_index('Date')
        return Apd
    
    
    class TestStrategy(bt.Strategy):
    
        def log(self, txt, dt=None):
            """logging function for this strategy
                this is essentially the print function for the strategy"""
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(),txt))
    
        def __init__(self):
            self.dataclose = self.datas[0].close
            # To keep track of pending orders
            self.order = None
    
        def next(self):
            if len(self) >= 7: #start processing only after 7 days, to make sure at least one monday exists
                #check if monday
                if self.datas[0].datetime.date().isoweekday() == 1:
                    print('self.dataclose[0] is %.2f' % self.dataclose[0])
                    print('self.dataclose[-5] is %.2f' % self.dataclose[-5])
                    print('self.datas[0].datetime.date(-5).isoformat() is %s' % self.datas[0].datetime.date(-5).isoformat())
                    print('self.datas[0].datetime.date(0).isoformat() is %s' % self.datas[0].datetime.date(0).isoformat())
                    print('\n')       
    
            if self.order:
                return
    
    
    cerebro = bt.Cerebro()
    cerebro.addstrategy(TestStrategy)
    fromDate = '2018-03-04'
    toDate = '2018-04-04'
    StockData = MakeArbitraryData(fromDate, toDate)
    data = bt.feeds.PandasData(dataname=StockData,
                                   # datetime='Date',
                                   nocase=True,
                                   )
    #add stock to cerebro
    cerebro.adddata(data)
    
    
    cerebro.broker.setcash(1000.0)
    
    #printing out starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
    #run over everything
    cerebro.run()
    
    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
    print(StockData)

  • administrators

    @dinesh-dileep-gaurav said in Accessing last monday's value:

    I guess, we can save every monday's value in a variable which can be accessed later. Is there a better/alternative way?

    That's the only way, because trading holidays (which sometimes happen in a row) render a fixed value of -5 useless.