Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Sorting through securities

Hey all,

I'm pretty new to Quantopian and was wondering if anyone could give me a hand with this implementation. I'm trying to create write code that will filter through all securities that are available and heapify them according to various metrics like mavg, My first thought was writing a for loop and going through 'data' and having a helper method sort through the securities but i keep getting compiler errors. If anyone has any tips it's greatly appreciated.

4 responses

Hi Michael,

You could use set_universe (https://www.quantopian.com/posts/new-feature-set-universe-is-live) or a big list of securities like the one found here (https://www.quantopian.com/posts/list-of-nasdaq-100-sids-to-use-in-your-algo) to start off with

Could you post what you have now so I could take a look at your code?

Thanks,
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.

Here's another handy list. I did not develop it--full credit to the those who did. --Grant

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  
    ]  

Thanks guys! That helps a lot.

My code is pretty hacked up right now. But in a nutshell, it just contains a heap sort method and an awful attempt at iterating through stocks contained in 'data' using a for loop. I pretty much just googled a python heap implementation and just tweaked it.

I would like to add to this. How can I do sorting once I've implemented the set_universe call. I'll try to keep this as simple as possible. For my example only 2 stocks to be in the portfolio. Currently the implementation below will just buy the first 2 stock from the universe meeting the momentum conditions. How can I change it to chose the 2 that are highest?

#  
# Complete Includes  
#  
import math

#  
# Partial Includes  
#  
from pytz import timezone, utc  
from datetime import datetime, timedelta

#  
# Technical Library Initialize  
#  
movingAverage = ta.EMA(timeperiod=200)  
momentum = ta.CMO(timeperiod=10)

#  
# Algo Setup  
#  
def initialize(context):  
    # Algorithm configuration parameters  
    context.buyThreshold  = 35 # %  
    context.sellThreshold = 10 # %  
    set_universe(universe.DollarVolumeUniverse(floor_percentile=99.8,ceiling_percentile=100.0))

    # Account configuration parameters  
    context.allowableMargin    = 0.0 # 0 %  
    context.availableMargin    = context.portfolio.cash * context.allowableMargin  
    context.usedMargin         = 0.0 # In Dollars  
    context.cash               = context.portfolio.cash + context.availableMargin  
    context.cashUsed           = 0  
    context.stocksInPortfolio  = 0  
    context.portfolioSizeRequested = 2  

    # Simulation Parameters  
    set_commission(commission.PerTrade(cost=10.00))  
    context.lastTradingDay = datetime(2009,1,4)

#  
# Process new stock data (runs about 1 time per min)  
#  
def handle_data(context, data):  

    # Metrics  
    record(cash=context.cash)  

    # Daily Clean Up  
    currentTime = get_datetime()  
    if currentTime.date != context.lastTradingDay.date:  
        context.lastTradeingDay = currentTime  
        cleanUpOldOrders(context,data)  

    # Compute technicals for all stocks  
    ema = movingAverage(data)  
    momentumOscillator = momentum(data)

    # Loop over all stock to find candiates  
    for stock in data.keys():

        # Long Conditions  
        if (momentumOscillator[stock] > context.buyThreshold  
            and data[stock].price > ema[stock]):  
            orderManager(context,data,stock,1)  

        # Exit long Conditions  
        if (momentumOscillator[stock]