Пример #1
0
def pipe_definition(context):
    context.stocks = symbols('DBA', 'DBC', 'DIA', 'EEM', 'EFA', 'EPP', 'EWA',
                             'EWJ', 'EWZ', 'FXF', 'FXI', 'GLD', 'IEV', 'ILF',
                             'IWM', 'IYR', 'MDY', 'QQQ', 'SPY', 'TLT', 'XLE',
                             'XLF')
    universe = Filters.StaticAssets(context.stocks)
    #universe = Fundamentals.total_revenue.latest.top(500)
    #universe = Q1500US()
    close_price = USEquityPricing.close.latest

    m3 = Returns(inputs=[USEquityPricing.close], window_length=67) * 100
    m6 = Returns(inputs=[USEquityPricing.close], window_length=137) * 100
    blend = m3 * 0.7 + m6 * 0.3
    sma_88 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                 window_length=89,
                                 mask=universe)

    return Pipeline(
        columns={
            'close_price': close_price,
            'm3': m3,
            'm6': m6,
            'blend': blend,
            'sma_88': sma_88,
        },
        screen=universe,
    )
Пример #2
0
def make_ml_pipeline(factors, universe, window_length=5, n_fwd_days=2):
    factors_pipe = OrderedDict()
    # Create returns over last n days.
    factors_pipe['Returns'] = Returns(inputs=[USEquityPricing.open],
                                      mask=universe,
                                      window_length=n_fwd_days)

    for i in [2, 3, 4, 5, 7, 10, 20, 60, 100, 250]:
        factors_pipe['Return' + str(i)] = Returns(
            inputs=[USEquityPricing.open], mask=universe, window_length=i)
    # Instantiate ranked factors
    for name, f in factors.iteritems():
        factors_pipe[name] = f().zscore(mask=universe)

    # Create our ML pipeline factor. The window_length will control how much
    # lookback the passed in data will have.
    factors_pipe['ML'] = ML(inputs=factors_pipe.values(),
                            window_length=window_length + 1,
                            mask=universe)
    factors_pipe['ML_zscore'] = factors_pipe['ML'].zscore(mask=universe)
    factors_pipe['ML_ranked'] = factors_pipe['ML'].rank(mask=universe)

    pipe = Pipeline(screen=universe, columns=factors_pipe)

    return pipe
Пример #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 QTradableStocksUS universe. For more detail, see this post:
    # https://www.quantopian.com/posts/working-on-our-best-universe-yet-qtradablestocksus
    universe = QTradableStocksUS()

    # Create a Returns factor with a 5-day lookback window for all
    # securities in our QTradableStocksUS 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():
    """
    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()

    # Base universe set to the Q1500US.
    base_universe = Q1500US()

    # Get returns of base universe stocks starting from 12 months ago (252 trading days ago).
    returns_12m = Returns(window_length=252, mask=base_universe)
    # Get returns of base universe stocks starting from 2 months ago (42 trading days ago).
    returns_2m = Returns(window_length=42, mask=base_universe)
    # Get returns of base universe stocks starting from 12 months and ending 2 months ago.
    returns_diff = returns_12m - returns_2m

    # Divide those returns into deciles.
    returns_diff_decile = returns_diff.deciles()

    # Filter to select securities to long
    longs = (returns_diff_decile.eq(9))
    pipe.add(longs, 'longs')

    # Filter to select securities to short
    shorts = (returns_diff_decile.eq(0))
    pipe.add(shorts, 'shorts')

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

    pipe.set_screen(securities_to_trade)

    return pipe
Пример #5
0
def before_trading_start(context, data):
    """
    Called every month before market open.
    """
    context.output = pipeline_output('my_pipeline')
    # Go long in securities for which the 'longs' value is True
    context.longs = context.output[context.output['longs']].index.tolist()
    # Go short in securities for which the 'shorts' value is True.
    context.shorts = context.output[context.output['shorts']].index.tolist()

    base_universe = Q1500US()
    returns_past_12_months = Returns(window_length=252, mask=base_universe)
    returns_past_2_months = Returns(window_length=42, mask=base_universe)
    returns_relevant = returns_past_12_months - returns_past_2_months
    returns_relevant_deciles = returns_relevant.deciles()
    longs = (returns_relevant_deciles.eq(9))
    shorts = (returns_relevant_deciles.eq(0))
    WML_returns = context.output['returns_relevant'][
        context.output['longs']].sum() - context.output['returns_relevant'][
            context.output['shorts']].sum()

    #std_dev = StdDev(inputs=[WML_returns], window_length=126)
    std_dev = np.std(WML_returns)

    if std_dev < 0.12:
        context.long_leverage, context.short_leverage = 0.5, -0.5
    else:
        context.long_leverage, context.short_leverage = .5 (
            .12 / std_dev), -.5 (.12 / std_dev)
Пример #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
Пример #7
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=filters.default_us_equity_universe_mask(minimum_market_cap=0))

    # 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.bottom(50)
    target_sector = context.sector.eq(101)

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

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

    return pipe
Пример #8
0
def make_pipeline():
    universe = QTradableStocksUS()

    # Variables Seleccionadas Del Dataframe de Fundamentals
    value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest
    working_capital = Fundamentals.working_capital.latest
    restricted_cash = Fundamentals.restricted_cash.latest
    cash_and_cash_equivalents = Fundamentals.cash_and_cash_equivalents.latest
    goodwill = Fundamentals.goodwill.latest
    capital_stock = Fundamentals.capital_stock.latest
    total_assets = Fundamentals.total_assets.latest
    common_stock = Fundamentals.common_stock.latest
    free_cash_flow = Fundamentals.free_cash_flow.latest
    recent_returns = Returns(window_length=RETURNS_LOOKBACK_DAYS,
                             mask=universe)

    # Winsorized - Variables (SIN ATIPICOS)
    value_winsorized = value.winsorize(min_percentile=0.05,
                                       max_percentile=0.95)
    working_capital = working_capital.winsorize(min_percentile=0.05,
                                                max_percentile=0.95)
    restricted_cash = restricted_cash.winsorize(min_percentile=0.05,
                                                max_percentile=0.95)
    cash_and_cash_equivalents = cash_and_cash_equivalents.winsorize(
        min_percentile=0.05, max_percentile=0.95)
    goodwill = goodwill.winsorize(min_percentile=0.05, max_percentile=0.95)
    capital_stock = capital_stock.winsorize(min_percentile=0.05,
                                            max_percentile=0.95)
    total_assets = total_assets.winsorize(min_percentile=0.05,
                                          max_percentile=0.95)
    common_stock = common_stock.winsorize(min_percentile=0.05,
                                          max_percentile=0.95)
    free_cash_flow = free_cash_flow.winsorize(min_percentile=0.05,
                                              max_percentile=0.95)
    recent_returns = recent_returns.winsorize(min_percentile=0.05,
                                              max_percentile=0.95)

    # FACTOR COMBINADO
    combined_factor = (
        value_winsorized.zscore() * 0.05 + working_capital.zscore() * 0.55 +
        restricted_cash.zscore() * 0.2 +
        cash_and_cash_equivalents.zscore() * 0.01 + goodwill.zscore() * 0.01 +
        capital_stock.zscore() * 0.1 + total_assets.zscore() * 0.01 +
        common_stock.zscore() * 0.01 + free_cash_flow.zscore() * 0.01 +
        recent_returns.zscore() * 0.05)

    longs = combined_factor.top(TOTAL_POSITIONS // 2, mask=universe)
    shorts = combined_factor.bottom(TOTAL_POSITIONS // 2, mask=universe)

    long_short_screen = (longs | shorts)

    pipe = Pipeline(columns={
        'longs': longs,
        'shorts': shorts,
        'combined_factor': combined_factor
    },
                    screen=long_short_screen)
    return pipe
Пример #9
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.
    
    In particular, this function can be copy/pasted into research and run by itself.
    """

    # Basic momentum metrics.
    cross_momentum = CrossSectionalMomentum()

    abs_momentum = Returns(inputs=[USEquityPricing.close], window_length=252)

    # We only want to trade relatively liquid stocks.
    # Build a filter that only passes stocks that have $10,000,000 average
    # daily dollar volume over the last 20 days.
    dollar_volume = AverageDollarVolume(window_length=20)
    is_liquid = (dollar_volume > 1e7)

    # We also don't want to trade penny stocks, which we define as any stock with an
    # average price of less than $5.00 over the last 200 days.
    sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=200)
    not_a_penny_stock = (sma_200 > 5)

    # Before we do any other ranking, we want to throw away the bad assets.
    initial_screen = (is_liquid & not_a_penny_stock)

    # 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 passed `initial_screen`.
    combined_rank = (cross_momentum.rank(mask=initial_screen) +
                     abs_momentum.rank(mask=initial_screen))

    # Build Filters representing the top and bottom 5% of stocks by our combined ranking system.
    # We'll use these as our tradeable universe each day.
    longs = combined_rank.percentile_between(95, 100)
    shorts = combined_rank.percentile_between(0, 5)

    # The final output of our pipeline should only include
    # the top/bottom 5% of stocks by our criteria.
    pipe_screen = (longs | shorts)

    pipe_columns = {
        'longs': longs,
        'shorts': shorts,
        'combined_rank': combined_rank,
        'abs_momentum': abs_momentum,
        'cross_momentum': cross_momentum
    }

    # Create pipe
    pipe = Pipeline(columns=pipe_columns, screen=pipe_screen)
    return pipe
Пример #10
0
def initialize(context):

    # UNIVERSE DECLARATION
    universe = QTradableStocksUS()

    # ATTACH PIPELINE NAME
    pipe = Pipeline(screen=universe)
    attach_pipeline(pipe, 'my pipe')

    # ADD SECTOR TO THE PIPELINE
    sector = Fundamentals.morningstar_sector_code.latest
    pipe.add(sector, 'sector')

    # ADD MONTHLY RETURN FACTOR AND RANKED RETURN FACTOR
    monthly_return = Returns(window_length=21)
    monthly_rank = monthly_return.rank(mask=universe)
    pipe.add(monthly_return, 'Mreturn')
    pipe.add(monthly_rank, 'Mrank')

    # ADD CUMULATIVE MONTHLY RETURNS TO THE PIPELINE
    prod_return = np.prod(monthly_return)
    pipe.add(prod_return, 'prodReturn')

    # DEFINE OUR PRE-FILTERED LONG AND SHORT LISTS
    longs = (prod_return > 0)
    pipe.add(longs, 'longs')

    # SETTINGS
    #----------

    # SCHEDULE SETTINGS FOR THE 'REBALANCE' FUNCTION
    schedule_function(func=rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(),
                      half_days=True)

    # SCHEDULE SETTINGS FOR THE 'RECORD VARS' FUNCTION
    schedule_function(func=record_vars,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(),
                      half_days=True)

    # LEVERAGE SETTINGS (CAN BE ADJUSTED)
    context.long_leverage = 0.5
    context.short_leverage = -0.5

    # SLIPPAGE SETTINGS (CAN BE ADJUSTED - DEFAULT)
    set_slippage(us_equities=slippage.FixedBasisPointsSlippage(
        basis_points=5, volume_limit=0.1))

    # COMMISSION SETTINGS (CAN BE ADJUSTED - SET TO INTERACTIVE BROKERS COMMISSION PRICING)
    set_commission(
        us_equities=commission.PerShare(cost=0.005, min_trade_cost=1))
Пример #11
0
def make_pipeline(context):

    universe = QTradableStocksUS()

    # Mean Average Multiplier calculation
    mean_close_50 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=50,
                                        mask=universe)
    mean_close_200 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                         window_length=200,
                                         mask=universe)

    mean_average_multiplier = mean_close_200 / mean_close_50

    #Sentiment Score calculation
    bull_m_bear = (SimpleMovingAverage(inputs=[stocktwits.bull_minus_bear],
                                       window_length=RETURNS_LOOKBACK_DAYS,
                                       mask=universe))
    total_messages = (SimpleMovingAverage(
        inputs=[stocktwits.total_scanned_messages],
        window_length=RETURNS_LOOKBACK_DAYS,
        mask=universe))

    sentiment_score = total_messages / (bull_m_bear)
    sentiment_score_winsorized = sentiment_score.winsorize(min_percentile=0.01,
                                                           max_percentile=0.95,
                                                           mask=universe)

    #Returns with lookback calculations
    recent_returns = Returns(window_length=RETURNS_LOOKBACK_DAYS,
                             mask=universe)
    recent_returns_zscore = recent_returns.zscore()

    #Universe and low-high calculations
    low_returns = recent_returns_zscore.percentile_between(0,
                                                           25,
                                                           mask=universe)
    high_returns = recent_returns_zscore.percentile_between(75,
                                                            100,
                                                            mask=universe)

    securities_to_trade = (low_returns | high_returns) & universe

    #Total score calculation
    total_score = sentiment_score_winsorized * recent_returns_zscore * mean_average_multiplier

    pipe = Pipeline(columns={
        'total_score': total_score,
    },
                    screen=securities_to_trade)

    return pipe
Пример #12
0
def make_pipeline(context):
    """
    A function to create our dynamic stock selector (pipeline). Documentation on
    pipeline can be found here: https://www.quantopian.com/help#pipeline-title
    """
    primary = Q500US()  # IsPrimaryShare()
    sma7 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=7)
    sma3 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=3)
    sma21 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=21)

    above_10 = sma3 > 10

    #dollar_volume = AverageDollarVolume(window_length=60)
    #high_dollar_volume = dollar_volume.percentile_between(85, 100,mask = above_10 & primary)

    smaRatio = sma7 / sma21

    sma_rank = smaRatio.rank()

    shorts = sma_rank.percentile_between(90, 100)

    longs = sma_rank.percentile_between(0, 10)

    # Create a dollar volume factor.

    # Pick the top 1% of stocks ranked by dollar volume.

    #high_dollar_volume = high_dollar_volume & primary
    morn_cyc = SuperSector()
    Close = USEquityPricing.close.latest

    returns = Returns(window_length=10)
    returns_slice = returns[sid(8554)]
    spy_correlations = returns.pearsonr(target=returns_slice,
                                        correlation_length=30)
    LowBeta = (spy_correlations >= -0.39) & (spy_correlations <= 0.39)
    #LowBeta1 = spy_correla

    pipe = Pipeline(
        screen=primary & above_10,
        columns={
            #'dollar_volume': dollar_volume,
            'longs': longs,
            'shorts': shorts,
            'sma_rank': sma_rank,
            'ratioCy': smaRatio,
            'SpyCor': LowBeta,
            'Q500': Q500US(),
            'Close': Close
        })
    return pipe
Пример #13
0
def make_pipeline(context):
    # Use a universe of just the top 500 US stocks
    universe = Q500US()
    sector = Sector()

    # Determine if the market is trending up or down. If the market is trending down then just buy bonds. If it is trending up then buy stocks
    # This is not an optimal solution and will obviously not work in all future market crashes
    spy_ma_fast_slice = SMA(
        inputs=[USEquityPricing.close],
        window_length=context.TF_FAST_LOOKBACK)[context.SPY]
    spy_ma_slow_slice = SMA(
        inputs=[USEquityPricing.close],
        window_length=context.TF_SLOW_LOOKBACK)[context.SPY]
    spy_ma_fast = SMA(inputs=[spy_ma_fast_slice], window_length=1)
    spy_ma_slow = SMA(inputs=[spy_ma_slow_slice], window_length=1)
    # If the 100 moving average crosses the 10 then alter the trend up variable
    trend_up = spy_ma_fast > spy_ma_slow

    # Get simple factors to determine "quality" companies
    cash_return = ms.cash_return.latest.rank(mask=universe)
    fcf_yield = ms.fcf_yield.latest.rank(mask=universe)
    roic = ms.roic.latest.rank(mask=universe)
    rev_growth = ms.revenue_growth.latest.rank(mask=universe)

    value = (cash_return + fcf_yield).rank(mask=universe)

    # Find sentiment rank using https://www.quantopian.com/posts/sentiment-as-a-factor
    sentiment_score = SMA(
        inputs=[sentiment.sentiment_signal],
        window_length=30,
    )
    sentiment_score_zscore = sentiment_score.zscore()
    sentiment_overall_rank = sentiment_score_zscore.rank(
        mask=universe, groupby=sector).demean()

    # Combine factors to create one single ranking system
    quality = roic + rev_growth + value + sentiment_overall_rank

    # Create a 'momentum' factor by looking back over the last 140 days (20 weeks).
    momentum = Returns(window_length=context.MOMENTUM_LOOKBACK_DAYS)

    # Filters for top quality and momentum to use in the selection criteria
    top_quality = quality.top(context.TOP_ROE_QTY, mask=universe)
    top_quality_momentum = momentum.top(context.TARGET_SECURITIES,
                                        mask=top_quality)
    # Only return values to be used in the selection criteria by using the screen parameter
    pipe = Pipeline(columns={
        'trend_up': trend_up,
        'top_quality_momentum': top_quality_momentum,
    },
                    screen=top_quality_momentum)
    return pipe
Пример #14
0
def make_pipeline(context):
    """
    A function to create our pipeline (dynamic security selector). The pipeline is used
    to rank securities based on different factors, including builtin facotrs, or custom 
    factors that you can define. Documentation on pipeline can be found here:
        https://www.quantopian.com/help#pipeline-title
    """

    # Create a pipeline object.
    pipe = Pipeline()

    # Create a dollar_volume factor using default inputs and window_length.
    # This is a builtin factor.
    dollar_volume = AverageDollarVolume(window_length=1)
    pipe.add(dollar_volume, 'dollar_volume')

    # Create a recent_returns factor with a 5-day returns lookback. This is
    # a custom factor defined below (see RecentReturns class).
    recent_returns = Returns(window_length=context.returns_lookback)
    pipe.add(recent_returns, 'recent_returns')

    # Define high dollar-volume filter to be the top 5% of securities by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(95, 100)

    # 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,
                                                    mask=high_dollar_volume)
    high_returns = recent_returns.percentile_between(90,
                                                     100,
                                                     mask=high_dollar_volume)

    # Factors return a scalar value for each security in the entire universe
    # of securities. Here, we add the recent_returns rank factor to our pipeline
    # and we provide it with a mask such that securities that do not pass the mask
    # (i.e. do not have high dollar-volume), are not considered in the ranking.
    pipe.add(recent_returns.rank(mask=high_dollar_volume),
             'recent_returns_rank')

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

    # Add the low_returns and high_returns filters as columns to the pipeline so
    # that when we refer to securities remaining in our pipeline later, we know
    # which ones belong to which category.
    pipe.add(low_returns, 'low_returns')
    pipe.add(high_returns, 'high_returns')

    return pipe
def make_pipeline(context):
    mask = Q500US()
    #lb_13 = -Returns(window_length=13, mask=mask)

    weekly_return = Returns(window_length=6, mask=mask)
    pipe = Pipeline(
        columns={
            'weekly_return': weekly_return,
            '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=weekly_return.notnull() & Sector().notnull(),
    )
    return pipe
Пример #16
0
def make_ml_pipeline(universe, window_length=126, n_forward_days=21):
    pipeline_columns = OrderedDict()

    # ensure that returns is the first input
    pipeline_columns['Returns'] = Returns(
        inputs=(USEquityPricing.open,),
        mask=universe, window_length=n_forward_days + 1,
    )

    # rank all the factors and put them after returns
    pipeline_columns.update({
        k: v().zscore(mask=universe) for k, v in features.items()
    })

    # Create our ML pipeline factor. The window_length will control how much
    # lookback the passed in data will have.
    pipeline_columns['ML'] = ML(
        inputs=pipeline_columns.values(),
        window_length=window_length + 1,
        mask=universe,
    )

    pipeline_columns['Sector'] = Sector()

    return Pipeline(screen=universe, columns=pipeline_columns)
Пример #17
0
def make_pipeline2():
    pipe = Pipeline()
    '''standards'''
    book_to_price = 1 / Latest([Fundamentals.pb_ratio])
    PE = Latest([Fundamentals.pe_ratio])
    #research_and_development = Latest([Fundamentals.research_and_development])
    gross_dividend_payment = Latest([Fundamentals.gross_dividend_payment])
    value_score = Latest([Fundamentals.value_score])
    returns = Returns(inputs=[USEquityPricing.close], window_length=2)
    growth_score = Latest([Fundamentals.growth_score])
    profit_grade = Fundamentals.profitability_grade.latest
    financial_health_grade = Fundamentals.financial_health_grade.latest
    '''filter'''
    #profit_requirement = (profit_grade=='A') | (profit_grade=='B')
    mask = QTradableStocksUS()
    mask &= Sector().eq(sector)
    #mask &= value_score > 30
    mask &= PE < 35
    mask &= USEquityPricing.volume.latest > 10000
    '''pipeline'''
    pipe = Pipeline(columns={
        'Returns': returns,
        'B/P': book_to_price,
        'P/E': PE,
        'Dividends': gross_dividend_payment,
        'Value Score': value_score,
        'Growth_Score': growth_score,
        'Profit_Grade': profit_grade,
        'Financial_Health': financial_health_grade
    },
                    screen=mask)
    return pipe
Пример #18
0
def make_fundamentals_pipeline():
    
    base_universe  = StaticAssets([asset])
    
    #Fundamentals
    returns = Returns(window_length=2)
    pe_ratio = Fundamentals.pe_ratio.latest
    current_assets = Fundamentals.current_assets.latest
    current_debt = Fundamentals.current_debt.latest
    enterprise_value = Fundamentals.enterprise_value.latest
    eps_earnings = Fundamentals.basic_eps_earnings_reports.latest
    avg_earnings = Fundamentals.basic_average_shares_earnings_reports.latest
    accrued_expenses = Fundamentals.current_accrued_expenses.latest
    current_liabilities = Fundamentals.current_liabilities.latest

    return Pipeline(
        screen = base_universe,
        columns={
            'daily_returns': returns,
            'pe_ratio': pe_ratio,
            'current_assets' : current_assets,
            'current_debt' : current_debt,
            'eps_earnings' : eps_earnings,
            'enterprise_value' : enterprise_value,
            'avg_earnings' : avg_earnings,
            'accrued_exspenses' : accrued_expenses,
            'liabilities' : current_liabilities})
Пример #19
0
class Momentum(CustomFactor):

    inputs = [Returns(window_length=10)]
    window_length = 10

    def compute(self, today, assets, out, lag_returns):
        out[:] = lag_returns[0]
Пример #20
0
    class Mean_Reversion_1M(CustomFactor):
        inputs = [Returns(window_length=21)]
        window_length = 252

        def compute(self, today, assets, out, monthly_rets):
            out[:] = (monthly_rets[-1] - np.nanmean(
                monthly_rets, axis=0)) / np.nanstd(monthly_rets, axis=0)
Пример #21
0
def make_pipeline():
    # get factors
    mktcap = Fundamentals.market_cap.latest
    price_close = USEquityPricing.close.latest

    # get factors, higher is better
    roe = Fundamentals.roe.latest
    fcf_yield = Fundamentals.fcf_yield.latest
    ret_20 = Returns(window_length=20)

    # compare built-in valuation ratio with manually calculated
    price_close = USEquityPricing.close.latest
    fcf_per_share = Fundamentals.fcf_per_share.latest
    fcf_yield_manual = fcf_per_share / price_close

    # get ranks, masked by the universe, higher is better
    quality = roe.rank(method='average', mask=min_liq_univ())
    value = fcf_yield.rank(method='average', mask=min_liq_univ())
    momentum = ret_20.rank(method='average', mask=min_liq_univ())

    # combine ranks
    qvm = (quality + value + momentum).rank(method='average',
                                            mask=min_liq_univ())

    # Sort into 10 deciles
    num_quantiles = 10
    qvm_quantiles = qvm.quantiles(num_quantiles, mask=min_liq_univ())
    long_decile = qvm_quantiles.eq(num_quantiles - 1)
    short_decile = qvm_quantiles.eq(0)

    # Get top 10 and bottom 10 stocks by rank
    long_10 = qvm.top(10, mask=min_liq_univ())
    short_10 = qvm.bottom(10, mask=min_liq_univ())

    return Pipeline(columns={
        'mktcap': mktcap,
        'fcf_yield': fcf_yield,
        'fcf_yield_manual': fcf_yield_manual,
        'roe': roe,
        'ret_20': ret_20,
        'quality': quality,
        'value': value,
        'momentum': momentum,
        'qvm': qvm,
        'long_10': long_10
    },
                    screen=min_liq_univ())
Пример #22
0
class aa_momentum(CustomFactor):
    """ Alpha Architect - Momentum factor """
    inputs = [USEquityPricing.close,
    Returns(window_length=126)]
    window_length = 252
    def compute(self, today, assets, out, prices, returns):  
            out[:] = ((prices[-21] - prices[-252])/prices[-252] -  
                      (prices[-1] - prices[-21])/prices[-21]) / np.nanstd(returns, axis=0)
Пример #23
0
def make_pipeline(context):
    """
    A function to create our pipeline (dynamic security selector). The pipeline is used
    to rank securities based on different factors, including builtin facotrs, or custom 
    factors that you can define. Documentation on pipeline can be found here:
        https://www.quantopian.com/help#pipeline-title
    """
    
    # Create a pipeline object. 
    pipe = Pipeline()
    
    # Create a dollar_volume factor using default inputs and window_length.
    # This is a builtin factor.
    dollar_volume = AverageDollarVolume(window_length=1)
    pipe.add(dollar_volume, 'dollar_volume')
    
    # Create a recent_returns factor with a 5-day returns lookback. This is
    # a custom factor defined below (see RecentReturns class).
    recent_returns = Returns(window_length=context.returns_lookback)
    pipe.add(recent_returns, 'recent_returns')
    
    # Define high dollar-volume filter to be the top 5% of securities by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(95, 100)
    
    # 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,mask=high_dollar_volume)
    high_returns = recent_returns.percentile_between(90,100,mask=high_dollar_volume)
    
    # Factors return a scalar value for each security in the entire universe
    # of securities. Here, we add the recent_returns rank factor to our pipeline
    # and we provide it with a mask such that securities that do not pass the mask
    # (i.e. do not have high dollar-volume), are not considered in the ranking.
    pipe.add(recent_returns.rank(mask=high_dollar_volume), 'recent_returns_rank')
    
    # Add a filter to the pipeline such that only high-return and low-return
    # securities are kept.
    pipe.set_screen(low_returns | high_returns)
    
    # Add the low_returns and high_returns filters as columns to the pipeline so
    # that when we refer to securities remaining in our pipeline later, we know
    # which ones belong to which category.
    pipe.add(low_returns, 'low_returns')
    pipe.add(high_returns, 'high_returns')
    
    return pipe
Пример #24
0
class Returns(CustomFactor):
    """Equity Momentum"""

    inputs = [Returns(window_length=20)]
    window_length = 2

    def compute(self, today, assets, out, ret):
        out[:] = ret[0]
Пример #25
0
    class PercentChange(CustomFactor):
        """ Momentum factor """
        inputs = [USEquityPricing.close, Returns(window_length=126)]
        window_length = 252

        def compute(self, today, assets, out, prices, returns):
            out[:] = ((prices[-1] - prices[-21]) / prices[-21]) / np.nanstd(
                returns, axis=0)
Пример #26
0
def make_pipeline(context):
    """
    A function that creates and returns our pipeline.
    We break this piece of logic out into its own function to make it easier to
    test and modify in isolation. In particular, this function can be
    copy/pasted into research and run by itself.
    Parameters
    -------
    context : AlgorithmContext
        See description above.
    Returns
    -------
    pipe : Pipeline
        Represents computation we would like to perform on the assets that make
        it through the pipeline screen.
    """

    # Filter for stocks in the QTradableStocksUS universe. For more detail, see
    # the documentation:
    # https://www.quantopian.com/help#quantopian_pipeline_filters_QTradableStocksUS
    universe = QTradableStocksUS()

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

    # Turn our recent_returns factor into a z-score factor to normalize the results.
    recent_returns_zscore = recent_returns.zscore()

    # Define high and low returns filters to be the bottom 10% and top 10% of
    # securities in the QTradableStocksUS.
    low_returns = recent_returns_zscore.percentile_between(0, 10)
    high_returns = recent_returns_zscore.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 to computes the recent_returns_zscore for securities
    # in the top 10% and bottom 10% (ranked by recent_returns_zscore) every day.
    pipe = Pipeline(columns={'recent_returns_zscore': recent_returns_zscore},
                    screen=securities_to_trade)

    return pipe
Пример #27
0
    class OBV(CustomFactor):
        inputs = [Returns(window_length=21)]
        window_length = 21

        def compute(self, today, assets, out, vol):
            prevDay = vol[-21]
            current = vol[-1]

            out[:] = (prevDay - current) / prevDay
class Downside_Volatility(CustomFactor):
    # Use returns as the input
    inputs = [Returns(window_length=2)]
    window_length = 10

    def compute(self, today, assets, out, returns):
        # set any returns greater than 0 to NaN so they are excluded from our calculations
        returns[returns > 0] = np.nan
        out[:] = np.nanstd(returns, axis=0)
class Momentum(CustomFactor):
    """ Conventional Momentum factor """
    inputs = [USEquityPricing.close, Returns(window_length=126)]
    window_length = 252

    # /np.nanstd(returns, axis=0)
    def compute(self, today, assets, out, prices, returns):
        out[:] = ((prices[-21] - prices[-252]) / prices[-252] -
                  (prices[-1] - prices[-21]) / prices[-21])
Пример #30
0
class MeanReversion1M(CustomFactor):
    inputs = (Returns(window_length=21),)
    window_length = 252

    def compute(self, today, assets, out, monthly_rets):
        np.divide(
            monthly_rets[-1] - np.nanmean(monthly_rets, axis=0),
            np.nanstd(monthly_rets, axis=0),
            out=out,
        )
Пример #31
0
def Asset_Growth_3M():
    """
    3-month Asset Growth:
    Increase in total assets over 3 months
    https://www.pnc.com/content/dam/pnc-com/pdf/personal/wealth-investments/WhitePapers/FactorAnalysisFeb2014.pdf # NOQA
    Notes:
    High value represents good financial health as quantity of
    assets is increasing
    """
    return Returns(inputs=[bs.total_assets], window_length=63)