Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Error: TimeoutException: Too much time spent in handle_data call

Hi everyone,

Whenever I try to backtest my algorithm in the minute mode I get this error

TypeError: Too much time spent in handle_data call.

Any help would be appreciated. Thanks!

import pandas

def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(95, 100))  
    context.size = (context.portfolio.cash / 10)  
    #context.shorts =  context.size * 0.5  
    #context.longs =  context.size * 0.5  
    context.shorts = []  
    context.shorting= True  
    #set_do_not_order_list(security_lists.leveraged_etf_list)  
    #schedule_function(logic,date_rules.every_day(),time_rules.market_open(hours=0, minutes=1))

def handle_data(context, data):  

    high = history(252, "1d", "high")  
    low = history(252, "1d", "low")  
    rolling_max = pandas.stats.moments.rolling_max(high,251)  
    rolling_min = pandas.stats.moments.rolling_min(low,251)  

    for s in data:  
        price = data[s].price  
        pmin = rolling_min[s][-2]  
        pmax = rolling_max[s][-2]  
        ma5 = data[s].mavg(14)  
        ma10 = data[s].mavg(30)  
        ma50 = data[s].mavg(100)  
        ma200 = data[s].mavg(200)    

        current_position = context.portfolio.positions[s].amount  
        price = data[s].price  
        if  (price > pmax) and (current_position == 0) and (ma10 > ma50) and (ma50 > ma200)  :  
             if not get_open_orders():  
                 order_target_value(s, context.size )  
                 log.info("LONG " + str(s.symbol))  

        elif (price < ma5) and (current_position != 0) and s not in context.shorts :  
            order_target_value(s, 0)  
            log.info("sell " + str(s.symbol))  

        if context.shorting:  
            if (price < pmin) and (current_position == 0) and (ma10 < ma50) and (ma50 < ma200) :  
               # if s not in context.fundamentals:  
                if not get_open_orders() :  
                    order_target_value(s, -context.size )  
                    context.shorts.append(s)  
                    log.info("short " + str(s.symbol))  
            elif (price > ma5) and (current_position != 0) and s in context.shorts :  
                order_target_value(s, 0)  
                log.info("recover " + str(s.symbol))  
                context.shorts.remove(s)  
    record('Leverage',context.account.leverage)  
4 responses

has anyone encountered the same situation ?

The .mavg() calculation is computationally slow and the most likely culprit for the timeout. You can use pandas' mean function instead to get the values:

prices_200 = history(200, '1d', 'price')   # gets the trailing 200 EOD prices for all stocks in algo  
prices_100 = prices_200[-100:]   # grab the last 100 prices  
prices_30 = prices_200[-30:]   # grab the last 30 prices  
prices_14= prices_200[-14:]   # grab the last 14 prices

for s in data:  
       price = data[s].price  
       pmin = rolling_min[s][-2]  
       pmax = rolling_max[s][-2]  
       ma14 = prices_14[s].mean()  
       ma30 = prices_30[s].mean()  
       ma100 = prices_100[s].mean()  
       ma200 = prices_200[s].mean()  

For more info on indexing into the dataframe, take a look at the pandas documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

As above. Also ...

Timing code for help with such things.

2015-02-02 timing:127 INFO Timing by highs descending:  
2015-02-02 timing:129 INFO avg 0.003677 lo 0.000431  hi 11.850341  mavg  
2015-02-02 timing:129 INFO avg 0.000080 lo 0.000053  hi 0.110973  other  
2015-02-02 timing:129 INFO avg 0.000252 lo 0.000213  hi 0.110847  roll2  
2015-02-02 timing:129 INFO avg 0.001168 lo 0.001112  hi 0.002116  roll1  

And something like DollarVolumeUniverse(99.8, 100) or symbols('TSLA', 'AAPL') will provide for a chance to at least run.

Thank you Alisa & garyha.

the algo works fine in the daily mode, but not in the minute mode. the minute mode uses too much leverage