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

Hi everyone. I am newbie on quantopian and python as well. I need help on an issue. I want to filter all the stocks on SP500 due to the bollinger bands(20,2) to filter the stocks accrosing the middle band of bollinger. Is it possible to do on quantopian? Thanks in advance.

2 responses

Shebat,

As middle line of bollinger bands is moving average you may use or modify existing price - moving average crossover strategy like this:

from quantopian.algorithm import (attach_pipeline, pipeline_output, order_optimal_portfolio,)  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data.builtin import USEquityPricing  
import quantopian.pipeline.filters as Filters  
import quantopian.pipeline.factors as Factors  
import quantopian.optimize as opt  
# -------------------------------------------  
STK_SET, MA, LEV = Filters.Q500US(), 126, 1.0  
# -------------------------------------------  
def initialize(context):  
    schedule_function(trade,date_rules.month_start(),time_rules.market_open(minutes = 65))  
    attach_pipeline(make_pipeline(), 'pipeline')

def make_pipeline():  
    middle  = Factors.SimpleMovingAverage(inputs = [USEquityPricing.close], window_length = MA, mask = STK_SET)  
    price   = USEquityPricing.close.latest

    volume  = USEquityPricing.volume.latest  
    avg_vol = Factors.SimpleMovingAverage(inputs = [USEquityPricing.volume], window_length = 5, mask = STK_SET)    

    pipe    = Pipeline(screen = STK_SET & (price > middle) & (volume > avg_vol))  
    return pipe

def trade(context, data):  
    securities = pipeline_output('pipeline').index  
    weights = {}  
    for sec in context.portfolio.positions: weights[sec] = LEV/500 if sec in securities else 0  
    for sec in securities: weights[sec] = LEV/500 if sec in securities else 0 

    order_optimal_portfolio(opt.TargetWeights(weights), [opt.MaxGrossExposure(LEV)])  
    record(leverage = context.account.leverage)  

Vladimir,

Great help, thanks a lot for your attention.

Shebat.