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

Simple bidask.py example doesn't seemt work



  • Hi guys, I am new to BackTrader and I just installed to try out an example

    It waas the ./samples/data-bid-ask/bidask.py

    I tried to run it under python3.7 and it came with anaconda

    While the input is

    TIMESTAMP,BID,ASK
    02/03/2010 16:53:50,0.5346,0.5347
    02/03/2010 16:53:51,0.5343,0.5347
    02/03/2010 16:53:52,0.5543,0.5545
    02/03/2010 16:53:53,0.5342,0.5344
    02/03/2010 16:53:54,0.5245,0.5464
    02/03/2010 16:53:54,0.5460,0.5470
    02/03/2010 16:53:56,0.5824,0.5826
    02/03/2010 16:53:57,0.5371,0.5374
    02/03/2010 16:53:58,0.5793,0.5794
    02/03/2010 16:53:59,0.5684,0.5688
    
    

    Tried on my Linux and Mac
    The output seems to be

       1: 2010-02-03T23:59:59.999989 - Bid 0.5346 - 0.5347 Ask
       2: 2010-02-03T23:59:59.999989 - Bid 0.5343 - 0.5347 Ask
       3: 2010-02-03T23:59:59.999989 - Bid 0.5543 - 0.5545 Ask
       4: 2010-02-03T23:59:59.999989 - Bid 0.5342 - 0.5344 Ask
       5: 2010-02-03T23:59:59.999989 - Bid 0.5245 - 0.5464 Ask
       6: 2010-02-03T23:59:59.999989 - Bid 0.5460 - 0.5470 Ask
       7: 2010-02-03T23:59:59.999989 - Bid 0.5824 - 0.5826 Ask
       8: 2010-02-03T23:59:59.999989 - Bid 0.5371 - 0.5374 Ask
       9: 2010-02-03T23:59:59.999989 - Bid 0.5793 - 0.5794 Ask
      10: 2010-02-03T23:59:59.999989 - Bid 0.5684 - 0.5688 Ask
    

    This is on linux
    and

       1: 02/03/2010 23:59:59 - Bid 0.5346 - 0.5347 Ask
       2: 02/03/2010 23:59:59 - Bid 0.5343 - 0.5347 Ask
       3: 02/03/2010 23:59:59 - Bid 0.5543 - 0.5545 Ask
       4: 02/03/2010 23:59:59 - Bid 0.5342 - 0.5344 Ask
       5: 02/03/2010 23:59:59 - Bid 0.5245 - 0.5464 Ask
       6: 02/03/2010 23:59:59 - Bid 0.5460 - 0.5470 Ask
       7: 02/03/2010 23:59:59 - Bid 0.5824 - 0.5826 Ask
       8: 02/03/2010 23:59:59 - Bid 0.5371 - 0.5374 Ask
       9: 02/03/2010 23:59:59 - Bid 0.5793 - 0.5794 Ask
      10: 02/03/2010 23:59:59 - Bid 0.5684 - 0.5688 Ask
    

    Tihs is on my mac.

    I think the format difference doesn't matter. I would like to figure out why it differ from this article: https://www.backtrader.com/blog/posts/2016-03-08-escape-from-ohlc-land/escape-from-ohlc-land/

    Anyone knows what went wrong?



  • Please add in a full copy of your code. Thanks.



  • I am using the code from the repo (I believe this is the same code as in the article)
    https://github.com/mementum/backtrader/blob/master/samples/data-bid-ask/bidask.py

    #!/usr/bin/env python
    # -*- coding: utf-8; py-indent-offset:4 -*-
    ###############################################################################
    #
    # Copyright (C) 2015-2020 Daniel Rodriguez
    #
    # This program is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.
    #
    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    # GNU General Public License for more details.
    #
    # You should have received a copy of the GNU General Public License
    # along with this program.  If not, see <http://www.gnu.org/licenses/>.
    #
    ###############################################################################
    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    import argparse
    
    import backtrader as bt
    import backtrader.feeds as btfeeds
    import backtrader.indicators as btind
    
    
    class BidAskCSV(btfeeds.GenericCSVData):
        linesoverride = True  # discard usual OHLC structure
        # datetime must be present and last
        lines = ('bid', 'ask', 'datetime')
        # datetime (always 1st) and then the desired order for
        params = (
            # (datetime, 0), # inherited from parent class
            ('bid', 1),  # default field pos 1
            ('ask', 2),  # default field pos 2
        )
    
    
    class St(bt.Strategy):
        params = (('sma', False), ('period', 3))
    
        def __init__(self):
            if self.p.sma:
                self.sma = btind.SMA(self.data, period=self.p.period)
    
        def next(self):
            dtstr = self.data.datetime.datetime().isoformat()
            txt = '%4d: %s - Bid %.4f - %.4f Ask' % (
                (len(self), dtstr, self.data.bid[0], self.data.ask[0]))
    
            if self.p.sma:
                txt += ' - SMA: %.4f' % self.sma[0]
            print(txt)
    
    
    def parse_args():
        parser = argparse.ArgumentParser(
            description='Bid/Ask Line Hierarchy',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        )
    
        parser.add_argument('--data', '-d', action='store',
                            required=False, default='../../datas/bidask.csv',
                            help='data to add to the system')
    
        parser.add_argument('--dtformat', '-dt',
                            required=False, default='%m/%d/%Y %H:%M:%S',
                            help='Format of datetime in input')
    
        parser.add_argument('--sma', '-s', action='store_true',
                            required=False,
                            help='Add an SMA to the mix')
    
        parser.add_argument('--period', '-p', action='store',
                            required=False, default=5, type=int,
                            help='Period for the sma')
    
        return parser.parse_args()
    
    
    def runstrategy():
        args = parse_args()
    
        cerebro = bt.Cerebro()  # Create a cerebro
    
        data = BidAskCSV(dataname=args.data, dtformat=args.dtformat)
        cerebro.adddata(data)  # Add the 1st data to cerebro
        # Add the strategy to cerebro
        cerebro.addstrategy(St, sma=args.sma, period=args.period)
        cerebro.run()
    
    
    if __name__ == '__main__':
        runstrategy()
    
    


  • I figured out the reason.

    I think the example is absolutely out-dated and I fortunately first went into this example. Thus the confusion.

    The catch here is that data should specify the timeframe now:
    data = BidAskCSV(dataname=args.data, dtformat=args.dtformat, timeframe=bt.TimeFrame.Ticks)

    because in csvgeneric.py
    If timeframe not specified, end of session time will be used

            if self.p.timeframe >= TimeFrame.Days:
                # check if the expected end of session is larger than parsed
                if self._tzinput:
                    dtin = self._tzinput.localize(dt)  # pytz compatible-ized
                else:
                    dtin = dt
    
                dtnum = date2num(dtin)  # utc'ize
    
                dteos = datetime.combine(dt.date(), self.p.sessionend)
                dteosnum = self.date2num(dteos)  # utc'ize
    
                if dteosnum > dtnum:
                    self.lines.datetime[0] = dteosnum
                else:
                    # Avoid reconversion if already converted dtin == dt
                    self.l.datetime[0] = date2num(dt) if self._tzinput else dtnum
            else:
                self.lines.datetime[0] = date2num(dt)
    
    

Log in to reply
 

});