Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Newbie dtformat

    General Code/Help
    2
    3
    64
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • tavagnascoi
      tavagnascoi last edited by

      Hello everybody,

      I'm a newbie and I can't solve the attached code issue.
      I think the problem is dtformat='%Y-%m-%d %H:%M:%S'.
      But I don't get over it.

      I take the opportunity to ask you if you know where to find various example codes for a neophyte?

      ======================================
      screen.jpg

      EURUSD_1_H_csv_parsed = bt.feeds.PandasData (dataname=EURUSD_1_H_csv,
      datetime=None,
      open=0,
      high=1,
      low=2,
      close=3,
      volume=None,
      openinterest=None,

                                             dtformat='%Y-%m-%d %H:%M:%S'
                                              )
      

      print(type(EURUSD_1_H_csv_parsed))

      cerebro = bt.Cerebro()

      cerebro.adddata(EURUSD_1_H_csv_parsed)

      cerebro.run()

      %matplotlib inline
      cerebro.plot(iplot=False)

      ========================================
      TypeError: PandasData.init() got an unexpected keyword argument 'dtformat'

      Many thanks

      Z 1 Reply Last reply Reply Quote 0
      • Z
        Z @tavagnascoi last edited by

        @tavagnascoi here is my code:

            data = btfeeds.GenericCSVData(
                dataname=file_path,
                nullvalue=0.0,
                dtformat=('%Y-%m-%d'),
                datetime=0,
                open=1,
                high=2,
                low=3,
                close=4,
                volume=5,
                openinterest=-1
           )
        

        Seems like you need to put the dtformat's value in parentheses? Let me know if that fixes it. I am a newbie as well.

        tavagnascoi 1 Reply Last reply Reply Quote 0
        • tavagnascoi
          tavagnascoi @Z last edited by

          @Z This is the solution I found:
          I apologize in advance for the long text!

          =================

          df1 = pd.read_csv(name_file)

          df1['time'] = pd.to_datetime(df1['time'])
          df1['time'] = df1['time'].dt.strftime('%Y-%m-%d %H:%M:%S')
          df1['time'] = pd.to_datetime(df1['time']) # Same code, in this way, work ?
          df1.set_index("time", inplace=True)

          =========================

          This code below works.
          Adding an indicator.

          =========================

          from future import (absolute_import, division, print_function,
          unicode_literals)

          import datetime # For datetime objects
          import os.path # To manage paths
          import sys # To find out the script name (in argv[0])

          # Import the backtrader platform

          import backtrader as bt

          # Create a Stratey

          class TestStrategy(bt.Strategy):
          params = (
          ('maperiod', 15),
          )

          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):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
          
              # To keep track of pending orders and buy price/commission
              self.order = None
              self.buyprice = None
              self.buycomm = None
          
              # Add a MovingAverageSimple indicator
              self.sma = bt.indicators.SimpleMovingAverage(
                  self.datas[0], period=self.params.maperiod)
          
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  return
          
              # Check if an order has been completed
              # Attention: broker could reject order if not enough cash
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log(
                          'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm))
          
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else:  # Sell
                      self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm))
          
                  self.bar_executed = len(self)
          
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
          
              self.order = None
          
          def notify_trade(self, trade):
              if not trade.isclosed:
                  return
          
              self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                       (trade.pnl, trade.pnlcomm))
          
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
          
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
          
              # Check if we are in the market
              if not self.position:
          
                  # Not yet ... we MIGHT BUY if ...
                  if self.dataclose[0] > self.sma[0]:
          
                      # BUY, BUY, BUY!!! (with all possible default parameters)
                      self.log('BUY CREATE, %.2f' % self.dataclose[0])
          
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.buy()
          
              else:
          
                  if self.dataclose[0] < self.sma[0]:
                      # SELL, SELL, SELL!!! (with all possible default parameters)
                      self.log('SELL CREATE, %.2f' % self.dataclose[0])
          
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.sell()
          

          if name == 'main':
          # Create a cerebro entity
          cerebro = bt.Cerebro()

          # Add a strategy
          cerebro.addstrategy(TestStrategy)
          
          
          data = bt.feeds.PandasData (dataname=df1, 
                                      datetime=None,
                                      open=0, 
                                      high=1, 
                                      low=2, 
                                      close=3, 
                                      volume=None, 
                                      openinterest=None,
                                      #dtformat= ('%Y-%m-%d %H:%M:%S')
                                      )
          
          
          
          # Add the Data Feed to Cerebro
          cerebro.adddata(data)
          
          # Set our desired cash start
          cerebro.broker.setcash(1000.0)
          
          # Add a FixedSize sizer according to the stake
          cerebro.addsizer(bt.sizers.FixedSize, stake=10)
          
          # Set the commission
          cerebro.broker.setcommission(commission=0.0)
          
          # Print out the 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())
          

          ###=======================
          This code below works.
          Let’s Optimize.
          ###=======================
          from future import (absolute_import, division, print_function,
          unicode_literals)

          import datetime # For datetime objects
          import os.path # To manage paths
          import sys # To find out the script name (in argv[0])

          # Import the backtrader platform

          import backtrader as bt

          # Create a Stratey

          class TestStrategy(bt.Strategy):
          params = (
          ('maperiod', 15),
          ('printlog', False),
          )

          def log(self, txt, dt=None, doprint=False):
              ''' Logging function fot this strategy'''
              if self.params.printlog or doprint:
                  dt = dt or self.datas[0].datetime.date(0)
                  print('%s, %s' % (dt.isoformat(), txt))
          
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
          
              # To keep track of pending orders and buy price/commission
              self.order = None
              self.buyprice = None
              self.buycomm = None
          
              # Add a MovingAverageSimple indicator
              self.sma = bt.indicators.SimpleMovingAverage(
                  self.datas[0], period=self.params.maperiod)
          
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  return
          
              # Check if an order has been completed
              # Attention: broker could reject order if not enough cash
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log(
                          'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm))
          
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else:  # Sell
                      self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm))
          
                  self.bar_executed = len(self)
          
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
          
              # Write down: no pending order
              self.order = None
          
          def notify_trade(self, trade):
              if not trade.isclosed:
                  return
          
              self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                       (trade.pnl, trade.pnlcomm))
          
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
          
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
          
              # Check if we are in the market
              if not self.position:
          
                  # Not yet ... we MIGHT BUY if ...
                  if self.dataclose[0] > self.sma[0]:
          
                      # BUY, BUY, BUY!!! (with all possible default parameters)
                      self.log('BUY CREATE, %.2f' % self.dataclose[0])
          
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.buy()
          
              else:
          
                  if self.dataclose[0] < self.sma[0]:
                      # SELL, SELL, SELL!!! (with all possible default parameters)
                      self.log('SELL CREATE, %.2f' % self.dataclose[0])
          
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.sell()
          
          def stop(self):
              self.log('(MA Period %2d) Ending Value %.2f' %
                       (self.params.maperiod, self.broker.getvalue()), doprint=True)
          

          if name == 'main':
          # Create a cerebro entity
          cerebro = bt.Cerebro()

          # Add a strategy
          strats = cerebro.optstrategy(
              TestStrategy,
              maperiod=range(10, 31))
          
          
          data = bt.feeds.PandasData (dataname=df1, 
                                      datetime=None,
                                      open=0, 
                                      high=1, 
                                      low=2, 
                                      close=3, 
                                      volume=None, 
                                      openinterest=None,
                                      #dtformat= ('%Y-%m-%d %H:%M:%S')
                                      )
          
          
          # Add the Data Feed to Cerebro
          cerebro.adddata(data)
          
          # Set our desired cash start
          cerebro.broker.setcash(1000.0)
          
          # Add a FixedSize sizer according to the stake
          cerebro.addsizer(bt.sizers.FixedSize, stake=10)
          
          # Set the commission
          cerebro.broker.setcommission(commission=0.0)
          
          # Run over everything
          cerebro.run(maxcpus=1)
          

          ====================

          This code below DOESN'T WORK, and I don't understand where the error is !?!?!?
          Visual Inspection: Plotting ???

          ====================

          Error code:
          ValueError: Axis limits cannot be NaN or Inf

          ====================

          from future import (absolute_import, division, print_function,
          unicode_literals)

          import datetime # For datetime objects
          import os.path # To manage paths
          import sys # To find out the script name (in argv[0])

          # Import the backtrader platform

          import backtrader as bt

          # Create a Strategy

          class TestStrategy(bt.Strategy):
          params = (
          ('maperiod', 15),
          )

          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):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
          
              # To keep track of pending orders and buy price/commission
              self.order = None
              self.buyprice = None
              self.buycomm = None
          
              # Add a MovingAverageSimple indicator
              self.sma = bt.indicators.SimpleMovingAverage(
                  self.datas[0], period=self.params.maperiod)
          
              # Indicators for the plotting show
              bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
              bt.indicators.WeightedMovingAverage(self.datas[0], period=25,
                                                  subplot=True)
              bt.indicators.StochasticSlow(self.datas[0])
              bt.indicators.MACDHisto(self.datas[0])
              rsi = bt.indicators.RSI(self.datas[0])
              bt.indicators.SmoothedMovingAverage(rsi, period=10)
              bt.indicators.ATR(self.datas[0], plot=False)
          
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  return
          
              # Check if an order has been completed
              # Attention: broker could reject order if not enough cash
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log(
                          'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm))
          
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else:  # Sell
                      self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm))
          
                  self.bar_executed = len(self)
          
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
          
              # Write down: no pending order
              self.order = None
          
          def notify_trade(self, trade):
              if not trade.isclosed:
                  return
          
              self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                       (trade.pnl, trade.pnlcomm))
          
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
          
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
          
              # Check if we are in the market
              if not self.position:
          
                  # Not yet ... we MIGHT BUY if ...
                  if self.dataclose[0] > self.sma[0]:
          
                      # BUY, BUY, BUY!!! (with all possible default parameters)
                      self.log('BUY CREATE, %.2f' % self.dataclose[0])
          
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.buy()
          
              else:
          
                  if self.dataclose[0] < self.sma[0]:
                      # SELL, SELL, SELL!!! (with all possible default parameters)
                      self.log('SELL CREATE, %.2f' % self.dataclose[0])
          
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.sell()
          

          if name == 'main':
          # Create a cerebro entity
          cerebro = bt.Cerebro()

          # Add a strategy
          cerebro.addstrategy(TestStrategy)
          
          
          data = bt.feeds.PandasData (dataname=df1, 
                                      datetime=None,
                                      open=0, 
                                      high=1, 
                                      low=2, 
                                      close=3, 
                                      volume=None, 
                                      openinterest=None,
                                      #dtformat= ('%Y-%m-%d %H:%M:%S')
                                      )
          
          
          # Add the Data Feed to Cerebro
          cerebro.adddata(data)
          
          # Set our desired cash start
          cerebro.broker.setcash(1000.0)
          
          # Add a FixedSize sizer according to the stake
          cerebro.addsizer(bt.sizers.FixedSize, stake=10)
          
          # Set the commission
          cerebro.broker.setcommission(commission=0.0)
          
          # Print out the 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())
          
          # Plot the result
          cerebro.plot()
          
          1 Reply Last reply Reply Quote 0
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors