Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Bollinger Band Help

Hi,

I am new to the site, so apologies in advance if my questions are basic.

I have created an algorithm that identifies potential longs and shorts based on their last close price relative to a 2 STD deviation Bollinger band based on the past 20 prices. The algorithm will take a long position if the last price closed below the lower band, and the algorithm will take a short position if the last price closed above the upper band. The algorithm uses quantopian's pipeline feature to identify the long and shorts. Currently, the algorithm rebalances every week and closes any positions not in pipeline output at the start of the week.

Ideally, the algorithm will maintain the position until the price reverts to the 20 day MA (will build out detailed logic later). However, I cannot figure out how to create the appropriate code. The current code is below. def rebalance(context,data):

long_weight, short_weight = compute_weights(context)

for security in context.security_list:  
    if data.can_trade(security):  
        if security in context.long_secs.index:  
            order_target_percent(security, long_weight)  
        elif security in context.short_secs.index:  
            order_target_percent(security, short_weight)

for security in context.portfolio.positions:  
    if security not in context.security_set and data.can_trade(security):  
        order_target_percent(security, 0)    

# Log the long and short orders each week.  
log.info("This week's longs: "+", ".join([long_.symbol for long_ in context.long_secs.index]))  
log.info("This week's shorts: "  +", ".join([short_.symbol for short_ in context.short_secs.index]))

Can someone help? Thanks in advance!