Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
avoid NaNs w/ history API - most efficient approach?

Here's some code that will skip subsequent lines in handle_data by checking for NaNs in the data returned by the history API.

Is this the most efficient approach? Or perhaps there is a better way using pandas directly (rather than resorting to numpy)?

Cheers,

Grant

import numpy as np

def initialize(context):  
    context.stocks = []  
    set_universe(universe.DollarVolumeUniverse(20, 20.2))  
def handle_data(context, data):  
    context.stocks = [sid for sid in data]  
    context.p = history(30, '1d', 'price', ffill=False)  
    context.v = history(30, '1d', 'volume', ffill=False)  
    if (np.isnan(np.sum(context.p.as_matrix(context.stocks))) or  
        np.isnan(np.sum(context.v.as_matrix(context.stocks)))):  
        print 'NaN found'  
        return  
6 responses

You could also use

np.any(pandas.isnull(df))  

(generally no reason to always convert to a np.matrix, numpy can deal with pandas dataframes for the most part, otherwise use df.values).

It does seem a little extreme though, as you have to wait for the nans to be completely moved outside the window. With a long window I bet that condition is never true. Wouldn't dropping nans not be enough?

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.

Thanks Thomas,

Yes, I agree it is too extreme. For the OLMAR algorithm with the history API, I don't think that dropping the NaNs will work. I'll explain, when I get the chance.

Happy New Year!

Grant

Happy New Year, Grant :) (and to the rest of Quantopians!)

Thomas

Hi Grant,

I'm curious, are you seeing "leading" nans. (i.e. nans only at the front)
Or are the nans intermingled?

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.

Hello Eddie,

When I get the chance, I'll write a separate script to see if I can flag the apparent problem.

Grant

Hello Eddie,

The attached backtest resulted in some NaNs being reported. I haven't sorted out if they are only at the front.

Grant

import pandas as pd  
import numpy as np  
from pytz import timezone

def initialize(context):  
    context.stocks = [  
    sid(24),    # AAPL,  APPLE INC  
    sid(62),    # ABT,   ABBOTT LABORATORIES  
    sid(25555), # ACN,   ACCENTURE PLC  
    sid(161),   # AEP,   AMERICAN ELECTRIC POWER INC  
    sid(239),   # AIG,   AMERICAN INTL GROUP INC  
    sid(24838), # ALL,   ALLSTATE CORP (THE)  
    sid(368),   # AMGN,  AMGEN INC  
    sid(16841), # AMZN,  AMAZON.COM INC  
    sid(448),   # APA,   APACHE CORP  
    sid(455),   # APC,   ANADARKO PETROLEUM CORP  
    sid(679),   # AXP,   AMERICAN EXPRESS COMPANY  
    sid(698),   # BA,    BOEING CO  
    sid(700),   # BAC,   BANK OF AMERICA CORP  
    sid(734),   # BAX,   BAXTER INTERNATIONAL INC  
    sid(903),   # BK,    BANK OF NEW YORK MELLON CORP/T  
    sid(980),   # BMY,   BRISTOL MYERS SQUIBB COMPANY  
    sid(11100), # BRK.B, BERKSHIRE HATHWY INC(HLDG CO) B  
    sid(1335),  # C,     CITIGROUP  
    sid(1267),  # CAT,   CATERPILLAR INC  
    sid(1582),  # CL,    COLGATE-PALMOLIVE CO  
    sid(12160), # COF,   CAPITAL ONE FINANCIAL CORP  
    sid(23998), # COP,   CONOCOPHILLIPS  
    sid(1787),  # COST,  COSTCO WHOLESALE CORP  
    sid(1900),  # CSCO,  CISCO SYSTEMS INC  
    sid(1971),  # CTS,   CTS CORP  
    sid(4799),  # CVS,   CVS CAREMARK CORP  
    sid(23112), # CVX,   CHEVRON CORPORATION  
    sid(2119),  # DD,    DU PONT DE NEMOURS E I &CO  
    sid(25317), # DELL,  DELL INC  
    sid(2190),  # DIS,   WALT DISNEY CO-DISNEY COMMON  
    sid(2263),  # DOW,   DOW CHEMICAL CO  
    sid(2368),  # DVN,   DEVON ENERGY CORP (NEW)  
    sid(24819), # EBAY,  EBAY INC  
    sid(2518),  # EMC,   EMC CORPORATION  
    sid(2530),  # EMR,   EMERSON ELECTRIC CO  
    sid(22114), # EXC,   EXELON CORPORATION  
    sid(2673),  # F,     FORD MOTOR CO(NEW)  
    sid(13197), # FCX,   FREEPORT-MCMORAN COPPER&GOLD B  
    sid(2765),  # FDX,   FEDEX CORPORATION  
    sid(3136),  # GD,    GENERAL DYNAMICS CORP  
    sid(3149),  # GE,    GENERAL ELECTRIC CO  
    sid(3212),  # GILD,  GILEAD SCIENCES INC  
    sid(20088), # GS,    GOLDMAN SACHS GROUP INC  
    sid(3443),  # HAL,   HALLIBURTON CO (HOLDING CO)  
    sid(3496),  # HD,    HOME DEPOT INC  
    sid(25090), # HON,   HONEYWELL INTERNATIONAL INC  
    sid(3735),  # HPQ,   HEWLETT-PACKARD CO  
    sid(3766),  # IBM,   INTL BUSINESS MACHINES CORP  
    sid(3951),  # INTC,  INTEL CORP  
    sid(4151),  # JNJ,   JOHNSON AND JOHNSON  
    sid(25006), # JPM,   JPMORGAN CHASE & CO COM STK  
    sid(4283),  # KO,    COCA-COLA CO  
    sid(4487),  # LLY,   LILLY ELI & CO  
    sid(12691), # LMT,   LOCKHEED MARTIN CORP  
    sid(4521),  # LOW,   LOWES COMPANIES INC  
    sid(4707),  # MCD,   MCDONALDS CORP  
    sid(22802), # MDLZ,  MONDELEZ INTERNATIONAL INC  
    sid(4758),  # MDT,   MEDTRONIC INC  
    sid(21418), # MET,   METLIFE  INC  
    sid(4922),  # MMM,   3M COMPANY  
    sid(4954),  # MO,    ALTRIA GROUP INC.  
    sid(22140), # MON,   MONSANTO COMPANY  
    sid(5029),  # MRK,   MERCK & CO INC  
    sid(17080), # MS,    MORGAN STANLEY  
    sid(5061),  # MSFT,  MICROSOFT CORP  
    sid(5328),  # NKE,   NIKE INC CL-B  
    sid(24809), # NOV,   NATIONAL OILWELL VARCO  INC.  
    sid(5442),  # NSC,   NORFOLK SOUTHERN CORP  
    sid(12213), # NWSA,  NEWS CP - CL A  
    sid(5692),  # ORCL,  ORACLE CORP  
    sid(5729),  # OXY,   OCCIDENTAL PETROLEUM CORP  
    sid(5885),  # PEP,   PEPSICO INC  
    sid(5923),  # PFE,   PFIZER INC  
    sid(5938),  # PG,    PROCTER & GAMBLE CO  
    sid(6295),  # QCOM,  QUALCOMM INC  
    sid(6583),  # RTN,   RAYTHEON CO. (NEW)  
    sid(6683),  # SBUX,  STARBUCKS CORPORATION  
    sid(6928),  # SLB,   SCHLUMBERGER LTD  
    sid(7011),  # SO,    SOUTHERN CO  
    sid(10528), # SPG,   SIMON PROPERTIES GROUP INC  
    sid(6653),  # T,     AT&T INC. COM  
    sid(21090), # TGT,   TARGET CORPORATION  
    sid(357),   # TWX,   TIME WARNER INC.  
    sid(7671),  # TXN,   TEXAS INSTRUMENTS INC  
    sid(7792),  # UNH,   UNITEDHEALTH GROUP INC  
    sid(7800),  # UNP,   UNION PACIFIC CORPORATION  
    sid(20940), # UPS,   UNITED PARCEL SERVICE INC.CL B  
    sid(25010), # USB,   U.S.BANCORP (NEW)  
    sid(7883),  # UTX,   UNITED TECHNOLOGIES CORP  
    sid(21839), # VZ,    VERIZON COMMUNICATIONS  
    sid(8089),  # WAG,   WALGREEN COMPANY  
    sid(8151),  # WFC,   WELLS FARGO & CO(NEW)  
    sid(8214),  # WMB,   WILLIAMS COMPANIES  
    sid(8229),  # WMT,   WAL-MART STORES INC  
    sid(8347),  # XOM,   EXXON MOBIL CORPORATION  
    ]  
def handle_data(context, data):  
    if not intradingwindow_check(context):  
        return

    prices = history(30, '1d', 'price', ffill=True)  
    volumes = history(30, '1d', 'volume', ffill=True)  
    if (np.any(pd.isnull(prices)) or np.any(pd.isnull(volumes))):  
        print prices.tail()  
        print volumes.tail()  
def intradingwindow_check(context):  
    # Converts all time-zones into US EST to avoid confusion  
    loc_dt = get_datetime().astimezone(timezone('US/Eastern'))  
    if loc_dt.hour == 10 and loc_dt.minute == 0:  
        return True  
    else:  
        return False