Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Exiting at the close of the next day

Dear All,

I am trying to find the relevant code in order to exit at the close of next day. Are there any examples i could look at?

Thank you,

Harry

2 responses

Hello Harry,

I whipped this together pretty quickly, but it seems to be working. Look it over, and let me know if it still needs work.

I should have time later today to add a bunch of comments, if they'd help.

Grant

from pytz import timezone  
from zipline.utils.tradingcalendar import get_early_closes

def initialize(context):  
    context.stocks =   [ sid(19662),  # XLY Consumer Discrectionary SPDR Fund  
                       sid(19656),  # XLF Financial SPDR Fund  
                       sid(19658),  # XLK Technology SPDR Fund  
                       sid(19655),  # XLE Energy SPDR Fund  
                       sid(19661),  # XLV Health Care SPRD Fund  
                       sid(19657),  # XLI Industrial SPDR Fund  
                       sid(19659),  # XLP Consumer Staples SPDR Fund  
                       sid(19654),  # XLB Materials SPDR Fund  
                       sid(19660) ] # XLU Utilities SPRD Fund  
    context.spy = sid(8554)  
    start_date = context.spy.security_start_date  
    end_date = context.spy.security_end_date  
    context.early_closes = get_early_closes(start_date,end_date).date  
    context.prior_day = None  
    context.day_count = -1  
def handle_data(context, data):  
    if context.prior_day != get_datetime().day:  
        context.prior_day = get_datetime().day  
        context.day_count += 1  
        if context.day_count % 2 == 0.0:  
            for stock in context.stocks:  
                order_target_percent(stock,1.0/len(context.stocks))  
    else:  
        context.prior_day = get_datetime().day  
        if context.day_count % 2 != 0.0:  
            if sell_EOD(context):  
                return  
        return  
def sell_EOD(context):

    date = get_datetime().date()  
    if date in context.early_closes:  
        close = 13 # early closing time  
    else:  
        close = 16 # normal closing time  
    loc_dt = get_datetime().astimezone(timezone('US/Eastern'))  
    if loc_dt.hour == close-1 and loc_dt.minute == 45:  
        pass  
    else:  
        return False  
    for stock in context.stocks:  
        order_target_percent(stock,0)  
    return True

That's great Grant, i will give it a try

Thank you so much.