Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. AliAskari
    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 3
    • Posts 8
    • Best 1
    • Groups 0

    AliAskari

    @AliAskari

    2
    Reputation
    369
    Profile views
    8
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    AliAskari Unfollow Follow

    Best posts made by AliAskari

    • RE: Beginner- the date data format Error

      I had a similar issue and couldn't find what was wrong for the life of me. Instead I used the following class and it worked like a charm

      class custom_csv(btfeed.GenericCSVData):
          params = (
              ('datetime', 0),
              ('time', -1),
              ('open', 1),
              ('high', 2),
              ('low', 3),
              ('close', 4),
              ('volume', 5),
              ('openinterest', -1),
              ('timeframe', bt.TimeFrame.Minutes),
              ('compression', 1),
          )
      

      and to actually use it you can do

      data = custom_csv(dataname='some_csvf_file')
      

      if you have found another solution for your problem please post it here so others can use it.

      posted in General Code/Help
      A
      AliAskari

    Latest posts made by AliAskari

    • How to save figures generated by cerebro.plot?

      I am running my tests on a headless server and mostly it's my CI that is running the tests. I would like to save the figures, figures generated by cerebro.plot(), but it seems the functionality has been deprecated.

      I have searched in the forums and it seems one way is to dump the cerebro instance to disk and then reload it later and save the plot manually. It's a really dirty solution for this problem specially considering that this was supported at some point in the development of the application.

      Is there any other way I could save the figures?

      Thanks

      posted in General Code/Help
      A
      AliAskari
    • How to modify header names in the csv output of WriterFile?

      By default the csv writer uses the indicator class name as the name of the header in the csv output, i.e.

      def __init__(self):
          self.fast_ma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.fast_ma)
          self.slow_ma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.slow_ma)
          self.fast_ma.csv = True
          self.slow_ma.csv = True
      

      in the csv file generated by

      cerebro.addwriter(bt.WriterFile, csv=True, out='some_file.csv')
      

      I am getting two columns with the same name SimpleMovingAverage. The same thing is valid for the plot but there is an extra plotname parameter that can be used to change the name of an indicator in plots

      self.fast_ma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.fast_ma, plotname='fast_ma')
      

      but this parameter doesn't modify the header name in the csv file.

      I looked in the code and there doesn't seem to be a method to do so. Is this supported?

      Thanks!

      posted in General Code/Help
      A
      AliAskari
    • RE: Confused with pnlcomm and pnl

      Thanks for your time, it's now working as expected.

      posted in General Code/Help
      A
      AliAskari
    • RE: Confused with pnlcomm and pnl

      I see. Makes sense. Thanks!

      So if I want to capture the real buy/sell prices, along with other metrics, I'm better off writing my own logger and dump the log into a csv file.

      posted in General Code/Help
      A
      AliAskari
    • RE: Confused with pnlcomm and pnl

      Thanks for your time @backtrader. I was not sure how to add csv file as there are a lot of columns. I have attached both the entire csv file and also a snapshot from the data around this particular trade.

      0_1525189002436_71adc4ea-e066-47a7-87da-550e93f2f849-image.png

      EDIT: edited to add the link to csv data file: https://www.dropbox.com/s/cpdbzf839kpx5mb/bitfinex_btc_price.csv?dl=0

      You also have this logging code, but the output of it (which for sure could help) is also not shown

      I modified the script to print more info and also used notify_order as suggested. Here is the output:

      Starting Portfolio Value: 1000.00 USD$
      Open trade #01 with size 0.0367 value 500.5144 price 13621.0000
      Close trade #01 with size -0.0367 value 500.5144 price 13569.0000
      Open trade #02 with size 0.0366 value 499.0812 price 13631.0000
      Close trade #02 with size -0.0366 value 499.0812 price 13548.0000
      

      I just realized that the price mentioned in the log does not match the buy/sell price in the csv file. The info pasted in the screenshot is from trade#2.

      i.e.

                  notify_order print log        csv 
      
      open        13621.0000              13400.9250
      close       13569.0000              13760.3550
      

      The only thing the screenshot shows is that the value decreases from the very first moment after your buy operation.

      I am not sure why you say the price decreases? By looking at the csv and the buy/sell columns it appears to me that the buy price is lower than the sell price.

      I am under the impression that those columns reflect the price at which the trade was completed. But apparently it is not the case.

      What am I missing here?

      Thanks!

      posted in General Code/Help
      A
      AliAskari
    • RE: Order execution price

      @tomasrollo I'm not super sure but according to the docs it seems to be the expected behavior:

      price: execution price Note: if no price is given and no pricelimite is given, the closing price at the time or order creation will be used as reference

      what you might want to do is to use the notify_trade() method and check trade.value.

      posted in General Discussion
      A
      AliAskari
    • RE: Beginner- the date data format Error

      I had a similar issue and couldn't find what was wrong for the life of me. Instead I used the following class and it worked like a charm

      class custom_csv(btfeed.GenericCSVData):
          params = (
              ('datetime', 0),
              ('time', -1),
              ('open', 1),
              ('high', 2),
              ('low', 3),
              ('close', 4),
              ('volume', 5),
              ('openinterest', -1),
              ('timeframe', bt.TimeFrame.Minutes),
              ('compression', 1),
          )
      

      and to actually use it you can do

      data = custom_csv(dataname='some_csvf_file')
      

      if you have found another solution for your problem please post it here so others can use it.

      posted in General Code/Help
      A
      AliAskari
    • Confused with pnlcomm and pnl

      I have just started working with backtrader and tried a simple strategy but I'm getting very weird results.

      I'm using the addwriter method to save the trade results to a csv file:

      cerebro.addwriter(bt.WriterFile, csv=True, out="trade_history.csv")
      

      and I'm also setting the commission to zero.

      This is part of the csv results

      0_1525004691472_eff42c45-5dc5-4373-bdd9-3061c6470795-image.png

      at the 85th iteration (don't know if it's the right term, correct me please) I buy ~500$ worth of BTC at a price of ~13400$, which means I have ~0.037 BTC which is then sold at ~13760. My calculations are telling me that after selling my cash balance should be more than what I had before entering the trade because the trade is clearly profitable but it is not the case and I'm in a 3$ loss! Could someone please explain what is going on?

      I have attached my script

      import backtrader as bt
      import backtrader.feeds as btfeed
      import numpy as np
      
      
      class custom_csv(btfeed.GenericCSVData):
          params = (
              ('datetime', 0),
              ('time', -1),
              ('open', 1),
              ('high', 2),
              ('low', 3),
              ('close', 4),
              ('volume', 5),
              ('openinterest', -1),
              ('timeframe', bt.TimeFrame.Minutes),
              ('compression', 1),
          )
      
      from datetime import datetime
      
      class ma_strat(bt.Strategy):
          params = (
              ('fast_ma', 12),
              ('slow_ma', 60),
          )
      
          def __init__(self):
              self.dataclose = self.datas[0].close
              self.volume = self.datas[0].volume
              self.latest_order = None
              self.first_run = True
              self.order_size = 0
              self.trade_number = 0
      
              self.fast_ma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.fast_ma)
              self.slow_ma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.slow_ma)
      
              self.fast_ma.csv = True
              self.slow_ma.csv = True
      
          def notify_order(self, order):
      
              if order.isbuy():
                  order_type = 'Buy'
              else:
                  order_type = 'Sell'
      
              if order.status == order.Completed:
                  self.latest_order = None
                  return
              elif order.status == order.Canceled:
                  print(order_type + ' order canceled')
                  self.latest_order = None
                  return
              elif order.status == order.Margin:
                  current_cash_balance = self.broker.get_cash()
                  print(order_type + ' order cancled due to margin Error')
                  print('Current balance: ' + str(current_cash_balance))
                  # Write down: no pending order
                  self.latest_order = None
                  return
              elif order.status == order.Rejected:
                  print(order_type + ' order rejected')
                  # Write down: no pending order
                  self.latest_order = None
                  return
      
      
      
          def notify_trade(self, trade):
      
              if trade.isopen:
                  self.trade_number += 1
                  print('Opening trade #%02d with size %.4f commision %.4f value %.2f price %.2f' %
                           (self.trade_number, trade.size, trade.commission, trade.value, trade.price))
              elif trade.isclosed:
                  print('Closing trade #%02d gross %.2f, net %.2f' %
                           (self.trade_number, trade.pnl, trade.pnlcomm))
      
          def next(self):
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.latest_order is not None:
                  return
      
              if not self.position:
                  if self.fast_ma[0] > self.slow_ma[0]:
                          current_cash_balance = self.broker.get_cash()
                          self.order_size = 0.5 * current_cash_balance / float(self.dataclose[0])
                          # place the buy order
                          self.latest_order = self.buy(size=self.order_size)
      
              else:
                  if self.fast_ma[0] < self.slow_ma[0]:
                          self.latest_order = self.sell(size=self.order_size)
      
      
      if __name__ == '__main__':
      
          # Create a cerebro entity
          cerebro = bt.Cerebro()
          cerebro.addwriter(bt.WriterFile, csv=True, out="trade_history.csv")
      
          csv_data_file =  'bitfinex_btc_price.csv'
          bitfinex_minut_data = custom_csv(dataname=csv_data_file)
      
          # Add the Data Feed to Cerebro
          unknown = cerebro.adddata(bitfinex_minut_data)
      
          cerebro.addstrategy(ma_strat)
      
          cerebro.broker.setcash(1000.0)
      
          print('Starting Portfolio Value: %.2f USD$' % cerebro.broker.getvalue())
      
          cerebro.run()
      
          print('Final Portfolio Value: %.2f USD$' % cerebro.broker.getvalue())
      
      posted in General Code/Help
      A
      AliAskari