Backtrader Community

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

    Check Hold Period

    General Code/Help
    4
    5
    2066
    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.
    • C
      cwse last edited by

      Hi,

      How can I check how long a stock has been held for?

      I tried: len(self.broker.getposition(d)) however this doesn't appear to give the hold days...

      Thanks!

      1 Reply Last reply Reply Quote 0
      • RandyT
        RandyT last edited by

        @cwse I've done the following to accomplish this.

        In notify_trade()

        def notify_trade(self, trade):
            self.htrade = trade
        

        In next()

        self.maxdays = ((self.data0.datetime.datetime()
                         - self.htrade.open_datetime()).days) >= self.p.limitdays
        
        1 Reply Last reply Reply Quote 1
        • A
          ab_trader last edited by ab_trader

          I am using code snippet from examples:

          In notify_order():

          if order.status in [order.Completed, order.Margin]:
              self.bar_executed = len(self)
          

          In next():

          if self.position:
              pos_length = len(self) - self.bar_executed + 1
          
          • If my answer helped, hit reputation up arrow at lower right corner of the post.
          • Python Debugging With Pdb
          • New to python and bt - check this out
          1 Reply Last reply Reply Quote 0
          • B
            backtrader administrators last edited by

            Trade instances carries an attribute which can help:

            • baropen

            Which records the length of the data when opening happens from the point of view of the strategy (len(self.data))

            Checking the difference between trade.baropen and the current length of the data len(self.data) gives the holding period.

            1 Reply Last reply Reply Quote 1
            • C
              cwse last edited by

              Thanks everyone!

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