Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Build Error: 47 Error Runtime exception: ValueError: cannot convert float NaN to integer

In the following code I always get the error when I try to run it with the full security universe (as the code shows), but when I run it and give a fixed value for XLF (toggle the commenting on the last three lines of code), I get valid data (no NaN data) for all the desired positions for the whole period through the info log. Any idea what the issue is?

from pandas import rolling_std

def initialize(context):

    context.secs = [ symbol('XLY'),  # XLY Consumer Discrectionary SPDR Fund  
                     symbol('XLF'),  # XLF Financial SPDR Fund  
                     symbol('XLK'),  # XLK Technology SPDR Fund  
                     symbol('XLE'),  # XLE Energy SPDR Fund  
                     symbol('XLV'),  # XLV Health Care SPRD Fund  
                     symbol('XLI'),  # XLI Industrial SPDR Fund  
                     symbol('XLP'),  # XLP Consumer Staples SPDR Fund  
                     symbol('XLB'),  # XLB Materials SPDR Fund  
                     symbol('XLU') ] # XLU Utilities SPRD Fund

    context.dev_wins = [15,20,25,30,35]  
    context.reg_wins = [260]  
    context.scaling = 0.0225  
    context.maxdw = max(context.dev_wins)  
def handle_data(context, data):  
    returndata = history(bar_count=781, frequency='1d', field='price').pct_change().ix[1:]  
    desiredpositions = {}

    for security in context.secs:  
        rmse = {}  
        for rw in context.reg_wins:  
            rmse[rw] = rolling_std(returndata[security],rw)

        begin = -65

        signals = {(rw,dw):0.0 for rw in context.reg_wins for dw in context.dev_wins}

        for dt in returndata[security].index[begin:]:  
            for rw in context.reg_wins:  
                resids = returndata[security].ix[:dt].ix[-rw:].mean() - returndata[security].ix[:dt].ix[-context.maxdw:]  
                resids.index = list(range(context.maxdw))  
                stderr = rmse[rw][dt]  
                for dw in context.dev_wins:  
                    signals[(rw,dw)] = resids.ix[-dw:].sum()/stderr  
            desiredpositions[security] = sum(signals.values())/len(signals) * context.scaling

    log.info(desiredpositions.values())  
    for security in context.secs:  
        order_target_percent(security, desiredpositions[security]) #This is the line that provokes the error

    # order_target_percent(symbol('XLF'), 1.0)  
1 response

Hi Angelo,

What's happening is that when you run it for all the securities, there are some that may not have data reaching back the full 781 days. What history() does when it doesn't have data, is fill the missing dates with NaNs which is why you're currently getting the NaN error.

What I've done is test whether or not 'sum(signals.values())/len(signals) * context.scaling' is a NaN and convert it to 0 if it is

from pandas import rolling_std  
import numpy as np

def initialize(context):

    context.secs = [ symbol('XLY'),  # XLY Consumer Discrectionary SPDR Fund  
                     symbol('XLF'),  # XLF Financial SPDR Fund  
                     symbol('XLK'),  # XLK Technology SPDR Fund  
                     symbol('XLE'),  # XLE Energy SPDR Fund  
                     symbol('XLV'),  # XLV Health Care SPRD Fund  
                     symbol('XLI'),  # XLI Industrial SPDR Fund  
                     symbol('XLP'),  # XLP Consumer Staples SPDR Fund  
                     symbol('XLB'),  # XLB Materials SPDR Fund  
                     symbol('XLU') ] # XLU Utilities SPRD Fund

    context.dev_wins = [15,20,25,30,35]  
    context.reg_wins = [260]  
    context.scaling = 0.0225  
    context.maxdw = max(context.dev_wins)  
def handle_data(context, data):  
    returndata = history(bar_count=781, frequency='1d', field='price').pct_change().ix[1:]  
    desiredpositions = {}

    for security in context.secs:  
        if security in data:  
            rmse = {}  
            for rw in context.reg_wins:  
                rmse[rw] = rolling_std(returndata[security],rw)

            begin = -65

            signals = {(rw,dw):0.0 for rw in context.reg_wins for dw in context.dev_wins}

            for dt in returndata[security].index[begin:]:  
                for rw in context.reg_wins:  
                    resids = returndata[security].ix[:dt].ix[-rw:].mean() - returndata[security].ix[:dt].ix[-context.maxdw:]  
                    resids.index = list(range(context.maxdw))  
                    stderr = rmse[rw][dt]  
                    for dw in context.dev_wins:  
                        signals[(rw,dw)] = resids.ix[-dw:].sum()/stderr  
                desired = sum(signals.values())/len(signals) * context.scaling  
               #: Convert to 0 instead  
                if np.isfinite(desired) != True:  
                    desired = 0  
                desiredpositions[security] = desired

    log.info(desiredpositions.values())  
    for security in context.secs:  
        order_target_percent(security, desiredpositions[security]) #This is the line that provokes the error

    # order_target_percent(symbol('XLF'), 1.0)  

I hope that helps and let me know if you have any questions on that

Seong

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.