def filter_universe():  
    """
    9 filters:
        1. common stock
        2 & 3. not limited partnership - name and database check
        4. database has fundamental data
        5. not over the counter
        6. not when issued
        7. not depository receipts
        8. primary share
        9. high dollar volume
    Check Scott's notebook for more details.
    """
    common_stock = mstar.share_class_reference.security_type.latest.eq('ST00000001')
    not_lp_name = ~mstar.company_reference.standard_name.latest.matches('.* L[\\. ]?P\.?$')
    not_lp_balance_sheet = mstar.balance_sheet.limited_partnership.latest.isnull()
    have_data = mstar.valuation.market_cap.latest.notnull()
    not_otc = ~mstar.share_class_reference.exchange_id.latest.startswith('OTC')
    not_wi = ~mstar.share_class_reference.symbol.latest.endswith('.WI')
    not_depository = ~mstar.share_class_reference.is_depositary_receipt.latest
    primary_share = IsPrimaryShare()
    
    # Combine the above filters.
    tradable_filter = (common_stock & not_lp_name & not_lp_balance_sheet &
                       have_data & not_otc & not_wi & not_depository & primary_share)
    
    high_volume_tradable = AverageDollarVolume(
            window_length=21,
            mask=tradable_filter
        ).rank(ascending=False) < 500

    mask = high_volume_tradable
    
    return mask
def make_pipeline():
    """
    A function to create our dynamic stock selector (pipeline). Documentation on
    pipeline can be found here: https://www.quantopian.com/help#pipeline-title
    """

    # Base universe set to the Q500US
    base_universe = Q1500US()
    trading_universe = Q1500US()

    # Factor of yesterday's close price.
    pricing = USEquityPricing.close.latest

    primary_share = IsPrimaryShare(mask=base_universe)
    market_cap = Market_cap(mask=base_universe)
    sales = Sales(mask=base_universe)
    industry = Industry(mask=base_universe)

    universe = (primary_share & (pricing > 5))

    return Pipeline(
        #        screen = base_universe,
        screen=universe,
        columns={
            'market_cap': market_cap,
            'sales': sales,
            'industry': industry,
            'in_trading_univ': trading_universe,
        })
コード例 #3
0
def universe_filters():
    # Equities with an average daily volume greater than 750000.
    high_volume = (AverageDollarVolume(window_length=252) > 750000)
    # Not Misc. industry:
    indsutry_code_filter = ~ms.asset_classification.morningstar_industry_code.latest.isnull(
    )

    # Equities that morningstar lists as primary shares.
    # NOTE: This will return False for stocks not in the morningstar database.
    primary_share = IsPrimaryShare()

    # Equities for which morningstar's most recent Market Cap value is above $300m.
    have_market_cap = mstar.valuation.market_cap.latest > 300000000

    # Equities not listed as depositary receipts by morningstar.
    # Note the inversion operator, `~`, at the start of the expression.
    not_depositary = ~mstar.share_class_reference.is_depositary_receipt.latest

    # Equities that listed as common stock (as opposed to, say, preferred stock).
    # This is our first string column. The .eq method used here produces a Filter returning
    # True for all asset/date pairs where security_type produced a value of 'ST00000001'.
    common_stock = mstar.share_class_reference.security_type.latest.eq(
        'COMMON_STOCK')

    # Equities whose exchange id does not start with OTC (Over The Counter).
    # startswith() is a new method available only on string-dtype Classifiers.
    # It returns a Filter.
    not_otc = ~mstar.share_class_reference.exchange_id.latest.startswith('OTC')

    # Equities whose symbol (according to morningstar) ends with .WI
    # This generally indicates a "When Issued" offering.
    # endswith() works similarly to startswith().
    not_wi = ~mstar.share_class_reference.symbol.latest.endswith('.WI')

    # Equities whose company name ends with 'LP' or a similar string.
    # The .matches() method uses the standard library `re` module to match
    # against a regular expression.
    not_lp_name = ~mstar.company_reference.standard_name.latest.matches(
        '.* L[\\. ]?P\.?$')
    # Equities with a null entry for the balance_sheet.limited_partnership field.
    # This is an alternative way of checking for LPs.
    not_lp_balance_sheet = mstar.balance_sheet.limited_partnership.latest.isnull(
    )
    # Highly liquid assets only. Also eliminates IPOs in the past 12 months
    # Use new average dollar volume so that unrecorded days are given value 0
    # and not skipped over
    # S&P Criterion
    liquid = ADV_adj() > 250000
    # Add logic when global markets supported
    # S&P Criterion
    domicile = True
    # Keep it to liquid securities
    ranked_liquid = ADV_adj().rank(ascending=False) < 1500
    # universe_filter = (indsutry_code_filter & high_volume & primary_share & have_market_cap & not_depositary & common_stock & not_otc & not_wi & not_lp_name & not_lp_balance_sheet & liquid & domicile & liquid & ranked_liquid)
    universe_filter = (indsutry_code_filter & primary_share & high_volume
                       & ranked_liquid)

    return universe_filter
コード例 #4
0
def make_pipeline(context):
    ## symbol universe
    base_universe = Q500US() if False else Q1500US()
    ## filters
    # Filter for primary share equities. IsPrimaryShare is a built-in filter.
    primary_share = IsPrimaryShare()
    # Equities listed as common stock (as opposed to, say, preferred stock).
    # 'ST00000001' indicates common stock.
    common_stock = morningstar.share_class_reference.security_type.latest.eq(
        'ST00000001')
    # Non-depositary receipts. Recall that the ~ operator inverts filters,
    # turning Trues into Falses and vice versa
    not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest
    # Equities not trading over-the-counter.
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith(
        'OTC')
    # Not when-issued equities.
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
    # Equities without LP in their name, .matches does a match using a regular expression
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches(
        '.* L[. ]?P.?$')
    # Equities with a null value in the limited_partnership Morningstar fundamental field.
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull(
    )
    # Equities whose most recent Morningstar market cap is not null have fundamental data and therefore are not ETFs.
    have_market_cap = morningstar.valuation.market_cap.latest.notnull()
    is_cyclical = SuperSector().eq(SuperSector.CYCLICAL)
    is_defensive = SuperSector().eq(SuperSector.DEFENSIVE)
    is_sensitive = SuperSector().eq(SuperSector.SENSITIVE)

    sector = Sector()
    close = USEquityPricing.close

    # For filter
    tradeable_stocks = (primary_share
                        & common_stock
                        & not_depositary
                        & not_otc
                        & not_wi
                        & not_lp_name
                        & not_lp_balance_sheet
                        & have_market_cap
                        & (is_cyclical | is_defensive | is_sensitive))
    dollar_volume = AverageDollarVolume(window_length=30)
    high_dollar_volume = dollar_volume.percentile_between(98, 100)

    myscreen = (base_universe & tradeable_stocks & high_dollar_volume)

    # Pipeline
    pipe = Pipeline(columns={
        'yesterday_close': close.latest,
        'day_before_yesterday_close': PrevClose(),
        'day_before_yesterday_volume': PrevVolume(),
        'morningstar_sector_code': sector,
    },
                    screen=myscreen)
    return pipe
コード例 #5
0
def get_tradeable_stocks():
    # Filter for primary share equities. IsPrimaryShare is a built-in filter.
    primary_share = IsPrimaryShare()

    # Equities listed as common stock (as opposed to, say, preferred stock).
    # 'ST00000001' indicates common stock.
    common_stock = morningstar.share_class_reference.security_type.latest.eq(
        'ST00000001')

    # Non-depositary receipts. Recall that the ~ operator inverts filters,
    # turning Trues into Falses and vice versa
    not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest

    # Equities not trading over-the-counter.
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith(
        'OTC')

    # Not when-issued equities.
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')

    # Equities without LP in their name, .matches does a match using a regular
    # expression
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches(
        '.* L[. ]?P.?$')

    # Equities with a null value in the limited_partnership Morningstar
    # fundamental field.
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull(
    )

    # Equities whose most recent Morningstar market cap is not null have
    # fundamental data and therefore are not ETFs.
    have_market_cap = morningstar.valuation.market_cap.latest.notnull()

    # Filter for stocks that pass all of our previous filters.
    tradeable_stocks = (primary_share
                        & common_stock
                        & not_depositary
                        & not_otc
                        & not_wi
                        & not_lp_name
                        & not_lp_balance_sheet
                        & have_market_cap)

    return tradeable_stocks
def universe_filters():
    # Equities with an average daily volume greater than 750000.
    high_volume = (AverageDollarVolume(window_length=252) > 750000)
    # Not Misc. industry:
    indsutry_code_filter = ~ms.asset_classification.morningstar_industry_code.latest.isnull(
    )

    # Equities that morningstar lists as primary shares.
    # NOTE: This will return False for stocks not in the morningstar database.
    primary_share = IsPrimaryShare()

    # Keep it to liquid securities
    ranked_liquid = ADV_adj().rank(ascending=False) < 1500

    universe_filter = (indsutry_code_filter & primary_share & high_volume
                       & ranked_liquid)

    return universe_filter
コード例 #7
0
def filter_universe():
    """

    Modified from Nathan Wolfe's Algorithm
    https://www.quantopian.com/posts/pipeline-trading-universe-best-practice

    returns
    -------
    zipline.pipeline.Filter
        Filter for the set_screen of a Pipeline to create an
        ideal trading universe

    The filters:
        1. common stock
        2 & 3. not limited partnership - name and database check
        4. database has fundamental data
        5. not over the counter
        6. not when issued
        7. not depository receipts
        8. primary share
        9. high dollar volume
    """

    common_stock = mstar.share_class_reference.security_type.latest.eq('ST00000001')
    not_lp_name = ~mstar.company_reference.standard_name.latest.matches('.* L[\\. ]?P\.?$')
    not_lp_balance_sheet = mstar.balance_sheet.limited_partnership.latest.isnull()
    have_data = mstar.valuation.market_cap.latest.notnull()
    not_otc = ~mstar.share_class_reference.exchange_id.latest.startswith('OTC')
    not_wi = ~mstar.share_class_reference.symbol.latest.endswith('.WI')
    not_depository = ~mstar.share_class_reference.is_depositary_receipt.latest
    primary_share = IsPrimaryShare()

    # Combine the above filters.
    tradable_filter = (common_stock & not_lp_name & not_lp_balance_sheet &
                       have_data & not_otc & not_wi & not_depository & primary_share)

    high_volume_tradable = (AverageDollarVolume(window_length=21,
                                                mask=tradable_filter).percentile_between(70, 100))

    screen = high_volume_tradable

    return screen
def make_pipeline():
    """
    Create our pipeline.
    """

    # To make the program more flexible, we allow for the possibility of having two universes,
    #   one for estimating HHI and one for trading stocks after sorting by changes in HHI
    estimation_universe = Q500US()
    trading_universe = Q500US()

    pricing = USEquityPricing.close.latest
    # Note that if we don't filter for primary share class, we double count sales for dual class stocks
    primary_share = IsPrimaryShare(mask=estimation_universe)
    sales = Sales(mask=estimation_universe)
    industry = Industry(mask=estimation_universe)

    universe = (primary_share & (pricing > 5))

    return Pipeline(screen=universe,
                    columns={
                        'sales': sales,
                        'industry': industry,
                        'in_trading_univ': trading_universe
                    })
コード例 #9
0
def make_pipeline(context):

    # Filter for primary share equities. IsPrimaryShare is a built-in filter.
    primary_share = IsPrimaryShare()

    # Equities listed as common stock (as opposed to, say, preferred stock).
    # 'ST00000001' indicates common stock.
    common_stock = morningstar.share_class_reference.security_type.latest.eq(
        'ST00000001')

    # Non-depositary receipts. Recall that the ~ operator inverts filters,
    # turning Trues into Falses and vice versa
    not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest

    # Equities not trading over-the-counter.
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith(
        'OTC')

    # Not when-issued equities.
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')

    # Equities without LP in their name, .matches does a match using a regular
    # expression
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches(
        '.* L[. ]?P.?$')

    # Equities with a null value in the limited_partnership Morningstar
    # fundamental field.
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull(
    )

    # Equities whose most recent Morningstar market cap is not null have
    # fundamental data and therefore are not ETFs.
    have_market_cap = morningstar.valuation.market_cap.latest.notnull()

    # At least a certain price
    price = USEquityPricing.close.latest
    AtLeastPrice = (price >= context.MyLeastPrice)
    AtMostPrice = (price <= context.MyMostPrice)

    # Filter for stocks that pass all of our previous filters.
    tradeable_stocks = (primary_share
                        & common_stock
                        & not_depositary
                        & not_otc
                        & not_wi
                        & not_lp_name
                        & not_lp_balance_sheet
                        & have_market_cap
                        & AtLeastPrice
                        & AtMostPrice)

    log.info('''
Algorithm initialized variables:
 context.MaxCandidates %s
 LowVar %s
 HighVar %s''' %
             (context.MaxCandidates, context.LowerFilter, context.UpperFilter))

    # High dollar volume filter.
    base_universe = AverageDollarVolume(
        window_length=20,
        mask=tradeable_stocks).percentile_between(context.LowerFilter,
                                                  context.UpperFilter)

    # Short close price average.
    ShortSMA = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                   window_length=context.ShortSmaTerm,
                                   mask=base_universe)

    # Long close price average.
    LongSMA = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=context.LongSmaTerm,
                                  mask=base_universe)

    percent_difference = (ShortSMA - LongSMA) / LongSMA

    ADV = AverageDollarVolume(window_length=context.LongSmaTerm,
                              mask=base_universe)

    # Filter to select securities to long.
    stocks_worst = percent_difference.bottom(context.MaxCandidates)

    return Pipeline(
        columns={
            'average_dollor_vol': ADV,
            'stocks_worst': stocks_worst,
        },
        screen=stocks_worst,
    )
コード例 #10
0
def make_pipeline(context):
    ## symbol universe
    base_universe = Q500US() if False else Q1500US()

    ## filters
    # Filter for primary share equities. IsPrimaryShare is a built-in filter.
    primary_share = IsPrimaryShare()
    # Equities listed as common stock (as opposed to, say, preferred stock).
    # 'ST00000001' indicates common stock.
    common_stock = morningstar.share_class_reference.security_type.latest.eq('ST00000001')
    # Non-depositary receipts. Recall that the ~ operator inverts filters,
    # turning Trues into Falses and vice versa
    not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest
    # Equities not trading over-the-counter.
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')
    # Not when-issued equities.
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
    # Equities without LP in their name, .matches does a match using a regular expression
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches('.* L[. ]?P.?$')
    # Equities with a null value in the limited_partnership Morningstar fundamental field.
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()
    # Equities whose most recent Morningstar market cap is not null have fundamental data and therefore are not ETFs.
    have_market_cap = morningstar.valuation.market_cap.latest.notnull()
    is_cyclical = SuperSector().eq(SuperSector.CYCLICAL)
    is_defensive = SuperSector().eq(SuperSector.DEFENSIVE)
    is_sensitive = SuperSector().eq(SuperSector.SENSITIVE)

    # Filter for stocks that pass all of our previous filters.
    tradeable_stocks = (
        primary_share
        &common_stock
        &not_depositary
        &not_otc
        &not_wi
        &not_lp_name
        &not_lp_balance_sheet
        &have_market_cap
        #&(is_cyclical)
        #&(is_defensive)
        #&(is_sensitive)
        &(is_cyclical | is_defensive | is_sensitive)
    )

    # ToDo この範囲を色々変えてみる.
    dollar_volume = AverageDollarVolume(window_length=30)
    high_dollar_volume = dollar_volume.percentile_between(98, 100)
    daily_volatility = AnnualizedVolatility(window_length=20)/math.sqrt(252)
    sme20 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=20)
    rsi = RSI(inputs=[USEquityPricing.close])
    #sector = ms.asset_classification.morningstar_sector_code
    sector = Sector()
    static_sectors = (sector.eq(311) | 
                      sector.eq(309) | 
                      sector.eq(103) | 
                      sector.eq(101) | 
                      sector.eq(308) | 
                      sector.eq(206) )

    if context.static_asset:
        myscreen = StaticSids(context.special_sids) #context.special_assets
    else: 
        myscreen = (base_universe & tradeable_stocks & high_dollar_volume ) # & static_sectors
        

    pipe = Pipeline(
        columns={
            'prev_close': PrevClose(),
            'prev_volume': PrevVolume(),
            'prev_turnover': PrevClose()*PrevVolume(),
            'dollar_volume': dollar_volume,
            'high_dollar_volume': high_dollar_volume,
            'daily_volatility': daily_volatility,
            'sma20': sme20,
            'rsi': rsi,
            'morningstar_sector_code': sector,
        },
        screen=myscreen,
    )
    return pipe
コード例 #11
0
    ev = Fundamentals.enterprise_value.latest

    # Base universe set to the QTradableStocksUS
    # Around 1600-2100 stocks
    # https://www.quantopian.com/posts/working-on-our-best-universe-yet-qtradablestocksus
    #
    # If we dont use it, there are around 4000 stocks.  But we must
    # screen for price & liquidity ourselves. And I think Quantopian
    # may only support their own stock universe(s) later.
    base_universe = QTradableStocksUS()

    # Filter tradable stocks.
    # https://www.quantopian.com/posts/pipeline-trading-universe-best-practice
 
    # Filter for primary share equities. IsPrimaryShare is a built-in filter.
    primary_share = IsPrimaryShare()
 
    # Equities listed as common stock (as opposed to, say, preferred stock).
    # 'ST00000001' indicates common stock.
    common_stock = Fundamentals.security_type.latest.eq('ST00000001')
 
    # Non-depositary receipts. Recall that the ~ operator inverts filters,
    # turning Trues into Falses and vice versa
    not_depositary = ~Fundamentals.is_depositary_receipt.latest
 
    # Equities not trading over-the-counter.
    not_otc = ~Fundamentals.exchange_id.latest.startswith('OTC')
 
    # Not when-issued equities.
    not_wi = ~Fundamentals.symbol.latest.endswith('.WI')
 
コード例 #12
0
def make_pipeline(context):
    """
    Create our pipeline.
    """

    # Filter for primary share equities. IsPrimaryShare is a built-in filter.
    primary_share = IsPrimaryShare()

    # Equities listed as common stock (as opposed to, say, preferred stock).
    # 'ST00000001' indicates common stock.
    common_stock = morningstar.share_class_reference.security_type.latest.eq(
        'ST00000001')

    # Non-depositary receipts. Recall that the ~ operator inverts filters,
    # turning Trues into Falses and vice versa
    not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest

    # Equities not trading over-the-counter.
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith(
        'OTC')

    # Not when-issued equities.
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')

    # Equities without LP in their name, .matches does a match using a regular
    # expression
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches(
        '.* L[. ]?P.?$')

    # Equities with a null value in the limited_partnership Morningstar
    # fundamental field.
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull(
    )

    # Equities whose most recent Morningstar market cap is not null have
    # fundamental data and therefore are not ETFs.
    have_market_cap = morningstar.valuation.market_cap.latest.notnull()

    # At least a certain price
    price = USEquityPricing.close.latest
    AtLeastPrice = (price >= context.MyLeastPrice)
    AtMostPrice = (price <= context.MyMostPrice)

    # Filter for stocks that pass all of our previous filters.
    tradeable_stocks = (primary_share
                        & common_stock
                        & not_depositary
                        & not_otc
                        & not_wi
                        & not_lp_name
                        & not_lp_balance_sheet
                        & have_market_cap
                        & AtLeastPrice
                        & AtMostPrice)

    LowVar = 6
    HighVar = 40

    log.info('''
Algorithm initialized variables:
 context.MaxCandidates %s
 LowVar %s
 HighVar %s''' % (context.MaxCandidates, LowVar, HighVar))

    # High dollar volume filter.
    # LowVar ~ HighVar の間の20日出来高平均.
    # 出来高平均が低いものだけ取得
    base_universe = AverageDollarVolume(
        window_length=20,
        mask=tradeable_stocks).percentile_between(LowVar, HighVar)

    # Short close price average.
    # 期間3日のSMA
    ShortAvg = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                   window_length=3,
                                   mask=base_universe)

    # Long close price average.
    # 期間45日のSMA
    LongAvg = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=45,
                                  mask=base_universe)

    # (SMA3-SMA45)をSMA45から見てどのくらい差があるか
    # つまり,この差がポジティブに大きければ,過去45日間で大きく値が上がったと言う意味
    percent_difference = (ShortAvg - LongAvg) / LongAvg

    # Filter to select securities to long.
    # percent_differenceが小さい銘柄を下から100銘柄
    # つまり,過去の値動きが小さい.もしくはネガティブに大きいものを拾ってくる.
    stocks_worst = percent_difference.bottom(context.MaxCandidates)
    securities_to_trade = (stocks_worst)

    return Pipeline(
        columns={'stocks_worst': stocks_worst},
        screen=(securities_to_trade),
    )
コード例 #13
0
def initialize(context):
    pipe = Pipeline()
    attach_pipeline(pipe, 'ranked_2000')
    my_sectors = [206]  #"Healthcare"
    sector_filter = Sector().element_of(my_sectors)
    # Create list of all criteria for securities worth investing in
    """
    9 filters:
        1. common stock
        2 & 3. not limited partnership - name and database check
        4. database has fundamental data
        5. not over the counter
        6. not when issued
        7. not depository receipts
        8. primary share
        9. high dollar volume
    """
    mkt_cap = MarketCap()
    top_2000 = mkt_cap.top(2000)
    common_stock = morningstar.share_class_reference.security_type.latest.eq(
        'ST00000001')
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches(
        '.* L[\\. ]?P\.?$')
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull(
    )
    have_data = morningstar.valuation.market_cap.latest.notnull()
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith(
        'OTC')
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
    not_depository = ~morningstar.share_class_reference.is_depositary_receipt.latest
    primary_share = IsPrimaryShare()

    # Combine the above filters.
    tradable_filter = (common_stock & not_lp_name & not_lp_balance_sheet
                       & have_data & not_otc & not_wi & not_depository
                       & primary_share & sector_filter & top_2000)
    pipe_screen = (sector_filter)

    # Create, register and name a pipeline

    # Add the factor defined to the pipeline
    price_to_sales = Price_to_sales(mask=tradable_filter)
    pipe.add(price_to_sales, 'price to sales')

    # Create and apply a filter representing the top 2000 equities by MarketCap every day
    # This is an approximation of the Russell 2000

    # Rank price to sales and add the rank to our pipeline
    price_to_sales_rank = price_to_sales.rank(mask=tradable_filter)
    pipe.add(price_to_sales_rank, 'ps_rank')
    # Set a screen to ensure that only the top 2000 companies by market cap
    # which are healthcare companies with positive PS ratios are screened
    pipe.set_screen(top_2000 & (price_to_sales > 0))
    # Scedule my rebalance function
    schedule_function(func=rebalance,
                      date_rule=date_rules.month_start(days_offset=0),
                      time_rule=time_rules.market_open(hours=0, minutes=30),
                      half_days=True)
    # Schedule my plotting function
    schedule_function(func=record_vars,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(),
                      half_days=True)
    # set my leverage
    context.long_leverage = 1.00
    context.short_leverage = -0.00
    context.spy = sid(8554)
    context.short_list = []
    context.short_list.append(context.spy)
コード例 #14
0
def make_pipeline():
    """
    Create our pipeline.
    """

    # Filter for primary share equities. IsPrimaryShare is a built-in filter.
    primary_share = IsPrimaryShare()

    # Equities listed as common stock (as opposed to, say, preferred stock).
    # 'ST00000001' indicates common stock.
    common_stock = morningstar.share_class_reference.security_type.latest.eq('ST00000001')

    # Non-depositary receipts. Recall that the ~ operator inverts filters,
    # turning Trues into Falses and vice versa
    not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest

    # Equities not trading over-the-counter.
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')

    # Not when-issued equities.
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')

    # Equities without LP in their name, .matches does a match using a regular
    # expression
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches('.* L[. ]?P.?$')

    # Equities with a null value in the limited_partnership Morningstar
    # fundamental field.
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()

    # Equities whose most recent Morningstar market cap is not null have
    # fundamental data and therefore are not ETFs.
    have_market_cap = morningstar.valuation.market_cap.latest.notnull()

    # Filter for stocks that pass all of our previous filters.
    tradeable_stocks = (
        primary_share
        & common_stock
        & not_depositary
        & not_otc
        & not_wi
        & not_lp_name
        & not_lp_balance_sheet
        & have_market_cap
    )

    # High dollar volume filter.
    base_universe = AverageDollarVolume(window_length=20, mask=tradeable_stocks).percentile_between(70, 100)

    # 10-day close price average.
    mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=base_universe)

    # 30-day close price average.
    mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=base_universe)

    percent_difference = (mean_10 - mean_30) / mean_30

    # Filter to select securities to short.
    shorts = percent_difference.top(25)

    # Filter to select securities to long.
    longs = percent_difference.bottom(25)

    # Filter for all securities that we want to trade.
    securities_to_trade = (shorts | longs)

    return Pipeline(
        columns={
            'longs': longs,
            'shorts': shorts
        },
        screen=(securities_to_trade),
    )