Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. backtrader
    3. Controversial
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    B
    • Profile
    • Following 0
    • Followers 67
    • Topics 182
    • Posts 3269
    • Best 599
    • Controversial 23
    • Groups 1

    Controversial posts made by backtrader

    • RE: optstrategy() and plotting

      OptReturn is a simplified return instance which mimics a strategy, to reduce the overhead of message passing from worker processes to the main process.

      See: Docs - Optimization Improvements

      Plotting has never been tested with optimization (not an expected use case)

      posted in General Code/Help
      B
      backtrader
    • Disqus Old Comments

      Old comments are available at: https://disqus.com/home/forum/backtrader/

      posted in Blog
      B
      backtrader
    • RE: Misunderstanding of the process: Order created but not executed at the same price

      From: https://community.backtrader.com/topic/1596/cheat_on_open-true-how-to-execute-the-order-on-another-price-than-the-next-open-price

      @viktor-w said in Cheat_on_open true: how to execute the order on another price than the next open price:

      For now my code looks like this:

      class TestStrategy(bt.Strategy):
          params = (
              ('maperiod', 60),
          )
          
          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
              self.data_cpa = self.datas[0].high
              self.data_cpb = self.datas[0].low
              
              
              self.order = None
              self.buyprice = None
              self.buycomm = None
              
              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, %.8f' % order.executed.price)
                  elif order.issell():
                      self.log('SELL EXECUTED, %.8f' % order.executed.price)
      
                  self.bar_executed = 0
      
              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 %.8f, NET %.f' %
                       (trade.pnl, trade.pnlcomm))
          
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.8f' % self.dataclose[0])
      
              if self.order:
                  return
      
              # Check if we are in the market
              if not self.position:
      
      
                  if self.dataclose[0] > self.sma[0]:
      
                      # BUY, BUY, BUY!!! (with all possible default parameters)
                      self.log('BUY CREATE, %.8f' % self.dataclose[0])
      
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.buy(price= self.dataclose[0])
      
                  
              else:
                  
                  if self.dataclose[0] < self.sma[0]:
                      # SELL, SELL, SELL!!! (with all possible default parameters)
                      self.log('SELL CREATE, %.8f' % self.dataclose[0])
      
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.sell(price= self.dataclose[0])
               
          
          
      
      if __name__ == '__main__':
          # Create a cerebro entity
          cerebro = bt.Cerebro(cheat_on_open=True)
      
          # Add a strategy
          cerebro.addstrategy(TestStrategy)
          
          # retrieve the csv file
          modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
          datapath = os.path.join(modpath, './datas/zrxeth_sample.txt')
      
          # Create a Data Feed
          data = bt.feeds.GenericCSVData(
          dataname = datapath,
      
          fromdate=datetime.datetime(2018, 9, 28),
          todate=datetime.datetime(2018, 12, 3),
      
          nullvalue=0.0,
      
          dtformat=('%Y-%m-%d %H:%M:%S'),
      
              datetime=0,
              high=1,
              low=2,
              open=3,
              close=4,
              volume=5,
              openinterest=-1
          )
          
          # Add the Data Feed to Cerebro
          cerebro.adddata(data)
      
          # Set our desired cash start
          cerebro.broker.setcash(100.0)
      
          # Print out the starting conditions
          print('Starting Portfolio Value: %.8f' % cerebro.broker.getvalue())
      
          # Run over everything
          cerebro.run()
      
          # Print out the final result
          print('Final Portfolio Value: %.8f' % cerebro.broker.getvalue())
      

      From my understanding of the library, when you use the parameter cheat_on_open=True, you can authorize the order the order to be executed directly and not the day after. However, the executed order takes as price the next open price, how is it possible to choose which price the order will apply? Thanks!

      posted in General Discussion
      B
      backtrader
    • RE: Simple buy-and-hold strategy

      @tw00000 said in Simple buy-and-hold strategy:

      My only guess is that either self.buy() or self.close() is not working as intended here.

      Sorry, but with a statement like that I don't really feel like writing a proper answer. Please have a look at your own code.

      posted in General Code/Help
      B
      backtrader
    • RE: Extending a Datafeed

      If If wrote this code

      import queue
      
      class MyQueue(queue.Queue):
      
          def __init__(self, **kwargs):
              print('doing something')
      

      Would you expect MyQueue to be inside the queue module?

      The same applies to something you define in your own script named Seasonals. It's not going to be inside bt.feeds (or backtrader.feeds without aliasing)

      posted in Indicators/Strategies/Analyzers
      B
      backtrader
    • RE: Misunderstanding of the process: Order created but not executed at the same price

      @viktor-w said in Misunderstanding of the process: Order created but not executed at the same price:

      I used the code Quickstart in the documentation but with my own data (which is on a minute basis)

      No you haven't. You are using something different. Your code

      @viktor-w said in Misunderstanding of the process: Order created but not executed at the same price:

                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.buy(price= self.dataclose[0])
      

      Code from: https://www.backtrader.com/docu/quickstart/quickstart.html#do-not-only-buy-but-sell

                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.buy()
      

      There is a clear obvious difference. When you code, small differences can mean a huge difference.

      @viktor-w said in Misunderstanding of the process: Order created but not executed at the same price:

      I would like now to understand why my orders are created but not executed at the same price and days later... thanks! I am really a beginner with the platform, so any help is more than welcome.

      The code is apparently producing logs in the console. Why don't you paste them and point out an example of what you think is wrong? This is a rhetorical question to point out, that if you think there is something wrong, we cannot know it, because there is no information as to what yo think is wrong.

      Furthermore, you only show the strategy, but believe me: the most obvious mistake you are making it's not in that part of the code. It is in the code you aren't showing.

      In any case let me point you to this:

      • Docs - Order Management and Execution

      and look at what a Market order is. Let me explain it here: it is an order for which YOU DON'T specify the price. The Market price is used. No, not the market price you currently see, but the one which you still haven't seen, i.e.: the next incoming price tick (if you use daily bars, that's already the next trading day)

      posted in General Discussion
      B
      backtrader
    • Canonical vs Non-Canonical Indicators
      • https://www.backtrader.com/blog/2019-07-08-canonical-or-not/canonical-or-not/
      • https://medium.com/@danjrod/canonical-vs-non-canonical-backtrader-8e17c23c69de
      posted in Blog
      B
      backtrader
    • RE: multiprocessing.pool.MaybeEncodingError

      @franklili said in multiprocessing.pool.MaybeEncodingError:

      multiprocessing.pool.MaybeEncodingError: Error sending result: '[<main.EmaMeanReversionStrategy object at 0x7f4ab7de6b38>]'. Reason: 'PicklingError("Can't pickle <class'main.EmaMeanReversionStrategy'>: it's not the same object as__main__.EmaMeanReversionStrategy")'

      This multiprocessing error has to do with scoping in Python, hence the ("it's not the same ...") It is a well-known pickling problem.

      My guess is that you have to take the core out of if __name___ ... and put it into a function of its own.

      posted in Indicators/Strategies/Analyzers
      B
      backtrader
    • RE: Multiple Datafeeds and multiple Timeframes

      @FaiqS said in Multiple Datafeeds and multiple Timeframes:

      Which is not convenient to iterate through in next function of strategy.

      It may not be convenient for you. Don't mix them in such a way then. Add first the lower timeframes and later the higher timeframes. You will have two clear partitions.

      Or iterate using steps other than 1 and with different starting indices.

      @FaiqS said in Multiple Datafeeds and multiple Timeframes:

      The straightforward it is referring to is to add "cerebro.adddata(data)"

      No. It is referring to resampledata(data, ...). Using any other approach won't change the order in which things are in the system and where.

      posted in General Discussion
      B
      backtrader
    • RE: Kalman et al.

      @RandyT There is no magic. The problem is that the initial values of the filter are orders of magnitude greater than the ones when the filter has settled.

      posted in Blog
      B
      backtrader
    • RE: sharpe ratio wrong?

      Question number 1:

      • Have you read the documentation? (Let me answer that one: No) (At least the part about the SharpeRatio analyzer)

      Question number 2:

      • What and in which form are you trying to calculate?

      Question number 3 (set of questions)

      • Don't you think that if you consider some results right and some wrong, you could provide those results for comparison?
      • A working snippet? Sample data?

      Question number 4:

      • Why 365 in your code? That's not what people use.
      posted in Indicators/Strategies/Analyzers
      B
      backtrader
    • RE: Pandas Dataframe issue (int object has no attribute to_pydatetime)

      @Suraj-Thorat said in Pandas Dataframe issue (int object has no attribute to_pydatetime):

      Anyone has got a solution to this?

      Yes. Read the documentation.

      The error is self-explaining.

      int object has no attribute to_pydatetime
      

      @Suraj-Thorat said in Pandas Dataframe issue (int object has no attribute to_pydatetime):

           datetime   open   high    low  close  volume
      0  2019-09-03  15.50  15.50  14.30  14.45     681
      1  2019-09-04  14.20  15.45  14.10  14.90    5120
      

      And you have an index which is made up of int values.

      @Suraj-Thorat said in Pandas Dataframe issue (int object has no attribute to_pydatetime):

      • EVEN IF I add this line to set index same error is given.

      Basic engineering principles:

      • You say you have done something
      • But you show code with something else
      • That means that for all intent and purposes you haven't done that.

      The PandasData has a dedicated documentation page, which shows the parameters available for the data feed, and the following is stated

      Link: Docs - PandasData - https://www.backtrader.com/docu/pandas-datafeed/pandas-datafeed/

      ...
          params = (
              # Possible values for datetime (must always be present)
              #  None : datetime is the "index" in the Pandas Dataframe
              #  -1 : autodetect position or case-wise equal name
              #  >= 0 : numeric index to the colum in the pandas dataframe
              #  string : column name (as index) in the pandas dataframe
              ('datetime', None),
      ...
      
      posted in General Code/Help
      B
      backtrader
    • RE: Anyone use backtrader to do live trading on Bitcoin exchange?

      You probably want to use a Store, rather than a fork (which had no good reason to be). Someone took the right approach extracting the code from the fork.

      • https://www.backtrader.com/recipes/storesbrokersdata/bt-ccxt-store/bt-ccxt-store.html
      posted in General Discussion
      B
      backtrader
    • RE: Multi timeframe indicator plotted twice and in wrong timeframe

      Use coupling: Docs - Mixing Timeframes in Indicators

      This functionality allows to calculate an indicator on a timeframe an automatically apply the indicator to another lower timeframe.

      posted in Indicators/Strategies/Analyzers
      B
      backtrader
    • RE: AttributeError: 'str' object has no attribute '_name' - The error is clear - but for the life of me I can't see why it's happening

      @ab_trader said in AttributeError: 'str' object has no attribute '_name' - The error is clear - but for the life of me I can't see why it's happening:

      I can attach the code if that would be helpful

      Everybody here can read other people minds, sure no script is needed.

      @east1992 said in AttributeError: 'str' object has no attribute '_name' - The error is clear - but for the life of me I can't see why it's happening:

      @ab_trader As you like

      I think @ab_trader was just trying a prank ...

      In any case ... let me wonder how you write such a script, yet miss the top of the forum

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

      Without the three backticks your code is basically rendered in a form which cannot be properly read.

      @east1992 said in AttributeError: 'str' object has no attribute '_name' - The error is clear - but for the life of me I can't see why it's happening:

        File "C:\ProgramData\Anaconda3\envs\finance\lib\site-packages\backtrader\broker.py", line 80, in getcommissioninfo
          if data._name in self.comminfo:
      AttributeError: 'str' object has no attribute '_name'
      

      The problem is clear: you have created a position for something which is a string and not a data feed. Hence data (which is a str) has no attribute _name

      From what one can read, it is unclear why you need to define a `get_data_by_name', given that a method to retrieve data feeds by name does already exist

      • Docs - Strategy - See getdatabyname

      But playing with the names is for sure the root of the problem.

      posted in General Code/Help
      B
      backtrader
    • RE: Multi timeframe indicator plotted twice and in wrong timeframe

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

      The current implementation of this indicator does not works: it has these two problems:

      Sorry, but it does work.

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

      • both the H1 and the D1 charts are shown. I only want the H1 chart.

      You have not told the system that you only want the H1 chart. It cannot be a problem. You have not configured things to work the way you want.

      See - Docs - Plotting and use plotinfo.plot=False for whatever you don't want plotted.

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

      • the indicator shows the right values in the D1 chart, but it is not plotted in the H1 chart

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

      data_h1 = bt.feeds.GenericCSVData(**{**csv_opts, **h1_opts})
      data_d1 = bt.feeds.GenericCSVData(**{**csv_opts, **d1_opts})
      

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

              self.levels = Levels(self.data1, period=self.p.period)
      

      Well, you load d1 as the second feed in the system (hence self.data1) and you apply the indicator to self.data1. It should be no surprise that the indicator plots on d1 and not on h1. It would be a surprise if it did otherwise.

      Again. See - Docs - Plotting and use plotinfo.plotmaster=YOUR_DESIRED_DATA to plot on your chosen target.

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

      See? No indicator in the H1 chart and a superfluous D1 chart.

      See above. There is nothing superfluous. You have to configure what you want and what you don't want and where you want it and where you don't want it.

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

      As you can see in the following code, at the top level I first load the H1 data and then the D1 data. . This should make H1 the default data source, right?

      No idea what you mean with "default data source". There is no such thing in backtrader. The only thing you have achieved is that h1 can be referred as self.data0 or self.datas[0] or self.data. This is described here: Docs - Strategy in the section Member Attributes

      @fino said in Multi timeframe indicator plotted twice and in the timeframe:

      Then, in the strategy, I set up the indicator to use self.data1. This should link its calculations to the D1 timeframe, shouldn't it?

      Yes. And that's why the indicator obviously plots on d1

      posted in Indicators/Strategies/Analyzers
      B
      backtrader
    • RE: Using data feed name and line name in Indicator

      Indicators can take anything as a data feed, including other indicators and temporary line buffers created out of (for example) arithmetic operations, which of course immediately forbids something like getdatabyname

      posted in General Code/Help
      B
      backtrader
    • RE: Is there a complete pdf version of the documentation of backtrader

      There isn't at the moment

      posted in General Discussion
      B
      backtrader
    • RE: Extending Datafeeds GenericCSV Attribute Error

      @michael172 said in Extending Datafeeds GenericCSV Attribute Error:

      AttributeError: module 'backtrader.feeds' has no attribute 'GenericCSV_PE'
      

      @michael172 said in Extending Datafeeds GenericCSV Attribute Error:

      if __name__ == '__main__':
           # Create a cerebro entity
           cerebro = bt.Cerebro()
       
       
           data = btfeeds.GenericCSV_PE(
       #    data = btfeeds.GenericCSVData(    
      

      @michael172 said in Extending Datafeeds GenericCSV Attribute Error:

       class GenericCSV_PE(GenericCSVData):
       
           # Add a 'pe' line to the inherited ones from the base class
           lines = ('pe_ttm',)
      

      This is something you define.

      The original answer does still apply

      @backtrader said in Extending Datafeeds GenericCSV Attribute Error:

      @Osofuego said in Extending Datafeeds GenericCSV Attribute Error:

      data = btfeeds.GenericCSVData(
      

      You are not using your own extended data feed.

      posted in Indicators/Strategies/Analyzers
      B
      backtrader
    • 1
    • 2
    • 1 / 2