Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
[Q] Having trouble selling with bollinger bands

I'm having some trouble with my bollinger band code
I am trying to add another factor such as RSI to the buy and sell, since it is currently selling many stocks

I think some of the logic is off

Here is my handle data code:

current_position = context.portfolio.positions[context.test].amount  
    price=data.current(context.test, 'price')  
    # Load historical data for the stocks  
    prices = data.history(context.test, 'price', 15, '1d')  
    upper, middle, lower = talib.BBANDS(  
        prices,  
        timeperiod=12, # using 12 because John Bollinger suggests using between 9-12 periods  
        # number of non-biased standard deviations from the mean  
        nbdevup=1,  
        nbdevdn=1,  
        # Moving average type: weighted moving average here  
        matype=1)  
    #needs to be adjusted  
    # If price is below the recent lower band and we have  
    # no long positions then invest the entire  
    # portfolio value into SPY  
    if price < lower[-1] and current_position >= 0 and data.can_trade(context.test):  
        order_target_percent(context.test, 1) #set position to buy 100%  
        log.info("buying %s" % price)  

    # If price is above the recent upper band and we have  
    # no short positions then invest the entire  
    # portfolio value to short SPY  
    #"""and current_position"""<= 0'  
    elif price >= upper[-1]: #and data.can_trade(context.test):  
        order_target_percent(context.test, -1) #change the position to short 100%  
        log.info("Selling %s" % price)  
    record(upper = upper[-1], #dispay upper band on chart  
           lower = lower[-1],  
           middle = middle[-1],  
           price = price,  
           )  

I think the sell function is working as I expected.
For some reason the algorithm is setup to spend all of the initial capital, even though the specifics for buying aren't met. For example, in the week of Jan 5, 2014: the upper band is at $22.96, and lower

I've been testing around with selling at the middle band instead of the upper band, because sometimes the price doesn't bounce back as much. I have also been testing around with shorting the stock. I'm currently testing all of the code with imax corp.

Thank you.