コード例 #1
0
def make_pipeline():
    
    # define alpha factors
    momentum = Momentum()
    growth = morningstar.operation_ratios.revenue_growth.latest
    pe_ratio = morningstar.valuation_ratios.pe_ratio.latest
        
    # Screen out non-desirable securities by defining our universe. 
    mkt_cap_filter = morningstar.valuation.market_cap.latest >= 500000000    
    price_filter = USEquityPricing.close.latest >= 5
    universe = Q1500US() & price_filter & mkt_cap_filter & \
               momentum.notnull() & growth.notnull() & pe_ratio.notnull()

    combined_rank = (
        momentum.rank(mask=universe).zscore() +
        growth.rank(mask=universe).zscore() +
        pe_ratio.rank(mask=universe).zscore()
    )

    longs = combined_rank.top(NUM_LONG_POSITIONS)
    shorts = combined_rank.bottom(NUM_SHORT_POSITIONS)

    long_short_screen = (longs | shorts)        

    # Create pipeline
    pipe = Pipeline(columns = {
        'longs':longs,
        'shorts':shorts,
        'combined_rank':combined_rank,
        'momentum':momentum,
        'growth':growth,            
        'pe_ratio':pe_ratio
    },
    screen = long_short_screen)
    return pipe
コード例 #2
0
def make_pipeline():
    base_universe = Q1500US()
    sector = morningstar.asset_classification.morningstar_sector_code.latest
    energy_sector = sector.eq(309)

    base_energy = base_universe & energy_sector

    dollar_volume = AverageDollarVolume(window_length=30)
    high_dollar_volume = dollar_volume.percentile_between(95, 100)

    top_five_base_energy = base_energy & high_dollar_volume

    mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=10,
                                  mask=top_five_base_energy)

    mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=30,
                                  mask=top_five_base_energy)

    percent_difference = (mean_10 - mean_30) / mean_30

    shorts = percent_difference < 0
    longs = percent_difference > 0

    securities_to_trade = (shorts | longs)

    return Pipeline(columns={
        'longs': longs,
        'shorts': shorts,
        'percent_diff': percent_difference
    },
                    screen=securities_to_trade)
コード例 #3
0
def make_pipeline(context):
    """
    A function to create our pipeline (dynamic stock selector). The pipeline is 
    used to rank stocks based on different factors, including builtin factors, 
    or custom factors that you can define. Documentation on pipeline can be 
    found here:
    https://www.quantopian.com/help#pipeline-title
    """

    # Filter for stocks in the Q1500US universe. For more detail, see this post:
    # https://www.quantopian.com/posts/the-q500us-and-q1500us
    universe = Q1500US()

    # Create a Returns factor with a 5-day lookback window for all
    # securities in our Q1500US Filter.
    recent_returns = Returns(window_length=context.returns_lookback,
                             mask=universe)

    # Define high and low returns filters to be the bottom 10% and top 10% of
    # securities in the high dollar-volume group.
    low_returns = recent_returns.percentile_between(0, 10)
    high_returns = recent_returns.percentile_between(90, 100)

    # Add a filter to the pipeline such that only high-return and low-return
    # securities are kept.
    securities_to_trade = (low_returns | high_returns)

    # Create a pipeline object with the defined columns and screen.
    pipe = Pipeline(columns={
        'low_returns': low_returns,
        'high_returns': high_returns,
    },
                    screen=securities_to_trade)

    return pipe
コード例 #4
0
def make_pipeline():
    
    ev = EV()
    excessCash = Fundamentals.enterprise_value.latest < 0
    
    Earnings = EBITDA()
    isProfitable = Fundamentals.ebitda.latest > 0 
    
    notFinance = Fundamentals.morningstar_sector_code != 103
    
    universe = Q1500US() & excessCash & notFinance
    buys = ev.top(5, mask=universe)
    
    longsUniverse = ev.top(5, mask=universe)
    
    tempEVMC = Fundamentals.enterprise_value.latest / Fundamentals.market_cap.latest
    evmc = tempEVMC < 0.7
    
    pipe = Pipeline(
        screen = longsUniverse,
        columns = {
            'Buys': buys,
            'EVMC': evmc
        }
    )
    
    return pipe
コード例 #5
0
def make_pipeline():
    # swap this out for testing different alphas
    # tested factors: operation_ratios, revenue_growth, operation_margin, sentiment, 
    #testing_factor = operation_ratios.revenue_growth.latest 
    
    testing_factor1 = operation_ratios.operation_margin.latest
    testing_factor2 = operation_ratios.revenue_growth.latest
    testing_factor3 = sentiment.sentiment_signal.latest
    
    universe = (Q1500US() & 
                testing_factor1.notnull() & 
                testing_factor2.notnull() & 
                testing_factor3.notnull())
    
    testing_factor1 = testing_factor1.rank(mask=universe, method='average')
    testing_factor2 = testing_factor2.rank(mask=universe, method='average')
    testing_factor3 = testing_factor3.rank(mask=universe, method='average')
    
    testing_factor = testing_factor1 + testing_factor2 + testing_factor3
    
    testing_quantiles = testing_factor.quantiles(2)
    
    pipe = Pipeline(columns={'testing_factor':testing_factor, 
                             'shorts':testing_quantiles.eq(0),
                            'longs':testing_quantiles.eq(1)}, screen=universe)
    return pipe
コード例 #6
0
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 = Q1500US()
    sector = Sector()
    # screen is based off of returns
    returns = Returns(window_length=2)
    # check if stock price has good strength, but not necessarily overbought
    rsi = RSI()
    price = USEquityPricing.close.latest
    # creating filter by specifying the type of returns desired
    top_return_stocks = returns.top(1, mask=base_universe, groupby=sector)
    pipe = Pipeline(
        columns={
            'rsi': rsi,
            'price': price
        },
        # filter top return stocks, and stocks that are not being overbought
        # but are not too oversold either
        screen=base_universe & top_return_stocks & (20 < rsi < 80)
        # the above is equivalent to: choose stocks from the base universe that have had the top returns in their sectors and have a good RSI value
    )
    return pipe
def make_pipeline(context):

    pipe = Pipeline()
    # Q1500US - вселенная из 1500 самых ликвидных активов
    universe = Q1500US()
    market_cap = MarketCap(mask=universe)
    market_cap_rank = market_cap.rank()
    # берем половину активов с большой капитализацией
    market_cap_high = market_cap_rank.top(750)
    volatility = Volatility(mask=market_cap_high)
    volatility_rank = volatility.rank()
    # оставляем 1/3 наименее волатильных
    volatility_low = volatility_rank.bottom(250)
    quality = Quality(mask=volatility_low)
    quality_rank = quality.rank()
    # 100 самых целесообразных в плане бизнеса
    qualit = quality_rank.top(120)  # was 100
    book_to_price = BookToPrice(mask=qualit)
    book_to_price_rank = book_to_price.rank()
    # 50 недооцененных в низким b/p
    highbp = book_to_price_rank.top(110)  # was 50
    securities_to_trade = (highbp)
    pipe = Pipeline(columns={
        'highbp': highbp,
    }, screen=securities_to_trade)

    return pipe
コード例 #8
0
ファイル: quant.py プロジェクト: bilalillama/Quantopian
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    context.iDays = 0
    context.NDays = 2  #
    set_slippage(slippage.FixedSlippage(spread=0.00))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))

    schedule_function(my_rebalance, TRADE_FREQ,
                      time_rules.market_open(minutes=1))

    # Record tracking variables at the end of each day.
    schedule_function(my_record_vars, date_rules.every_day(),
                      time_rules.market_close())

    # Set up universe, alphas and ML pipline
    context.universe = Q1500US()  # & ~IsAnnouncedAcqTarget()
    ml_factors = make_factors()
    ml_pipeline = make_ml_pipeline(ml_factors,
                                   context.universe,
                                   n_fwd_days=PRED_N_FWD_DAYS,
                                   window_length=ML_TRAINING_WINDOW)

    attach_pipeline(ml_pipeline, 'alpha_model')

    context.past_predictions = {}
    context.hold_out_accuracy = 0
    context.hold_out_log_loss = 0
    context.hold_out_returns_spread_bps = 0
コード例 #9
0
 def compute(self, today, assets, out, close):  
     close = pd.DataFrame(data=close, columns=assets) 
     # Going to rank largest we'll need to invert the sdev.
     # Annualized volatility is the standard deviation of logarithmic returns 
     # as a Ratio of its mean divided by 1/ sqrt of the number of trading days
     out[:] = 1 / np.log(close).diff().std()
     
     universe = Q1500US()
コード例 #10
0
def make_pipeline():
    """
    Create and return our pipeline.
    We break this piece of logic out into its own function to make it easier to
    test and modify in isolation.
    
    """

    # Create our mean reversion factor by taking the negative of a momentum factor
    
    reversion = Reversion()

    # Classify all securities by sector so that we can enforce sector neutrality later
    sector = Sector()

    # Screen out non-desirable securities by defining our universe.
    universe = Q1500US()

    # By applying a mask to the rank computations, we remove any stocks that failed
    # to meet our initial criteria **before** computing ranks.  This means that the
    # stock with rank 10.0 is the 10th-lowest stock that was included in the Q1500US.
    # 標準偏差
    # filter のかけかたを mask で行ってしまう
    factor_rank = reversion.rank(mask=universe).zscore()

    # Build Filters representing the top and bottom 150 stocks by our ranking system.
    # We'll use these as our tradeable universe each day.
    longs = factor_rank.top(NUM_LONG_POSITIONS)
    shorts = factor_rank.bottom(NUM_SHORT_POSITIONS)

    # The final output of our pipeline should only include
    # the top/bottom 300 stocks by our criteria
    long_short_screen = (longs | shorts)

    # Define any risk factors that we will want to neutralize
    # We are chiefly interested in market beta as a risk factor so we define it using
    # Bloomberg's beta calculation
    # Ref: https://www.lib.uwo.ca/business/betasbydatabasebloombergdefinitionofbeta.html
    beta = 0.66 * RollingLinearRegressionOfReturns(
        target=sid(8554),
        returns_length=5,
        regression_length=260,
        mask=long_short_screen
    ).beta + 0.33*1.0

    # Create pipeline
    pipe = Pipeline(
        columns={
            'longs': longs,
            'shorts': shorts,
            'factor_rank': factor_rank,
            'reversion': reversion,
            'sector': sector,
            'market_beta': beta
        },
        screen=long_short_screen
    )
    return pipe
コード例 #11
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
コード例 #12
0
ファイル: pipeline.py プロジェクト: liu1355/dl_fin
def Data_Pull_FFM():

    Data_Pipe_FFM = Pipeline()
    Data_Pipe_FFM.add(Momentum(), 'Momentum')
    Data_Pipe_FFM.add(SPY_proxy(), 'Market Cap')
    Data_Pipe_FFM.add(SPY_proxy.rank(mask = Q1500US()), 'Market Cap Rank')
    Data_Pipe_FFM.add(SPY_proxy.rank.top(1000), 'Biggest')
    Data_Pipe_FFM.add(SPY_proxy.rank.bottom(1000), 'Smallest')
    Data_Pipe_FFM.add(Price_to_Book(), 'Price to Book')
    Data_Pipe_FFM.add(Price_to_Book.rank.top(1000), 'Low BP')
    Data_Pipe_FFM.add(Price_to_Book.rank.bottom(1000), 'High BP')
    Data_Pipe_FFM.add(Returns(), 'Returns')
    Data_Pipe_FFM.add(Momentum.rank(mask=Q1500US()), 'Momentum Rank')
    Data_Pipe_FFM.add(Momentum.rank.top(1000), 'Top')
    Data_Pipe_FFM.add(Momentum.rank.bottom(1000), 'Bottom')

    Data_Pipe_FFM.add(Price_to_Book.rank(mask = Q1500US()), 'Price to Book Rank')

    return Data_Pipe_FFM
コード例 #13
0
def make_pipeline(context):

    profitable = mstar.valuation_ratios.ev_to_ebitda.latest > 0
    market_cap = mstar.valuation.market_cap.latest

    my_screen = market_cap.top(context.n_stocks, mask=(Q1500US() & profitable))

    return Pipeline(columns={
        'sector': Sector(),
    }, screen=my_screen)
コード例 #14
0
def make_pipeline():

    momentum = Momentum(inputs=[USEquityPricing.close], window_length=250)
    high = momentum.percentile_between(80, 100)
    low = momentum.percentile_between(0, 20)

    return Pipeline(columns={
        'Momentum': momentum,
        'long': high,
        'short': low,
    },
                    screen=Q1500US())
コード例 #15
0
def make_pipeline():
    #Get free cash flow yield from morningstart database (FCF/price)
    fcf = Fundamentals.fcf_yield.latest.rank(mask=Q1500US(), method='average')
    universe = (
        Q1500US()
        & fcf.notnull()
        #& is_fresh
        # & volatility_filter
    )
    #Sort into deciles
    num_quantiles = 5
    fcf_quantiles = fcf.quantiles(num_quantiles)
    #Build Pipeline, long top, short bottom decile
    pipe = Pipeline(screen=universe,
                    columns={
                        'FCF': fcf,
                        'longs': fcf_quantiles.eq(num_quantiles - 1),
                        'shorts': fcf_quantiles.eq(0)
                    })

    return pipe
コード例 #16
0
def make_pipeline2():

    # Universe Q1500US
    base_universe = Q1500US()

    # Energy Sector
    sector = morningstar.asset_classification.morningstar_sector_code.latest
    energy_sector = sector.eq(309)

    # Make Mask of 1500US and Energy
    base_energy = base_universe & energy_sector

    # Dollar Volume (30 Days) Grab the Info
    dollar_volume = AverageDollarVolume(window_length=30)

    # Grab the top 5% in avg dollar volume
    high_dollar_volume = dollar_volume.percentile_between(95, 100)

    # Combine the filters
    top_five_base_energy = base_energy & high_dollar_volume

    # 10 day mean close
    mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=10,
                                  mask=top_five_base_energy)

    # 30 day mean close
    mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=30,
                                  mask=top_five_base_energy)

    # Percent Difference
    percent_difference = (mean_10 - mean_30) / mean_30

    # List of Shorts
    shorts = percent_difference < 0

    # List of Longs
    longs = percent_difference > 0

    # Final Mask/Filter for anything in shorts or longs
    securities_to_trade = (shorts | longs)

    # Return Pipeline
    return Pipeline(columns={
        'longs': longs,
        'shorts': shorts,
        'perc_diff': percent_difference
    },
                    screen=securities_to_trade)
コード例 #17
0
ファイル: sentimentstrat.py プロジェクト: ajmal017/quantopian
def make_pipeline():
    sentiment_factor = sentiment.sentiment_signal.latest
    universe = (Q1500US() & sentiment_factor.notnull())

    sentiment_quantiles = sentiment_factor.rank(mask=universe,
                                                method='average').quantiles(2)

    pipe = Pipeline(columns={
        'sentiment': sentiment_factor,
        'longs': (sentiment_factor >= 4),
        'shorts': (sentiment_factor <= -2)
    },
                    screen=universe)
    return pipe
コード例 #18
0
def make_pipeline():
    # define our fundamental factor pipeline
    pipe = Pipeline()

    return_on_equity = Latest([Fundamentals.roe_af])
    reinvestment_rate = Fundamentals.reinvest_rate_af.latest
    momentum = Momentum()

    #do standardization
    return_on_equity = return_on_equity.zscore()
    reinvestment_rate = reinvestment_rate.zscore()
    momentum = momentum.zscore()
    total_z = 0.34 * return_on_equity + 0.16 * reinvestment_rate + 0.5 * momentum

    # we also get daily returns
    returns = Returns(window_length=2)

    # we compute a daily rank of both factors, this is used in the next step,
    # which is computing portfolio membership QTradableStocksUS
    total_z_rank = total_z.rank(mask=Q1500US())

    buy = total_z_rank.top(200)
    sell = total_z_rank.bottom(200)

    # Define our universe, screening out anything that isn't in the top or bottom 200
    universe = Q1500US() & (buy | sell)

    pipe = Pipeline(columns={
        'total_z': total_z,
        'Returns': returns,
        'total_z_rank': total_z_rank,
        'buy': buy,
        'sell': sell
    },
                    screen=universe)

    return pipe
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  
    """

    # Create a dollar volume factor.
    dollar_volume = AverageDollarVolume(window_length=1)
    # Pick the top 1% of stocks ranked by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(99, 100)
    pipe = Pipeline(
        # screen = (high_dollar_volume & Q500US()),
        screen=Q1500US(),
        columns={'dollar_volume': dollar_volume})
    return pipe
コード例 #20
0
def make_pipeline():

    # Base universe filter.
    base_universe = Q1500US()

    # Sector Classifier as Filter
    energy_sector = sector.eq(309)

    # Masking Base Energy Stocks
    base_energy = base_universe & energy_sector

    # Dollar volume factor
    dollar_volume = AverageDollarVolume(window_length=30)

    # Top half of dollar volume filter
    high_dollar_volume = dollar_volume.percentile_between(95, 100)

    # Final Filter Mask
    top_half_base_energy = base_energy & high_dollar_volume

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

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

    # Percent difference factor.
    percent_difference = (mean_10 - mean_30) / mean_30

    # Create a filter to select securities to short.
    shorts = percent_difference < 0

    # Create a filter to select securities to long.
    longs = percent_difference > 0

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

    return Pipeline(columns={
        'longs': longs,
        'shorts': shorts,
        'percent_diff': percent_difference
    },
                    screen=securities_to_trade)
コード例 #21
0
ファイル: Fondamentum.py プロジェクト: MVirdis/fondamentum
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
    """

    pipe = Pipeline(columns={
        'roe': Fundamentals.roe.latest,
        'roic': Fundamentals.roic.latest,
        'pb': MSFundamentals.pb_ratio.latest,
        'cap': Fundamentals.market_cap.latest,
        'close': USEquityPricing.close.latest
    },
                    screen=Q1500US())
    return pipe
コード例 #22
0
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()

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

    pipe = Pipeline(screen=base_universe, columns={
        'close': yesterday_close,
    })
    return pipe
コード例 #23
0
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 Q1500US.
    base_universe = Q1500US()
    # alpha_long_daily = AlphaLongDaily(
    #     inputs=[
    #         USEquityPricing.open,
    #         USEquityPricing.high,
    #         USEquityPricing.low,
    #         USEquityPricing.close
    #     ],
    #     window_length=1,
    #     mask=base_universe
    # )
    # alpha_long_weekly = AlphaLongWeekly(
    #     inputs=[
    #         USEquityPricing.open,
    #         USEquityPricing.high,
    #         USEquityPricing.low,
    #         USEquityPricing.close
    #     ],
    #     window_length=9,
    #     mask=base_universe
    # )
    volume_filter = VolumeFilter(inputs=[USEquityPricing.volume],
                                 window_length=1,
                                 mask=base_universe)

    # is_setup = volume_filter & alpha_long_weekly & alpha_long_daily

    daily_classifier = DailyClassifier(inputs=[
        USEquityPricing.open, USEquityPricing.high, USEquityPricing.low,
        USEquityPricing.close
    ],
                                       mask=volume_filter)

    pipe = Pipeline(screen=volume_filter & (daily_classifier > 0),
                    columns={
                        'daily_classifier': daily_classifier,
                        'daily_high': USEquityPricing.high.latest,
                        'daily_low': USEquityPricing.low.latest
                    })
    return pipe
コード例 #24
0
def make_pipeline():

    ev = EV()
    excessCash = morningstar.valuation.enterprise_value.latest < 0

    Earnings = EBITDA()
    isProfitable = morningstar.income_statement.ebitda.latest > 0

    universe = Q1500US() & excessCash & isProfitable
    longsUniverse = ev.top(25, mask=universe)

    tempEVMC = morningstar.valuation.enterprise_value.latest / morningstar.valuation.market_cap.latest
    evmc = tempEVMC < 0.5

    pipe = Pipeline(screen=longsUniverse, columns={'EVMC': evmc})

    return pipe
コード例 #25
0
def make_pipeline():

    ev = EV()
    excessCash = ev > 0

    EBITDA = PosEBITDA()
    isProfitable = EBITDA > 0

    universe = Q1500US() & excessCash & isProfitable
    longsUniverse = ev.top(10, mask=universe)

    pipe = Pipeline(screen=longsUniverse,
                    #columns = {
                    #    'close': yesterday_close,
                    #}
                    )
    return pipe
コード例 #26
0
def make_pipeline(context):

    # 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 = (
        Q1500US()  #QTradableStocksUS() 
        & 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

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

    return Pipeline(
        columns={'stocks_worst': stocks_worst},
        screen=stocks_worst,
    )
コード例 #27
0
def make_pipeline():

    # Sector
    sector = Sector()

    # Equity Filters
    mkt_cap_filter = morningstar.valuation.market_cap.latest >= 500000000
    price_filter = USEquityPricing.close.latest >= 5
    nan_filter = sentiment_free.sentiment_signal.latest.notnull()

    # Universe
    universe = Q1500US() & price_filter & mkt_cap_filter & nan_filter

    # Rank
    sentiment_signal = sentiment_free.sentiment_signal.latest
    sma_30 = SimpleMovingAverage(inputs=[sentiment_free.sentiment_signal],
                                 window_length=30,
                                 mask=universe)

    combined_rank = (sentiment_signal + sma_30.rank(mask=universe).zscore())

    # Long and Short Positions
    longs = combined_rank.top(NUM_LONG_POSITIONS)
    shorts = combined_rank.bottom(NUM_SHORT_POSITIONS)

    long_short_screen = (longs | shorts)

    # Bloomberg Beta Implementation
    beta = 0.66 * RollingLinearRegressionOfReturns(
        target=sid(8554),
        returns_length=5,
        regression_length=260,
        mask=long_short_screen).beta + 0.33 * 1.0

    pipe = Pipeline()
    pipe.add(longs, 'longs')
    pipe.add(shorts, 'shorts')
    pipe.add(combined_rank, 'combined_rank')
    pipe.add(sentiment_free.sentiment_signal.latest, 'sentiment_signal')
    pipe.add(sma_30, 'sma_30')
    pipe.add(sector, 'sector')
    pipe.add(beta, 'market_beta')
    pipe.set_screen(universe)

    return pipe
コード例 #28
0
def make_pipeline():
    
    ev = EV()
    excessCash = ev < 0
    
    Earnings = EBITDA()
    isProfitable = morningstar.income_statement.ebitda.latest > 0 
    
    universe = Q1500US() & excessCash & isProfitable
    longsUniverse = ev.top(5, mask=universe)
    
    pipe = Pipeline(
        screen = longsUniverse,
        #columns = {
        #    'close': yesterday_close,
        #}
    )
    return pipe
コード例 #29
0
def initialize(context):
    ## plugging in our factors into existing code
    testing_factor1 = operation_ratios.operation_margin.latest
    testing_factor2 = operation_ratios.revenue_growth.latest
    testing_factor3 = sentiment.sentiment_signal.latest
    
    universe = (Q1500US() & 
                testing_factor1.notnull() & 
                testing_factor2.notnull() & 
                testing_factor3.notnull())
    
    testing_factor1 = testing_factor1.rank(mask=universe, method='average')
    testing_factor2 = testing_factor2.rank(mask=universe, method='average')
    testing_factor3 = testing_factor3.rank(mask=universe, method='average')
    
    combined_alpha = testing_factor1 + testing_factor2 + testing_factor3
    
    testing_quantiles = combined_alpha.quantiles(2)

    # Schedule Tasks
    # --------------
    # Create and register a pipeline computing our combined alpha and a sector
    # code for every stock in our universe. We'll use these values in our 
    # optimization below.
    pipe = Pipeline(
        columns={
            'alpha': combined_alpha,
            'sector': Sector(),
        },
        # combined_alpha will be NaN for all stocks not in our universe,
        # but we also want to make sure that we have a sector code for everything
        # we trade.
        screen=combined_alpha.notnull() & Sector().notnull(),
    )
    algo.attach_pipeline(pipe, 'pipe')

    # Schedule a function, 'do_portfolio_construction', to run once a week
    # ten minutes after market open.
    algo.schedule_function(
        do_portfolio_construction,
        date_rule=algo.date_rules.week_start(),
        time_rule=algo.time_rules.market_open(minutes=MINUTES_AFTER_OPEN_TO_TRADE),
        half_days=False,
    )
コード例 #30
0
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
    """

    sentiment_factor = sentiment.sentiment_signal.latest
    universe = (Q1500US() & sentiment_factor.notnull())
    sentiment_quantiles = sentiment_factor.rank(
        mask=universe,
        method='average').quantiles(2)  # separate all stocks into 2 quantiles
    pipe = Pipeline(columns={
        'sentiment': sentiment_factor,
        'longs': (sentiment_factor >= 4),
        'shorts': (sentiment_factor <= 2)
    },
                    screen=universe)
    return pipe