Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. azuric
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    A
    • Profile
    • Following 0
    • Followers 0
    • Topics 5
    • Posts 7
    • Best 0
    • Groups 0

    azuric

    @azuric

    0
    Reputation
    13
    Profile views
    7
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    azuric Unfollow Follow

    Latest posts made by azuric

    • error whilst executing through vscode

      Exception has occurred: ImportError
      cannot import name 'feeds'

      Hi I am getting this issue with backtrader. Its running on a server and works fine in jupyter but wehn i try to debug in vscode i get this error at line

      import backtrader as bt

      It should be pointed to the correct python library since everything else works fine!

      posted in General Code/Help
      A
      azuric
    • backtesting error from getvaluesize:
      ---------------------------------------------------------------------------
      ValueError                                Traceback (most recent call last)
      <ipython-input-414-3bfb3089a414> in <module>
           11 #cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='myTradesStats')
           12 #cerebro.broker.setcommission(commission=0.001)
      ---> 13 results = cerebro.run()
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/cerebro.py in run(self, **kwargs)
         1125             # let's skip process "spawning"
         1126             for iterstrat in iterstrats:
      -> 1127                 runstrat = self.runstrategies(iterstrat)
         1128                 self.runstrats.append(runstrat)
         1129                 if self._dooptimize:
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/cerebro.py in runstrategies(self, iterstrat, predata)
         1291                     self._runonce_old(runstrats)
         1292                 else:
      -> 1293                     self._runonce(runstrats)
         1294             else:
         1295                 if self.p.oldsync:
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/cerebro.py in _runonce(self, runstrats)
         1686                         return
         1687 
      -> 1688             self._brokernotify()
         1689             if self._event_stop:  # stop if requested
         1690                 return
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/cerebro.py in _brokernotify(self)
         1358         notification to the strategy
         1359         '''
      -> 1360         self._broker.next()
         1361         while True:
         1362             order = self._broker.get_notification()
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/brokers/bbroker.py in next(self)
         1219 
         1220             else:
      -> 1221                 self._try_exec(order)
         1222                 if order.alive():
         1223                     self.pending.append(order)
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/brokers/bbroker.py in _try_exec(self, order)
         1065 
         1066         if order.exectype == Order.Market:
      -> 1067             self._try_exec_market(order, popen, phigh, plow)
         1068 
         1069         elif order.exectype == Order.Close:
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/brokers/bbroker.py in _try_exec_market(self, order, popen, phigh, plow)
          875             p = self._slip_down(plow, exprice, doslip=self.p.slip_open)
          876 
      --> 877         self._execute(order, ago=0, price=p, dtcoc=dtcoc)
          878 
          879     def _try_exec_close(self, order, pclose):
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/brokers/bbroker.py in _execute(self, order, ago, price, cash, position, dtcoc)
          749             # Adjust to returned value for closed items & acquired opened items
          750             if self.p.shortcash:
      --> 751                 closedvalue = comminfo.getvaluesize(-closed, pprice_orig)
          752             else:
          753                 closedvalue = comminfo.getoperationcost(closed, pprice_orig)
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/comminfo.py in getvaluesize(self, size, price)
          210             return abs(size) * self.get_margin(price)
          211 
      --> 212         return size * price
          213 
          214     def getvalue(self, position, price):
      
      ValueError: cannot copy sequence with size 1047 to array axis with dimension 8954
      ![alt text](image url)
      

      Can anyone help with this?

      posted in General Code/Help
      A
      azuric
    • RE: Pandas datafeed and simple test strat return Order Canceled/Margin/Rejected

      Making my account extremely large did solve the issue.

      Alternatively I can divide close by 10**10

      Thanks

      posted in General Code/Help
      A
      azuric
    • Pandas datafeed and simple test strat return Order Canceled/Margin/Rejected

      hi,

      I receive this log resopnse:

      2019-06-25, Close, 5821658823529.41
      2019-06-25, Close, 5827325581395.35
      2019-06-25, Order Canceled/Margin/Rejected
      2019-06-25, Close, 5831271259418.73
      2019-06-25, Order Canceled/Margin/Rejected

      class CustomDataLoader(btfeeds.PandasData):
      
          lines = ('g_p',)
      
          params = (
              #('open', 'Open'),
              #('high', 'High'),
              #('low', 'Low'),
              #('close', 'Close'),
              #('volume', None),
              #('openinterest', None),
              ('g_prediction', -1),
          )
      
      class TestStrategy(bt.Strategy):
          
          def __init__(self):
              self.close = self.datas[0].close
              self.gp = self.datas[0].g_p
              self.order = None
              self.buyprice = None
          
          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 next(self):
              self.log('Close, %.2f' % self.close[0])
              
              if self.order:
                  return
              
              if self.gp == 0:
                  if self.position:
                      self.order = self.sell()
              
              if self.gp == 1:
                  #self.buy(stake = 1, exectype=Order.Market)
                  #print('%03d %f' % (len(self), self.data.l.close[0],))
                  self.order = self.buy()
                  
          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'   %(order.executed.price))
      
                      self.buyprice = order.executed.price
                      #self.buycomm = order.executed.comm
                  else:  # Sell
                      self.log('SELL EXECUTED, Price: %.2f'   %(order.executed.price))
                  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))
      
      
      cerebro = bt.Cerebro()
      data = CustomDataLoader(dataname= df5, plot=True)
      cerebro.addstrategy(TestStrategy)
      cerebro.adddata(data)
      cerebro.broker.setcash(100000.0)
      cerebro.addsizer(bt.sizers.FixedSize, stake=10)
      cerebro.broker.setcommission(commission=0.001)
      cerebro.run()
      cerebro.broker.getvalue()
      
              
      

      running on jupyter.

      I assume I am missing out on setting something but I have used the generic strat in the quickstart guide as an example

      posted in General Code/Help
      A
      azuric
    • cerebro.plot() function with jupyter returns ValueErrror

      Hi I am getting this backtrace when I try and plot withing jupyter.

      Any ideas?

      ---------------------------------------------------------------------------
      ValueError                                Traceback (most recent call last)
      <ipython-input-256-b2b5b6d55a52> in <module>
            6 cerebro.run()
            7 cerebro.broker.getvalue()
      ----> 8 cerebro.plot()
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/cerebro.py in plot(self, plotter, numfigs, iplot, start, end, width, height, dpi, tight, use, **kwargs)
          989                 rfig = plotter.plot(strat, figid=si * 100,
          990                                     numfigs=numfigs, iplot=iplot,
      --> 991                                     start=start, end=end, use=use)
          992                 # pfillers=pfillers2)
          993 
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/plot/plot.py in plot(self, strategy, figid, numfigs, iplot, start, end, **kwargs)
          218                         downinds=self.dplotsdown[ind])
          219 
      --> 220                 self.plotdata(data, self.dplotsover[data])
          221 
          222                 for ind in self.dplotsdown[data]:
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/plot/plot.py in plotdata(self, data, indicators)
          667         if self.pinf.sch.volume and voloverlay:
          668             volplot = self.plotvolume(
      --> 669                 data, opens, highs, lows, closes, volumes, vollabel)
          670             axvol = self.pinf.daxis[data.volume]
          671             ax = axvol.twinx()
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/backtrader/plot/plot.py in plotvolume(self, data, opens, highs, lows, closes, volumes, label)
          609 
          610                 volylim /= self.pinf.sch.volscaling
      --> 611                 ax.set_ylim(0, volylim, auto=True)
          612             else:
          613                 # plot a legend
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/matplotlib-3.2.1-py3.6-linux-x86_64.egg/matplotlib/axes/_base.py in set_ylim(self, bottom, top, emit, auto, ymin, ymax)
         3573         self._process_unit_info(ydata=(bottom, top))
         3574         bottom = self._validate_converted_limits(bottom, self.convert_yunits)
      -> 3575         top = self._validate_converted_limits(top, self.convert_yunits)
         3576 
         3577         if bottom is None or top is None:
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/matplotlib-3.2.1-py3.6-linux-x86_64.egg/matplotlib/axes/_base.py in _validate_converted_limits(self, limit, convert)
         3099             if (isinstance(converted_limit, Real)
         3100                     and not np.isfinite(converted_limit)):
      -> 3101                 raise ValueError("Axis limits cannot be NaN or Inf")
         3102             return converted_limit
         3103 
      
      ValueError: Axis limits cannot be NaN or Inf
      
      ---------------------------------------------------------------------------
      ValueError                                Traceback (most recent call last)
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
          339                 pass
          340             else:
      --> 341                 return printer(obj)
          342             # Finally look for special method names
          343             method = get_real_method(obj, self.print_method)
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
          246 
          247     if 'png' in formats:
      --> 248         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
          249     if 'retina' in formats or 'png2x' in formats:
          250         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
          130         FigureCanvasBase(fig)
          131 
      --> 132     fig.canvas.print_figure(bytes_io, **kw)
          133     data = bytes_io.getvalue()
          134     if fmt == 'svg':
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/matplotlib-3.2.1-py3.6-linux-x86_64.egg/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
         2103                     orientation=orientation,
         2104                     bbox_inches_restore=_bbox_inches_restore,
      -> 2105                     **kwargs)
         2106             finally:
         2107                 if bbox_inches and restore_bbox:
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/matplotlib-3.2.1-py3.6-linux-x86_64.egg/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, metadata, pil_kwargs, *args, **kwargs)
          512         }
          513 
      --> 514         FigureCanvasAgg.draw(self)
          515         if pil_kwargs is not None:
          516             from PIL import Image
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/matplotlib-3.2.1-py3.6-linux-x86_64.egg/matplotlib/backends/backend_agg.py in draw(self)
          386         Draw the figure using the renderer.
          387         """
      --> 388         self.renderer = self.get_renderer(cleared=True)
          389         # Acquire a lock on the shared font cache.
          390         with RendererAgg.lock, \
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/matplotlib-3.2.1-py3.6-linux-x86_64.egg/matplotlib/backends/backend_webagg_core.py in get_renderer(self, cleared)
          224         if need_new_renderer:
          225             self._renderer = backend_agg.RendererAgg(
      --> 226                 w, h, self.figure.dpi)
          227             self._last_renderer = backend_agg.RendererAgg(
          228                 w, h, self.figure.dpi)
      
      /data/NFS/akhil/python-env/lib64/python3.6/site-packages/matplotlib-3.2.1-py3.6-linux-x86_64.egg/matplotlib/backends/backend_agg.py in __init__(self, width, height, dpi)
           90         self.width = width
           91         self.height = height
      ---> 92         self._renderer = _RendererAgg(int(width), int(height), dpi)
           93         self._filter_renderers = []
           94 
      
      ValueError: Image size of 191472350x251 pixels is too large. It must be less than 2^16 in each direction.
      
      <Figure size 432x288 with 3 Axes>
      
      posted in General Code/Help
      A
      azuric
    • RE: Passing a dataframe with all indicator/signal precalculated

      Thanks guys that puts me on the right track.

      posted in General Code/Help
      A
      azuric
    • Passing a dataframe with all indicator/signal precalculated

      Hi,

      Looking to use use backtrader as a quick way of prototyping signals.

      If I have a data frame with mid price of closes and some (one for simplicity) signals, how do I pass them to backtrader. I assume

      I do not need to build a custom indicator and instantiate them to do this but in effect just pass the frame directly and iterate over it.

      posted in General Code/Help
      A
      azuric