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

Date and time handling in the __init()__

  • Hi @backtrader

    Could you please advice the way of date & time handling using __init()__. Say I have data feed and want to have the following indicator values along the history:

    from the data beginning to 2000/12/31 it should be 1.0
    after 2001/01/01 it should be 2.0

    I've developed an indicator using next(). It simply compares last data feed dates and dates shown, and set values accordingly . Is there a way to make the same thing in the __init()__? It seems to me that it might be faster.

  • administrators

    Comparison is implemented for datetime.time instances and lines, but not for datetime.datetime or, which forbids a clean implementation of that idea with something like:

    def __init__(self):
        self.lines.myline = 1 + ( >=, 1, 1))

    But there is something which can be done even if not so elegant

    def __init__(self):
        self.lines.myline = 1 + ( >= date2num(, 1, 1)))

    Instead of directly comparing with the instance, the comparison is done against the numeric value.

  • @backtrader Thank you!

    I've used bt.date2num() function for transformation. Also I've found out that you rewrote if operator which can be applied to lines. That helped me also.

  • administrators

    Edited the snippet from above to reflect that the correct usage is with date2num (obviously)

    Of course using the If from backtrader allows for much more complex scenarios. The 1 + boolean in the snippet was just meant to solve the hypothetical case presented above (1 until date x, 2 from that point onwards)

Log in to reply