Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. J. Javier Gálvez
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    J
    • Profile
    • Following 0
    • Followers 0
    • Topics 9
    • Posts 24
    • Best 1
    • Controversial 0
    • Groups 0

    J. Javier Gálvez

    @J. Javier Gálvez

    1
    Reputation
    672
    Profile views
    24
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    J. Javier Gálvez Unfollow Follow

    Best posts made by J. Javier Gálvez

    • RE: For IB, now there is TWS API, is IBPy still valid?

      Agree with you @backtrader... If it ain't broke, don't fix it

      posted in General Discussion
      J
      J. Javier Gálvez

    Latest posts made by J. Javier Gálvez

    • RE: Leverage analysis with Pyfolio

      @ab_trader Ok. Thank you. Let me read it.

      posted in Indicators/Strategies/Analyzers
      J
      J. Javier Gálvez
    • RE: Leverage analysis with Pyfolio

      @ab_trader Please, if any further info is needed, don't hesitate to ask. Thanks again.

      posted in Indicators/Strategies/Analyzers
      J
      J. Javier Gálvez
    • RE: Leverage analysis with Pyfolio

      Thanks for your response. I apologize for not provide enough info.

      ADSK is the Autodesk stock symbol and I'm testing trading with the other two stocks: FB (Facebook) and AAPL (Apple). gross_lev is one of the outputs of the PyFolio Analyzer and it is a series with the amount of leverage that your strategy use.

      Following your suggestion, this is the result:

      • In bt using 4x leverage:
        • With a long position:
          long.png
        • With a short position:
          short.png
          and this is the code in the next() :
      def next(self):
         self.log('val:${:.2f}, cash:${:.2f}'.format(self.broker.getvalue(), self.broker.getcash())
      
         if self.send_order_flag:
             # self.buy(data=self.datas[1], size=200)
             self.sell(data=self.datas[1], size=200)
             self.send_order_flag = False
      
      • In ib:
        • Before open any position (buying power of ~4x):
          IB_none.png
        • With a long position:
          IB_long.png
        • With a short position:
          IB_short.png

      In the short scenario, bt behave as I expected. But in the long case, I expected, that as I buy more than the cash I had, the cash should be negative as a representation of the debt. As it is the behavior in ib.

      The "calcs" I made before comes from reading the PyFolio analyzer results in a jupyter notebook. Here are the jupyters for:

      • Long position:
        long_jupyter.png
      • Short position:
        short_jupyter.png

      This is how I saved the PyFolio analyzer results in backtrader

      results = cerebro.run()
      strat = results[0]
      pyfoliozer = strat.analyzers.getbyname('pyfolio')
      returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
      
      if not os.path.exists('out/'):
          os.makedirs('out/')
      
      filepath = 'out/BTesting_results.pkl'
      file = open(filepath, 'wb')
      pikle_dict = {
          'returns': returns,
          'positions': positions,
          'transactions': transactions,
          'gross_lev': gross_lev,
      }
      dump(pikle_dict, file)
      
      posted in Indicators/Strategies/Analyzers
      J
      J. Javier Gálvez
    • Leverage analysis with Pyfolio

      Hello, Backtraders!

      A few days ago I'm started to play with leverage in backtrader in order to use it in Interactive Brokers (IB). In particular to trade stocks.

      In my understanding, leverage in IB, it is a little different from other platforms (based on some blogs reading). What I mean by this, in simple words, is that you can consider that you are using leverage if you buy more than the cash you have (I know that some conditions need to be met, like initial margin, maintenance margin among others). When you do that, you cash will be negative, because you have "debt".
      In other platforms, and it seems the case of backtrader, when you buy with leverage, you will never have negative cash.

      Until now, that behavior of backtrader was not a problem, the returns of the strategy seem to be ok. It was until I processed the results with Pyfolio that I realized that it leads to confusion in the Pyfolio analysis.

      Here is a screenshot of the first position a strategy took with leverage of 4x:

      Screenshot from 2020-06-05 13-44-31.png

      In some operations with pyfolio, it considers the sum of each row as the portfolio value. And that it is incorrect here.

      Although it could be a desition design, another output from backtrader is also incorrect. The gross leverage is erroneous:

      Screenshot from 2020-06-05 13-51-58.png

      It never reports a value greater than 1.

      It could be a bug or a decision design or that pyfolio has changed since the last commit about pyfolio analyzer of backtrader. But I ask this community to provide any help on how to fix it. Any insight is welcome :)

      --
      Regards,
      Javier

      posted in Indicators/Strategies/Analyzers pyfolio leverage interactive analyzer
      J
      J. Javier Gálvez
    • On-close orders

      Hi, Backtraders!

      I want to test an intraday strategy that involves close positions at the close of each day. Interactive brokers have a type of order to achieve this: Market-on-Close (MOC) Orders. Reading the documentation of backtrader it seems that it doesn't have this feature in backtest mode.

      From a point o view, it will not consider appropriate to ask a question while rising a solution because it could induce bias but I will make an exception looking for feedback of my approach in case no other possible solution arrives:

      To achieve this kind of behavior I thought to modify my data feed to include two additional bars after the last bar of the day (16:00:00). One will be at 16:00:01 to create a market order and the other one will be at 16:00:02 to execute the order. Both will have in the OHLC data the close price of the 16:00:00 bar.

      I'm not simply close my positions at 15:49:00 (supposing minute bars) in order to be executed at 16:00 because I'm not using time bars. So, I have uncertainty about at what time it will be the previous bar to the close of the day.

      Could you think in another way to incorporate (or simulate) on-close orders in backtesting with backtrader? Or could you share an inconvenience that you see in my approach?

      Cheers!

      posted in General Discussion orders interactive intraday
      J
      J. Javier Gálvez
    • RE: Does bracket orders check the low price but execute at close prices?

      @backtrader Thanks for your response. I apologize for not making a clear question. But the link you provide solve my doubts about how backtrader executes orders. Very interesting mechanism.

      Greetings.

      posted in General Code/Help
      J
      J. Javier Gálvez
    • Does bracket orders check the low price but execute at close prices?

      Hi, Backtraders.

      I have a doubt in regards to how backtrader operates bracket orders (and perhaps limit and stop orders too). For instance, in a long position, the upper bracket will check if the low price of the current bar is greater than or equal to the value and then close the position at close price for that bar. Is this the way backtrader works?

      Greetings.

      posted in General Code/Help orders brackets limit orders
      J
      J. Javier Gálvez
    • RE: For IB, now there is TWS API, is IBPy still valid?

      Agree with you @backtrader... If it ain't broke, don't fix it

      posted in General Discussion
      J
      J. Javier Gálvez
    • Interactive Brokers Sub Accounts

      When I open the TWS I'm able to choose what sub account I want to operate. The problem is that I can not find a way to connect Backtrader to a specific one.

      Does Backtrader have this feature? If it doesn't, any clue how it could be added?

      posted in General Discussion live trading tws ib broker
      J
      J. Javier Gálvez
    • RE: Exception in line series length at paper trading

      Hi, @backtrader and Bactraders!

      I tried the second option but it didn't go as expected. I read the documentation and review every post about the backfill_from and tried several things from there without success.

      The issue is that the timestamp I get from the data when the next() is called jump from 12:00 to 5:00 of the other day instead of continue to 12:01 and so on until 16:00 and then 9:30 of the next day. Here an extract of my prints:

      2018-10-01T11:56:00
      2018-10-01T11:57:00
      2018-10-01T11:58:00
      2018-10-01T11:59:00
      2018-10-01T12:00:00
      2018-10-02T05:31:00
      2018-10-02T05:32:00
      2018-10-02T05:33:00
      2018-10-02T05:34:00
      2018-10-02T05:35:00
      2018-10-02T05:36:00
      2018-10-02T05:37:00
      

      I'm very sure that my local CSVs have data only between 9:30 and 16:00 hrs.

      Let me detail about my code. This is how I'm connecting to IB:

      cerebro = bt.Cerebro()
      store = bt.stores.IBStore(host='127.0.0.1',port=4002, clientId=36, reconnect=-1)
      

      My data is in minute bars and I'm reading it as follow:

      data0 = btfeed.GenericCSVData(
              dataname=file_path,
      
              fromdate=datetime.datetime(2018, 10, 1, 9, 30, 0),
              todate=datetime.datetime(2018, 12, 12, 9, 30, 0),
      
              timeframe=bt.TimeFrame.Minutes,
              compression=1,
      
              dtformat='%Y%m%d',
              tmformat='%H:%M:%S',
      
              datetime=0,
              time=1,
              open=3,
              high=4,
              low=5,
              close=6,
              volume=8,
              openinterest=-1,
      )
      

      Then, adding the data:

      contract = 'TWTR-STK-SMART-USD'
      data = store.getdata(dataname=contract, rtbar=True,
                                   timeframe=bt.TimeFrame.Ticks, historical=False,
                                   #todate=datetime.datetime.now(),
                                   fromdate=datetime.datetime(2018, 10, 1, 9, 30, 0),
                                   tz=pytz.timezone('US/Eastern'),
                                   backfill_from=data0,
                                   #sessionstart=datetime.time(9, 30, 0),
                                   #sessionend=datetime.time(16, 0, 0),
                                   )
      
      cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=1)
      

      Finally, I run cerebro as:

      cerebro.broker = store.getbroker()
      
      cerebro.addstrategy(TestStrategy)
      
      cerebro.run(exactbars=1, runonce=False)
      

      I have tried several combinations of parameters both, in store.getdata() and in btfeed.GenericCSVData() but none of them work. So, any help will be appreciated.

      Thanks in advance.

      posted in General Code/Help
      J
      J. Javier Gálvez