Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Only Trading One Stock

Hi everyone, everytime I backtest my algo whether I manually reference multiple securities or I use the set universe function and I look at the Transaction details, I see that my algorithm is only trading one stock. How can I fix this? here is the algorithm.

import numpy as np  
from scipy import stats

def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(98, 100))  
    set_symbol_lookup_date('2015-7-12')  
    context.dev_multiplier = 1.75  
    context.max_notional = 1000000  
    context.min_notional = -1000000  
def handle_data(context, data):  
    notional = context.portfolio.portfolio_value  
    dev_mult = context.dev_multiplier  
    for stock in data.keys():  
        current_price = data[stock].price  
        cash = context.portfolio.cash  
        average_band = data[stock].mavg(16)  
        std = data[stock].stddev(16)  
        standard_deviation = std*dev_mult  
        buy_long_band = average_band - standard_deviation  
        long_stop_band = buy_long_band - (buy_long_band*.035)  
        short_band = average_band + standard_deviation  
        short_stop_band = short_band + (.03*short_band)  
        number_of_shares = (cash/10)/current_price  


        if current_price <= buy_long_band  and cash >                       number_of_shares and notional < context.max_notional:  
            order(stock, +number_of_shares)  
            log.debug("Buying long" + str(stock))  
        elif current_price >= average_band:  
             order_target(stock, 0)  
             log.debug("Selling long" + str(stock))  
        if current_price <  long_stop_band:  
             order_target(stock, 0)  
             log.debug("Lost too much money, stopping position in" + str(stock))  
        if current_price >= short_band and notional >                     context.min_notional:  
           order_target_percent(stock, -0.1)  
           log.debug("Short selling" + str(stock))  
        elif current_price <= average_band:  
             order_target_percent(stock, +0.1)  
             log.debug("Buying back" +str(stock))  
        elif current_price >= short_stop_band:  
             order_target_percent(stock, +0.1)  
             log.debug("Lost too much money, stopping position in" + str(stock))  
        return  
3 responses

Try something like this


def initialize(context):  
    # create the universe of securities  
    context.stocks = symbols('F','BAC','XOM')

    ### your code here ###

def handle_data(context, data):

    for security in context.stocks:

    ### your code here ###

It now works like it should! Thanks for the help!

Remove the return statement at the end of the for loop.