Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Sell the position if the first day is red

My strategy buys stocks mostly at the market open. I found that if the stock close lower than the open on the buy day, I should not hold the position.
So I want to buy the position at market open, sell it if it is red before market close(may be 30 mins before market close) or in the next day market open. But I will hold it if it is green on the buying day.

Does anyone know how to do this? or can I know and store the buy day of that position?

2 responses

I have read the quantopian example and build below code. "context.hold[s]" is zero after buy. However, it disappears afterwards.
What is the problem??

def my_rebalance(context,data):  
    op = data.history(context.security_list,'open',2,'1d')  
    cl = data.history(context.security_list,'price',2,'1d')  
    for s in context.portfolio.positions:  
        op = data.history(s,'open',2,'1d')  
        cl = data.history(s,'price',2,'1d')  
        if context.hold.get(s) is not None:  
                print context.hold[s]  
                context.hold[s] += 1  
                if context.hold[s] == 1 and cl[-2] < op[-2]:  
                    order_target(s,0)  
                    del context.hold[s]  
                elif context.hold[s] > 1:  
                    del context.hold[s]  
    for s in context.security_list:  
      if context.vix <= context.vl:  
                #print s.symbol  
                context.security_listF[s] = s  
    MAX_LEVERAGE = calc_leverage(context.portfolio.cash)  
    context.pctx = diversify(context,data,context.security_listF,MAX_LEVERAGE)  
    if context.pctx == 0:  
        return  
    for s in context.security_listF:  
        cp = data.current(s,'price')  
        if s not in context.portfolio.positions and s not in get_open_orders():  
            #if context.portfolio.cash > 0:  
                if data.can_trade(s):  
                    #shares = context.portfolio.portfolio_value * context.pctx / cp  
                    order_target_percent(s,context.pctx,style=MarketOrder())  
                    if context.hold.get(s) is None:  
                        context.hold[s] = 0  

I finally solve it.