Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Testing Gap Fade Strategy on Multiple Stocks

Hi
I am new to Quantopian so sorry if this is very basic. I am trying to test a simple strategy on a large basket of stocks. If the stock gaps down x% buy after the open and sell on the close. I believe I have the code for one stock worked out but would like to test this using a large number of stocks (e.g stocks in S&P 500 or top 10% volume stocks etc) I tried using the set_universe function or even adding one more stock manually but I got the error
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I am not sure where to go from here. If someone could help me fix my code so that I works over a larger number of stocks too I would greatly appreciate it.

I also would want to divide my portfolio each day evenly between stocks that have gapped x%. If someone could help be with the position sizing part of my algorithm that would be great too.

Any suggestions on better ways to write this code would also be welcomed. I am new and piecing together what I can but would love to hear if there is a more efficient way to write it.

Thanks

Tim

3 responses

symbol() and symbols() work some magic in the background, converting the symbol or symbols to security objects and adding them to the universe. So there isn't actually a need to assign the result to anything, they wind up in data and you already had that loop in place. This switches over to symbols(), plural, so you can work with more than one, and you're already set up for that too. And then this adds a couple of other things that might help.

def initialize(context):  
    symbols('AAPL', 'TSLA')

    schedule_function(order_entry_function, date_rules.every_day(), time_rules.market_open(hours=0,minutes=1))  
    schedule_function(order_exit_function, date_rules.every_day(), time_rules.market_close(hours=0,minutes=1))

def order_entry_function(context, data):  
    for stock in data:  
        cash = context.portfolio.cash / len(data)  
        current_price = data[stock].close_price  
        yc = context.yc[stock].values.tolist()[0] # Unsure about these, check them  
        od = context.od[stock].values.tolist()[0] #   in the debugger for example.  
        gap_size = (od - yc) / yc

        if gap_size < -0.01:  
            number_of_shares = int(cash / current_price)

            order(stock, +number_of_shares)  
            log.info('Buying {} {}'.format(number_of_shares, stock.symbol))

def order_exit_function(context, data):  
    for stock in data:  
        cash = context.portfolio.cash  
        record(cash = cash)  
        current_price = data[stock].close_price  
        record(**{stock.symbol: current_price})  
        yc = context.yc[stock].values.tolist()[0]  
        od = context.od[stock].values.tolist()[0]  
        gap_size = (od - yc) / yc

        if gap_size < -0.01:  
            shrs = context.portfolio.positions[stock].amount  
            if shrs:  
                order_target(stock, 0)  
                log.info('Selling {} {}'.format(shrs, stock.symbol))

def handle_data(context, data):  
    # Only need to run history once per bar/frame  
    context.yc = history(2, "1d", 'close_price')  
    context.od = history(1, "1d", 'open_price')  

Thanks Gary
That helps so much! I appreciate it.

Tim

I have one more question. I'm trying to test this strategy on a number of stocks in a csv file. I've read as much about fetcher as I can but still can't these stocks to be included in my universe for the backtest. Any help with this would be greatly appreciated.

Thanks

Tim

def initialize(context):  
    #set_do_not_order_list(security_lists.leveraged_etf_list)  
    fetch_csv("https://dl.dropboxusercontent.com/s/q7i5k3453io9xlo/SPNQ_TickersQ.csv",universe_func=my_universe,date_column='Date',symbol='Ticker')  



    schedule_function(count_triggers_function, date_rules.every_day(), time_rules.market_open(hours=0,minutes=1))  
    schedule_function(order_entry_function, date_rules.every_day(), time_rules.market_open(hours=0,minutes=1))  
    schedule_function(order_exit_function, date_rules.every_day(), time_rules.market_close(hours=0,minutes=2))

def preview(df):  
    log.info(' %s ' % df.head())  
    return df  
def my_universe(context, fetcher_data):  
    my_stocks=set(fetcher_data[symbol])  

    return my_stocks  
def count_triggers_function(context,data):  
    triggers=0  
    for stock in data:  
        print stock  
        current_price = data[stock].close_price  
        yc = context.yc[stock].values.tolist()[0] # Unsure about these, check them  
        od = context.od[stock].values.tolist()[0] #   in the debugger for example.  
        gap_size = (od - yc) / yc

        if gap_size < -0.05:  
            triggers=triggers+1  
        elif gap_size>.05:  
            triggers=triggers+1  
    return triggers


def order_entry_function(context, data):  
    for stock in data:  
        current_price = data[stock].close_price  
        yc = context.yc[stock].values.tolist()[0] # Unsure about these, check them  
        od = context.od[stock].values.tolist()[0] #   in the debugger for example.  
        gap_size = (od - yc) / yc

        if gap_size <- 0.05:  
            print gap_size  
            triggers=count_triggers_function(context,data)  
            cash = (context.portfolio.cash / triggers)  
            print cash  
            number_of_shares = int((cash *.04)/(current_price-0.9*current_price))

            order(stock, +number_of_shares)  
            log.info('Buying {} {}'.format(number_of_shares, stock.symbol))  
            log.info(triggers)  
        elif gap_size>0.05:  
            print gap_size  
            triggers=count_triggers_function(context,data)  
            cash=context.portfolio.cash/triggers  
            number_of_shares = int((cash *.04)/(current_price-0.9*current_price))  
            order(stock,-number_of_shares)  
            log.info('Shorting {}{}'.format(number_of_shares,stock.symbol))  
            log.info(triggers)  



def order_exit_function(context, data):  
    for stock in data:  
        print stock  
        #record(cash = cash)  
        current_price = data[stock].close_price  
        #record(**{stock.symbol: current_price})  
        yc = context.yc[stock].values.tolist()[0]  
        od = context.od[stock].values.tolist()[0]  
        gap_size = (od - yc) / yc

        if gap_size <-0.05:  
            shrs = context.portfolio.positions[stock].amount  
            if shrs:  
                order_target(stock, 0)  
                log.info('Selling Longs{} {}'.format(shrs, stock.symbol))  
        elif gap_size>0.05:  
            shrs = context.portfolio.positions[stock].amount  
            if shrs:  
                order_target(stock, 0)  
                log.info('Buying to Cover{} {}'.format(shrs, stock.symbol))  


def handle_data(context, data):  
    # Only need to run history once per bar/frame  
    context.yc = history(2, "1d", 'close_price')  
    context.od = history(1, "1d", 'open_price')