Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Newbie struggling with first algorithm, help very much appreciated!

Hi so I'm fairly new to Quantopian but I have been watching and reading to try and learn as much as possible about how to go about building an algorithm. My first algorithm I'm attempting to filter stocks to the top 1% of stocks by average dollar volume, and then deciding on whether to long or short these depending on pairs of moving averages. However something isn't working and I can't figure out what. Running a backtest I get no errors, but no orders are made. If anyone can spot my mistake I would be very thankful.
Thanks

1 response

Try this:

from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import AverageDollarVolume

def initialize(context):  
    pipe = Pipeline()  
    attach_pipeline(pipe, name='my_pipeline')  
    dollar_volume = AverageDollarVolume(window_length=30)  
    pipe.add(dollar_volume, 'dollar_volume')  
    high_dollar_volume = dollar_volume.percentile_between(99, 100)  
    pipe.set_screen(high_dollar_volume)  
    context.securities = None  
def before_trading_start(context, data):  
    results = pipeline_output('my_pipeline').index  
    context.pipeline_results = results  
    context.securities = results  

def handle_data(context,data):  
    cash = context.portfolio.cash  
    for s in context.securities:  
        context.price = data.current(s,'price')  
        number_of_positions_possible = int((cash/len(context.securities))/context.price)  
        ma1 = data[s].mavg(30)  
        ma2 = data[s].mavg(60)  
        if ma1>ma2 and sid not in context.portfolio.positions:  
            order(s, number_of_positions_possible)  
        elif ma1<ma2 and sid not in context.portfolio.positions:  
            order(s, -number_of_positions_possible)