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

Best approach to limit strategy to certain times of day?

  • I'd like to limit my strategy/backtesting not only to certain days of data, but also to certain times during those days, for example +/- 30 minutes of BOD and EOD.

    Can anyone recommend the best approach to this?

  • You might wish to try using this library DateTimeRange.

    from datetimerange import DateTimeRange

    Set the current date and time:

    # Current bar datetime, date, and time.
    dt =
    date =

    Set the regular trading hours (rth) as:

    # str HH:MM:SS

    Then use this code to set the trading time range:

     # Create Regular Trading Hours range for the current trading day.
            rth = DateTimeRange(
                    date, datetime.strptime(self.p.rth_start, "%H:%M:%S").time()
                    date, datetime.strptime(self.p.rth_end, "%H:%M:%S").time()

    Then check if the datetime is in regular trading hours. If so, then 'return'.

    # Only trade in regular trading hours and intraday bars.
            if dt not in rth and self.p.time_frequency != 'D':

  • You may also utilize the trading calendars:

        def in_session(data_feed, sos_delta=timedelta(), eos_delta=timedelta()):
            dt = data_feed.num2date(tz=timezone.utc, naive=False).replace(tzinfo=None)
            (sos, eos) = data_feed._calendar.schedule(datetime.combine(, time()))
            if eos_delta:
                eos -= delta
            if sos_delta:
                sos += delta
            return sos <= dt <= eos

  • Excellent, thanks, guys. Let me give these a go.

  • I ended up using a version of @run-out 's suggestion without the datetimerange, using two custom trade hour params with corresponding params in my strategy

    cth_start = datetime.datetime.strptime(args.cth_start, '%H:%M:%S').time()
    cth_end = datetime.datetime.strptime(args.cth_end, '%H:%M:%S').time()

    and then within my strategy simply:

    def next(self):
                if ( < self.p.cth_start) or ( > self.p.cth_end):

Log in to reply