Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
screen to drop securities from list by trade date?

I'm looking for example code to screen a list of stocks to exclude ones that don't trade (e.g. due to de-listing) over the entire span of a backtest. Any ideas?

I've been running into a problem that my algorithm will buy a stock, but then not be able to sell it because it becomes inactive (for example, see https://www.quantopian.com/posts/market-closed-gap-trade). So, I'd like to exclude those stocks that are not listed over the full range of dates of the backtest (e.g. SNK).

Thanks,

Grant

4 responses

Hello Grant,

This is clumsy:

import datetime

def initialize(context):  
    stocks_in = [sid(39872), sid(2), sid(21), sid(42950)]  
    start_date = datetime.date(2009, 3 , 18)  
    end_date   = datetime.date(2014, 3 , 18)  
    context.stocks = []  
    for stock in stocks_in:  
        if stock.security_start_date.date() <= start_date and \  
           stock.security_end_date.date() >= end_date:  
            context.stocks.append(stock)  
    context.first = True

def handle_data(context, data):  
    if context.first:  
        print len(context.stocks)  
        context.first = False  

If context.portfolio.end_date existed and both context.portfolio.start_date and context.portfolio.end_date were available in initialize....

P.

Thanks! Works! --Grant

Grant, you should consider making that function only exclude symbols after they've been de-listed. Seems like an easy way to introduce survivorship bias

Thanks David,

I'm aware of the concept of survivorship bias, but what motivated this post was that some securities in the Quantopian database are offered with definite maturity dates. For example, SNK:

https://www.nasdaqtrader.com/content/newsalerts/2010/infocirculars/SNKcircular.pdf

http://www.nyse.com/pdfs/TraderUpdateSusp%28SKN&SVW%29.pdf

Per the documents, SNK is the symbol for Bank of America SPX Capped Leveraged Index Return
Notes (CUSIP 06052K281), with a maturity of 6/29/2012.

So, if one excludes securities that are scheduled to mature ("fail"), the bias differs from the classic survivorship bias (which involves using information available now that would not have been available over the period of the backtest--which companies failed and which survived).

Grant