Charles Witt's approach is the best. Don't go down the rabbit hole using 'if statements'. To run until the last hour then simply schedule functions as needed. While you could manually schedule them an easier approach is to use a loop. Maybe something like this..
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Set the start time and stop time (both in minutes)
# Here we are working backwards from market_close.
# To stop 1hr before market_close then set stop_time to 60
# There are typically 390 trading minutes in a day
# so set start_time to 390 if one wants to start at market open.
# Note that the schedule function ignores any pre-market schedules
# so this works fine for half days.
# Also set the frequency in minutes (in this case every 5 minutes)
# Frequency can be set to 1 to mimic the behavior of handle_data
start_time, stop_time, frequency = 390, 60, 5
for minutes_offset in range(stop_time, start_time, frequency):
schedule_function(
my_function,
date_rules.every_day(),
time_rules.market_close(minutes=minutes_offset),
half_days = True)
def my_function(context,data):
"""
Do any logic here. Will be executed each time it's scheduled
"""
log.info(get_datetime('US/Eastern').time())
See the attached algorithm to see this in action. Check the logs which show the times that the scheduled function was executed.Note the 11-25-2016 date in the logs. This was a half day and the algorithm ran as expected until 12:00 (since the market closed at 1:00).