Navigation

    Backtrader Community

    • Register
    • 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/

    Unable to feed my custom DataFrame to backtrader

    General Code/Help
    3
    3
    43
    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.
    • Ahmad Nazari
      Ahmad Nazari last edited by

      Hello, I have a custom Pandas DataFrame and I want to feed this data that has different column names to backtrader. For do this, I wrote my code according to documentation:

      from __future__ import (absolute_import, division, print_function, unicode_literals)
      import datetime
      import backtrader as bt
      
      
      # data class
      class PandasData(bt.feeds.DataBase):
         
          params = (
              ('datetime', None),
              ('open', -1),
              ('high', -1),
              ('low', -1),
              ('close', -1),
              ('Volume', -1),
              ('pos_side', -1),
              ('entry', -1),
              ('exit', -1),
              ('pos_result', -1),
              ('ema1', 15),
              ('ema2', 16),
              ('ema3', 17),
          )
      
      
      # Create a Stratey
      class TestStrategy(bt.Strategy):
      
          def log(self, txt, dt=None):
              ''' Logging function for 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
      
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
      
      
      
      if __name__ == '__main__':
          # Create a cerebro entity
          cerebro = bt.Cerebro()
      
          # Add a strategy
          cerebro.addstrategy(TestStrategy)
      
          # Create a Data Feed
          data_bt = PandasData(dataname=data)
      
          # represent the problem
          print('Len data:', len(data))
          print('Len data_bt:', len(data_bt))
      
          # Add the Data Feed to Cerebro
          cerebro.adddata(data_bt)
          
      
          # Set our desired cash start
          cerebro.broker.setcash(1000.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())
      

      but after running the above code, the length of the data_bt will be 0 and cerebro doesn't loop through the dataset to backtest the strategy and below is the output:

      719b7d63-4674-4f21-a256-7128aac10a47-image.png

      for better show my dataset these 2 images are the data.head() :

      1b69632f-1e36-48b2-8beb-ac83509dffa8-image.png
      f0565669-768e-4783-8e87-f13a8d7604aa-image.png

      and also data.dtypes:
      a75cc10b-6a27-43da-af94-51514f66da87-image.png

      I searched a lot and try various methods for feeding the data but couldn't solve this problem, please help me to solve it. @backtrader @ab_trader @vladisld
      Thank you!

      C 1 Reply Last reply Reply Quote 0
      • C
        CDubya @Ahmad Nazari last edited by

        @ahmad-nazari

        Hello, I stumbled across backtader after creating a whole lot of PYTHON UDF's for Excel with XLWINGS (awesome library btw)

        thinking I was spiffy, I thought I'd use my existing code to create a dataframe to pass to Cerebro and use the already calculated indicators at my disposal. I didn't get it to work. so I just "rebuilt" the indicators in BT's INIT

        i am really really new to BackTrader. thinking starting last friday.

        This guy seems to have done it. his trading logic was off, but I think he has done what you're trying to do. I think the key is to structure the data so that Cerebro "knows" where to look for the values it is trying to work with.

        https://community.backtrader.com/topic/5217/simple-macd-strategy-with-long-short-and-close

        Good Luck. this is an astounding package. considering I used to do all of this years ago in C and C++ before TALIB existed.

        1 Reply Last reply Reply Quote 0
        • K
          kareem88990 last edited by

          @cdubya said in Unable to feed my custom DataFrame to backtrader:

          Hello, I stumbled across backtader after creating a whole lot of PYTHON

          شركة نقل اثاث بالرياض
          شركة نقل عفش بجدة

          Hello, I stumbled across backtader after creating a whole lot of PYTHON

          1 Reply Last reply Reply Quote 0
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors