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
    """
    
    rsi_filter = SidInList(sid_list = context.stock_traded.sid)
    
    close = Latest(
        inputs = [USEquityPricing.close],
        mask = rsi_filter,
    )
    
    rsi_9 = RSI(
        inputs = [USEquityPricing.close],
        window_length = 9,
        mask = rsi_filter,
    )
     
    pipe = Pipeline()
    
    pipe.add(close, 'close')
    pipe.add(rsi_9, 'rsi_9')
    
    pipe.set_screen(rsi_filter)
    
    return pipe
def my_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
    """
    pipe = Pipeline()
    
    # span stands for past 120 days, need doulbe window length to get 120 data point.
    ewma120 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_long, span=context.look_back_long)
    pipe.add(ewma120, "ewma120")
    ewma60 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_middle, span=context.look_back_middle)
    pipe.add(ewma60, "ewma60")
    ewma15 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_short, span=context.look_back_short)
    pipe.add(ewma15, "ewma15")
    
    pipe.add(Latest(inputs=[USEquityPricing.close]), "yes_price")

    momentum = (ewma120 - ewma60).abs() + (ewma60 - ewma15).abs()
    
    middle_momentum = momentum.percentile_between(0, 5)
    
    # Create a dollar volume factor.
    dollar_volume = AverageDollarVolume(window_length=1, mask=middle_momentum)
    pipe.add(dollar_volume, 'dollar_volume')
 
    # Pick the top 10% of stocks ranked by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(90, 100)
    pipe.set_screen(high_dollar_volume)

    return pipe
def make_pipeline():

    pipe = Pipeline()

    # Set the universe to the QTradableStocksUS & stocks with Sector and Top 2000 by MarketCap
    universe = MarketCap().top(2000, mask = QTradableStocksUS()) & Sector().notnull()

    #filter more with momentum and volarility filter(lowest 600 volatility stocks)

    momentum = Momentum()

    volatility = Volatility()

    volatility_rank = volatility.rank(mask=universe, ascending=True)

    pipe.set_screen(universe  & (volatility_rank.top(600)) & (momentum>1))

    # Creating Price_to_book,Price_to_earnings, and return_on_assets, return_on_Equity, Return on Invested Capital Objects, and Dividend_yield Object and Rank them

    #Create Price to book and Price to Earning and rank them, the lower the ratio, the better
    pb = Price_to_Book()
    pb_rank = pb.rank(mask=universe, ascending=True)

    pe = Price_to_Earnings()
    pe_rank = pe.rank(mask=universe, ascending=True)

    #Create Return on Assets, Return on Equity, Return on Invested Capital and Dividend Yield Class and rank them,the higher the ratio, the better
    roa = Return_on_Assets()
    roa_rank = roa.rank(mask=universe, ascending=False)

    roe = Return_on_Equity()
    roe_rank = roe.rank(mask=universe, ascending=False)

    roic = Return_on_Invested_Capital()
    roic_rank = roic.rank(mask=universe, ascending=False)

    earnings_yield = Earnings_Yield()
    EY_rank   = earnings_yield.rank(ascending=False, mask=universe)


    dy = Dividend_Yield()
    dy_rank = dy.rank(mask=universe, ascending=False)


    #Give 1 weight forall metrics such as P/e,P/B,Dividend Yield,Return on Assets,Equity and Invested Capital
    the_ranking_score = (pb_rank+pe_rank+dy_rank+roa_rank+roe_rank+roic_rank*2 + EY_rank)/8

    # Rank the combo_raw and add that to the pipeline
    pipe.add(the_ranking_score.rank(mask=universe), 'ranking_score')

    return pipe
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
Exemple #5
0
def initialize(context):
    set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.00))
    schedule_function(func=rebalance,
                      date_rule=date_rules.month_start(days_offset=5),
                      time_rule=time_rules.market_open(),
                      half_days=True)
    schedule_function(close_orders,
                      date_rule=date_rules.week_end(),
                      time_rule=time_rules.market_close())
    set_do_not_order_list(security_lists.leveraged_etf_list)
    context.acc_leverage = 1.00
    context.holdings = 10
    context.profit_taking_factor = 0.01
    context.profit_target = {}
    context.profit_taken = {}
    context.entry_date = {}
    context.stop_pct = 0.75
    context.stop_price = defaultdict(lambda: 0)

    pipe = Pipeline()
    attach_pipeline(pipe, 'ranked_stocks')

    factor1 = momentum_factor_1()
    pipe.add(factor1, 'factor_1')
    factor2 = momentum_factor_2()
    pipe.add(factor2, 'factor_2')
    factor3 = momentum_factor_3()
    pipe.add(factor3, 'factor_3')
    factor4 = momentum_factor_4()
    pipe.add(factor4, 'factor_4')
    factor5 = efficiency_ratio()
    pipe.add(factor5, 'factor_5')

    mkt_screen = market_cap()
    stocks = mkt_screen.top(3000)
    factor_5_filter = factor5 > 0.031
    total_filter = (stocks & factor_5_filter)
    pipe.set_screen(total_filter)

    factor1_rank = factor1.rank(mask=total_filter, ascending=False)
    pipe.add(factor1_rank, 'f1_rank')
    factor2_rank = factor2.rank(mask=total_filter, ascending=False)
    pipe.add(factor2_rank, 'f2_rank')
    factor3_rank = factor3.rank(mask=total_filter, ascending=False)
    pipe.add(factor3_rank, 'f3_rank')
    factor4_rank = factor4.rank(mask=total_filter, ascending=False)
    pipe.add(factor4_rank, 'f4_rank')

    combo_raw = (factor1_rank + factor2_rank + factor3_rank + factor4_rank) / 4
    pipe.add(combo_raw, 'combo_raw')
    pipe.add(combo_raw.rank(mask=total_filter), 'combo_rank')
def high_dollar_volume_pipeline():
    
    # Create a pipeline object. 
    pipe = Pipeline()
    
    # Create a factor for average dollar volume over the last 63 day (1 quarter equivalent).
    dollar_volume = AverageDollarVolume(window_length=63)
    pipe.add(dollar_volume, 'dollar_volume')
    
    # Define high dollar-volume filter to be the top 5% of stocks by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(95, 100)
    pipe.set_screen(high_dollar_volume)
    
    return pipe
Exemple #7
0
def initialize(context):

    # how many days to look back volatility and returns
    context.lookback = 3 * 252  # 3 years
    context.long_leverage = 1.0

    #set_benchmark(sid(41382)) #SPLV

    pipe = Pipeline()
    attach_pipeline(pipe, 'lvhy')

    # This is an approximation of the S&P 500
    top_500 = Q500US()  # Q1500US()

    volatility = Volatility(window_length=context.lookback)
    pipe.add(volatility, 'volatility')

    # Rank factor 1 and add the rank to our pipeline
    volatility_rank = volatility.rank(mask=top_500)
    pipe.add(volatility_rank, 'volatility_rank')

    syield = Yield()
    pipe.add(syield, 'yield')

    # Rank factor 2 and add the rank to our pipeline
    yield_rank = syield.rank(mask=top_500)
    pipe.add(yield_rank, 'yield_rank')

    # Take the average of the two factor rankings, add this to the pipeline
    combo_raw = (volatility_rank + yield_rank) / 2
    pipe.add(combo_raw, 'combo_raw')

    # Rank the combo_raw and add that to the pipeline
    pipe.add(combo_raw.rank(mask=top_500), 'combo_rank')

    # Set a screen to capture max top 100 best stocks
    pipe.set_screen(top_500)

    # 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)
def Custom_pipeline(context):
    pipe = Pipeline()

    # Get bull/bearish data and sentiment data and store window length differences in different variables
    sma_bear_7 = SimpleMovingAverage(inputs=[st.bearish_intensity],
                                     window_length=7)
    sma_bull_7 = SimpleMovingAverage(inputs=[st.bullish_intensity],
                                     window_length=7)
    sma_bear_6 = SimpleMovingAverage(inputs=[st.bearish_intensity],
                                     window_length=6)
    sma_bull_6 = SimpleMovingAverage(inputs=[st.bullish_intensity],
                                     window_length=6)
    sma_bear_5 = SimpleMovingAverage(inputs=[st.bearish_intensity],
                                     window_length=5)
    sma_bull_5 = SimpleMovingAverage(inputs=[st.bullish_intensity],
                                     window_length=5)
    sma_bear_4 = SimpleMovingAverage(inputs=[st.bearish_intensity],
                                     window_length=4)
    sma_bull_4 = SimpleMovingAverage(inputs=[st.bullish_intensity],
                                     window_length=4)
    sma_bear_3 = SimpleMovingAverage(inputs=[st.bearish_intensity],
                                     window_length=3)
    sma_bull_3 = SimpleMovingAverage(inputs=[st.bullish_intensity],
                                     window_length=3)
    sma_bear_2 = SimpleMovingAverage(inputs=[st.bearish_intensity],
                                     window_length=2)
    sma_bull_2 = SimpleMovingAverage(inputs=[st.bullish_intensity],
                                     window_length=2)
    bull_1 = st.bullish_intensity.latest
    bear_1 = st.bearish_intensity.latest
    volume = USEquityPricing.volume
    pipe.add(st.bullish_intensity.latest, 'bullish_intensity')
    pipe.add(st.bearish_intensity.latest, 'bearish_intensity')
    pipe.add(st.total_scanned_messages.latest, 'total_scanned_messages')

    total_scan = st.total_scanned_messages.latest
    pricing = USEquityPricing.close.latest

    # Conditionals for determining stocks to screen
    price_range = 1.00 < pricing < 12.50
    min_volume = volume > 4000000
    total_scans = total_scan >= 10
    bull_condition = bull_1 > sma_bull_2 < sma_bull_3 < sma_bull_4 < sma_bull_5 < sma_bull_6 > 0
    bull_latest = bull_1 > 0

    # Set stock screener
    pipe.set_screen(price_range & min_volume & total_scans & bull_condition
                    & bull_latest)
    return pipe
Exemple #9
0
def Custom_pipeline(context):
    pipe = Pipeline()
    sma_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                 window_length=10)
    sma_50 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                 window_length=50)
    pipe.add(st.bull_scored_messages.latest, 'bull_scored_messages')
    pipe.add(st.bear_scored_messages.latest, 'bear_scored_messages')

    #changed to be easier to read.
    pipe.set_screen(Q500US() & (sma_10 > sma_50)
                    & ((0.35 * st.bull_scored_messages.latest) >
                       (st.bear_scored_messages.latest))
                    & (st.bear_scored_messages.latest > 10))
    return pipe
Exemple #10
0
def make_pipeline(context):
    pipe = Pipeline()
    base_universe = QTradableStocksUS()
    dollar_volume = AverageDollarVolume(window_length=30)
    high_dollar_volume = dollar_volume.percentile_between(98, 100)

    close_day_before_yeseterday = ValueDaybeforeYesterday(
        inputs=[USEquityPricing.close])
    volume_day_before_yeseterday = ValueDaybeforeYesterday(
        inputs=[USEquityPricing.volume])
    pipe.add(close_day_before_yeseterday, "close_day_before_yeseterday")

    my_screen = base_universe & high_dollar_volume
    pipe.set_screen(my_screen)
    return pipe
Exemple #11
0
def make_pipeline():

    pipe = Pipeline()

    _50ma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=50)
    _200ma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                 window_length=200)

    pipe.add(_50ma, '_50ma')
    pipe.add(_200ma, '_200ma')
    pipe.add(_50ma / _200ma, 'ma_ratio')
    pipe.set_screen(_50ma / _200ma > 1.0)

    return pipe
def initialize(context):
    log.info("here")
    context.x = 100

    # Create, register and name a pipeline in initialize.
    pipe = Pipeline()
    attach_pipeline(pipe, 'example')

    # Construct a simple moving average factor and add it to the pipeline.
    simple_return = Returns(inputs=[USEquityPricing.close], window_length=365)
    pipe.add(simple_return, 'simple_return')

    # Set a screen on the pipelines to filter out securities.
    pipe.set_screen(simple_return > 1.0)
    
    schedule_function(func=rebalance, date_rule = date_rules.every_day(), time_rule = time_rules.market_open(hours = 1))
Exemple #13
0
def initialize(context):
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='test')
    
    one = CustVwap(inputs=[USEquityPricing.close, USEquityPricing.volume], window_length=10)
    
    two = Alpha41(inputs=[USEquityPricing.close,  USEquityPricing.volume, USEquityPricing.high, USEquityPricing.low])
    
    pipe.add(preset, 'one')
    pipe.add(custom, 'two')
    
    #screen = preset.top(500)
    screen2 = custom.top(500)
    
    pipe.set_screen(screen2)
    pass
Exemple #14
0
def initialize(context):

    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='piotroski')

    profit = ROA() + ROAChange() + CashFlow() + CashFlowFromOps()
    leverage = LongTermDebtRatioChange() + CurrentDebtRatioChange(
    ) + SharesOutstandingChange()
    operating = GrossMarginChange() + AssetsTurnoverChange()
    piotroski = profit + leverage + operating

    pipe.add(piotroski, 'piotroski')
    pipe.set_screen(piotroski >= 7)
    context.is_month_end = False
    schedule_function(set_month_end, date_rules.month_end(1))
    schedule_function(trade, date_rules.month_end(), time_rules.market_close())
def initialize(context):
    window_length = 3    
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='Sentiment_Pipe')    
    dollar_volume = AverageDailyDollarVolumeTraded()
    filter = (dollar_volume > 10**7)

    pipe.add(AverageSentiment(inputs=[sentdex.sentiment_signal],
                          window_length=window_length), 'Average_Sentiment')    
    pipe.set_screen(filter)
    context.longs = None
    context.shorts = None
    
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(hours=1))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))
    set_slippage(slippage.FixedSlippage(spread=0))
Exemple #16
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()

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

    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='beta_metrics')
    pipe.add(Beta(), "beta")

    # Add other filters
    factor1 = AverageDollarVolume(window_length=20)
    pipe.add(factor1, 'Avg_dollar_Volume')
    market_cap1 = market_cap()
    pipe.add(market_cap1, 'market_cap1')
    mom5 = momentum_5()
    pipe.add(mom5, 'mom_5')
    annual_vol = AnnualizedVolatility()
    pipe.add(annual_vol, 'annual_vol')
    sma3 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=3)
    pipe.add(sma3, 'sma3')
    sma5 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=5)
    pipe.add(sma5, 'sma5')
    sma20 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=20)
    pipe.add(sma20, 'sma20')

    # Set pipeline screen
    factor1_filter = factor1 > 10**7
    market_cap_top = market_cap1 < 10 * 10**9
    market_cap_bottom = market_cap1 > 2 * 10**9
    # annual_vol_filter = annual_vol < 0.2
    # sma_filter = (sma3 > sma5) & (sma5 > sma20)
    # mom5_filter = mom5 > 1

    total_filter = (factor1_filter & market_cap_bottom & market_cap_top
                    )  # & annual_vol_filter) #and mom5_filter

    pipe.set_screen(total_filter)

    return pipe
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
Exemple #18
0
def initialize(context):

    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='piotroski')

    piotroski = Piotroski()

    market_cap = morningstar.valuation.market_cap > 5e7

    pipe.add(piotroski, 'piotroski')
    pipe.set_screen((piotroski >= 7) & market_cap)
    context.is_month_end = False
    schedule_function(set_month_end, date_rules.month_end(1))
    schedule_function(trade_long, date_rules.month_end(),
                      time_rules.market_open())
    # schedule_function(trade_short, date_rules.month_end(), time_rules.market_open())
    schedule_function(trade, date_rules.month_end(), time_rules.market_close())
def make_pipeline(context):
    # Create our pipeline
    pipe = Pipeline()

    # Screen out penny stocks and low liquidity securities.
    dollar_volume = AverageDollarVolume(window_length=20)
    is_liquid = dollar_volume > 10**7

    # Set our pipeline screens
    top_universe = is_liquid

    # Add long/shorts to the pipeline
    pipe.add(top_universe, "longs")
    pipe.add(BusinessDaysSince13DFilingsDate(), 'pbd_13')
    pipe.set_screen(is_liquid)

    return pipe
Exemple #20
0
def Custom_pipeline(context):
    pipe = Pipeline()
    sma_10 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=10)
    sma_50 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=50)
    
    pipe.add(st.bull_scored_messages .latest, 'bull_scored_messages')
    pipe.add(st.bear_scored_messages .latest, 'bear_scored_messages')
    pipe.add(sma_10, 'sma_10')
    pipe.add(sma_50, 'sma_50')
    
    pipe.set_screen(Q500US() 
                    & (sma_10 > sma_50) 
                    & ((st.bull_scored_messages.latest * 0.35) > st.bear_scored_messages.latest)
                    & (st.bear_scored_messages.latest > 10)
                   )
    
    return pipe
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
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.
    """
    pipe = Pipeline()

    initial_screen = filter_universe()

    factors = {
        "Message": MessageVolume(mask=initial_screen),
        "Momentum": Momentum(mask=initial_screen),
        "Value": Value(mask=initial_screen),
    }

    clean_factors = None
    for name, factor in factors.items():
        if not clean_factors:
            clean_factors = factor.isfinite()
        else:
            clean_factors = clean_factors & factor.isfinite()

    combined_rank = None
    for name, factor in factors.items():
        if not combined_rank:
            combined_rank = factor.rank(mask=clean_factors)
        else:
            combined_rank += factor.rank(mask=clean_factors)
    pipe.add(combined_rank, 'factor')

    # Build Filters representing the top and bottom 200 stocks by our combined ranking system.
    # We'll use these as our tradeable universe each day.
    longs = combined_rank.percentile_between(80, 90)
    shorts = combined_rank.percentile_between(10, 20)

    pipe.set_screen(longs | shorts)

    pipe.add(longs, 'longs')
    pipe.add(shorts, 'shorts')
    return pipe
Exemple #23
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.
    """
    pipe = Pipeline()
    
    initial_screen = Q500US()

    factors = {
        "Message": MessageVolume(mask=initial_screen),
        #"Momentum": Momentum(mask=initial_screen),
        "Value": Value(mask=initial_screen),
    }
    
    clean_factors = None
    for name, factor in factors.items():
        if not clean_factors:
            clean_factors = factor.isfinite()
        else:
            clean_factors = clean_factors & factor.isfinite()  
            
    combined_rank = None
    for name, factor in factors.items():
        if not combined_rank:
            combined_rank = factor.rank(mask=clean_factors)
        else:
            combined_rank += factor.rank(mask=clean_factors)
    pipe.add(combined_rank, 'factor')

    # Build Filters representing the top and bottom 200 stocks by our combined ranking system.
    # We'll use these as our tradeable universe each day.
    longs = combined_rank.percentile_between(90, 100)
    shorts = combined_rank.percentile_between(0, 10)
    
    pipe.set_screen(longs | shorts)
    
    pipe.add(longs, 'longs')
    pipe.add(shorts, 'shorts')
    return pipe
Exemple #24
0
def initialize(context):
    # Create, register and name a pipeline in initialize.
    pipe = Pipeline()
    attach_pipeline(pipe, 'dollar_volume_10m_pipeline')

    # Construct a 100-day average dollar volume factor and add it to the pipeline.
    dollar_volume = AverageDollarVolume(window_length=100)
    pipe.add(dollar_volume, 'dollar_volume')

    #Create high dollar-volume filter to be the top 2% of stocks by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(99, 100)
    # Set the screen on the pipelines to filter out securities.
    pipe.set_screen(high_dollar_volume)

    context.dev_multiplier = 2
    context.max_notional = 1000000
    context.min_notional = -1000000
    context.days_traded = 0
    schedule_function(func=process_data_and_order, date_rule=date_rules.every_day())
Exemple #25
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()

    # Factor of yesterday's close price.
    # yesterday_close = USEquityPricing.close.latest
     
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='beta_metrics')
    pipe.add(Beta(), "beta")

    # Add other filters
    factor1 = momentum_factor_1()
    pipe.add(momentum_factor_1(), 'factor_1')
    factor2 = momentum_factor_2()
    pipe.add(momentum_factor_2(), 'factor_2')
    factor3 = momentum_factor_3()
    pipe.add(momentum_factor_3(), 'factor_3')
    factor4 = momentum_factor_4()
    pipe.add(momentum_factor_4(), 'factor_4')
    factor5 = efficiency_ratio()
    pipe.add(factor5, 'factor_5')
    factor6 = AverageDollarVolume(window_length=20)
    pipe.add(factor6, 'factor_6')
    
    dollar_volume = AvgDailyDollarVolumeTraded()
    
    # Set pipeline screen
    mkt_screen = market_cap()    
    stocks = mkt_screen.top(3000) 
    factor_5_filter = factor5 > 0.0
    factor_6_filter = factor6 > 0.5e6 # only consider stocks trading >$500k per day
    # Screen out penny stocks and low liquidity securities.
    factor_7_filter = dollar_volume > 10**7
    total_filter = (stocks & factor_5_filter & factor_6_filter & factor_7_filter)
    pipe.set_screen(total_filter)  

    return pipe
Exemple #26
0
def initialize(context):
    context.leverage = 1
    schedule_function(rebalance, date_rules.month_start(),
                      time_rules.market_close(hours=1))
    schedule_function(record_vars, date_rules.month_start(),
                      time_rules.market_close())
    attach_pipeline(make_pipeline(), 'my_pipeline')
    pipe = Pipeline()
    dollar_volume = AverageDollarVolume(window_length=30)
    pipe.set_screen(QTradableStocksUS())
    pipe.add(dollar_volume, 'ADV')
    attach_pipeline(pipe, 'pipe')
    schedule_function(flush_portfolio, date_rules.every_day(),
                      time_rules.market_close(minutes=10))

    schedule_function(limit_orders, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
    schedule_function(flush_orders, date_rules.every_day(),
                      time_rules.market_close(minutes=1))
Exemple #27
0
def Custom_pipeline(context):
    pipe = Pipeline()
    static_sids = sum([[x[ETF], x[ASSET]] for x in context.conditions], [])
    my_sids =  StaticSids(static_sids)
    
    # sma_10 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=10)
    # sma_50 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=50)
    # pipe.add(st.bull_scored_messages .latest, 'bull_scored_messages')
    # pipe.add(st.bear_scored_messages .latest, 'bear_scored_messages')
    # pipe.add(st.bull_bear_msg_ratio .latest, 'bull_bear_msg_ratio')
    pipe.add(st.total_scanned_messages.latest, TOTAL_SCANNED_MESSAGES)
    pipe.set_screen(
        my_sids
        # & (sma_10 > sma_50)
        # & 0.35*st.bull_scored_messages.latest > st.bear_scored_messages.latest
        # & (st.bull_bear_msg_ratio.latest > 1.0 / 0.35)
        # & (st.bear_scored_messages.latest > 10)
    )   
    return pipe
def initialize(context):

    # Create and attach an empty Pipeline.
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='my_pipeline')

    # Construct Factors.
    sma_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10)
    sma_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30)

    # Construct a Filter.
    prices_under_5 = (sma_10 < 5)

    # Register outputs.
    pipe.add(sma_10, 'sma_10')
    pipe.add(sma_30, 'sma_30')

    # Remove rows for which the Filter returns False.
    pipe.set_screen(prices_under_5)
def initialize(context):
    
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='sentiment_metrics')
    
    # Add our AvgImpact factor to the pipeline
    pipe.add(AvgImpact(inputs=[alphaone.article_sentiment, alphaone.impact_score], window_length=7), "avg_impact")    
    
    dollar_volume = AvgDailyDollarVolumeTraded()
    
    # Screen out low liquidity securities.
    pipe.set_screen(dollar_volume > 10**7)
    context.shorts = None
    context.longs = None
    # context.spy = sid(8554)
    
    schedule_function(rebalance, date_rules.week_start(), time_rules.market_open(hours=1))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))
    set_slippage(slippage.FixedSlippage(spread=0))
def my_pipeline(context):
    pipe = Pipeline()

    revenue_growth = morningstar.operation_ratios.revenue_growth.latest
    dil_eps_growth = morningstar.earnings_ratios.diluted_eps_growth.latest
    net_income_growth = morningstar.operation_ratios.net_income_growth.latest
    operation_income_growth = morningstar.operation_ratios.operation_income_growth.latest

    #Filters
    # Only consider the top 10% of stocks ranked by dollar volume.
    dollar_volume = AverageDollarVolume(window_length=1)
    high_dollar_volume = dollar_volume.percentile_between(90, 100)
    #Traditional growth stocks metrics: >25% growth in all related factors
    rev_filter = revenue_growth > 0.20
    eps_filter = dil_eps_growth > 0.20
    income_filter = net_income_growth > 0.20
    opin_filter = operation_income_growth > 0.20

    # Create a regression factor with SPY.
    regression = RollingLinearRegressionOfReturns(
        target=context.target_asset,
        returns_length=context.returns_length,
        regression_length=context.regression_length,
        mask=high_dollar_volume,
    )
    alpha = regression.alpha
    beta = regression.beta
    correlation = regression.r_value
    low_beta = (beta < context.beta_threshold) & \
               (beta > -context.beta_threshold)
    high_beta = ~low_beta

    pipe.add(alpha, 'alpha')
    pipe.add(beta, 'beta')
    pipe.add(correlation, 'correlation')
    pipe.add(low_beta, 'low_beta')
    pipe.add(high_beta, 'high_beta')
    pipe.set_screen(rev_filter & eps_filter & income_filter & opin_filter
                    & high_dollar_volume)

    return pipe
    pass
def initialize(context):

    context.spy = sid(8554)
    set_benchmark(context.spy)

    # define momentum as latest/SMA, same as to market (SPY) filter
    momentum = (Latest(inputs=[USEquityPricing.close]) / SimpleMovingAverage(
        inputs=[USEquityPricing.close], window_length=Lookback)) - 1
    #mkt_cap         = Latest(inputs=[morningstar.valuation.market_cap]) #very slow
    #universe        = mkt_cap.top(UniverseSize)
    dollar_volume = AvgDailyDollarVolumeTraded(window_length=100)
    universe = dollar_volume.top(UniverseSize)
    momentum_rank = momentum.rank(mask=universe, ascending=False)
    long_filter = momentum_rank <= 0.2 * UniverseSize
    short_filter = momentum_rank > 0.8 * UniverseSize
    apr = APR()
    apr_filter = apr > 0.005

    pipe = Pipeline()
    #pipe.add(momentum, 'momentum') # include for debugging
    pipe.add(momentum_rank, 'momentum_rank')
    pipe.add(apr, 'apr')
    pipe.add(long_filter, 'long')
    pipe.add(short_filter, 'short')

    pipe.set_screen(universe & apr_filter & (long_filter | short_filter))
    pipe = attach_pipeline(pipe, name='equitylongshort')

    schedule_function(func=rebalance_positions,
                      date_rule=date_rules.week_start(days_offset=2),
                      time_rule=time_rules.market_open(hours=2),
                      half_days=True)
    schedule_function(func=cancel_all,
                      date_rule=date_rules.week_start(days_offset=2),
                      time_rule=time_rules.market_close(),
                      half_days=True)

    set_slippage(
        slippage.VolumeShareSlippage(volume_limit=0.025,
                                     price_impact=0.1))  # Default
    set_commission(commission.PerShare(cost=0.005,
                                       min_trade_cost=1.0))  # FSC for IB
Exemple #32
0
def initialize(context):
    context.max_pos_size = 0.01
    context.max_turnover = 0.95
    context.holdings = 10
    context.profit_taking = 20
    context.max_loss = -20
    context.max_leverage = 1
    set_slippage(slippage.FixedSlippage(spread=0.00))

    schedule_function(monthly_rebalance, date_rules.month_end(),
                      time_rules.market_open(hours=5))  #5 is 8%

    pipe = Pipeline()

    attach_pipeline(pipe, 'ranked_stocks')

    attach_pipeline(risk_loading_pipeline(), 'risk_pipe')

    market_cap_filter = market_cap()
    stocks = market_cap_filter.top(3000)
    total_filter = (stocks)
    pipe.set_screen(total_filter)

    m_factor1 = momentum_factor_1()
    pipe.add(m_factor1, 'factor_1')
    m_factor2 = momentum_factor_2()
    pipe.add(m_factor2, 'factor_2')
    m_factor_3 = stddev_factor()
    pipe.add(m_factor_3, 'factor_3')

    m_factor1_rank = m_factor1.rank(mask=total_filter, ascending=False)
    m_factor2_rank = m_factor2.rank(mask=total_filter, ascending=False)
    m_factor_3_rank = m_factor_3.rank(mask=total_filter, ascending=True)

    pipe.add(m_factor1_rank, 'f1_rank')
    pipe.add(m_factor2_rank, 'f2_rank')
    pipe.add(m_factor_3_rank, 'f3_rank')

    #should put weighted adding instead
    combo_raw = (m_factor1_rank + m_factor2_rank + m_factor_3_rank) / 3
    pipe.add(combo_raw, 'combo_raw')
    pipe.add(combo_raw.rank(mask=total_filter), 'combo_rank')
Exemple #33
0
def make_pipeline():
    """
    Function to create a pipeline
    """
    pipe = Pipeline()
    
    # Base universe set to the Q1500US
    base_universe = Q1500US()
    
    pipe.add(YOY_Slope(), 'YOY-Slope')
    
    loser_returns = YOY_Slope.percentile_between(YOY_Slope(),0,10,mask=base_universe)
    winner_returns = YOY_Slope.percentile_between(YOY_Slope(),90,100,mask=base_universe)
    
    pipe.set_screen(loser_returns | winner_returns)

    pipe.add(loser_returns, 'loser_returns')
    pipe.add(winner_returns, 'winner_returns')
    
    return pipe
def custom_pipe(context):
    pipe = Pipeline()
    # bull_1 = st.bullish_intensity.latest
    # bear_1 = st.bearish_intensity.latest
    # volume = USEquityPricing.volume.latest
    sma_scan_7 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=7)
    # sma_scan_6 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=6)
    # sma_scan_5 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=5)
    # sma_scan_4 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=4)
    # sma_scan_3 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=3)
    # sma_scan_2 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=2)
    scan_1 = st.total_scanned_messages.latest    
    # pipe.add(bull_1, 'bullish_intensity')
    # pipe.add(bear_1, 'bearish_intensity')
    # pipe.add(st.bear_scored_messages.latest, 'bear_scored_messages')
    # pipe.add(st.bull_scored_messages.latest, 'bull_scored_messages')
    pipe.add(scan_1, 'scan_1') 
    # pipe.add(sma_scan_2, 'sma_scan_2') 
    # pipe.add(sma_scan_3, 'sma_scan_3') 
    # pipe.add(sma_scan_4, 'sma_scan_4') 
    # pipe.add(sma_scan_5, 'sma_scan_5') 
    # pipe.add(sma_scan_6, 'sma_scan_6') 
    pipe.add(sma_scan_7, 'sma_scan_7') 
    # pricing = USEquityPricing.close.latest

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

    pipe.set_screen(
        (base_universe)
        # (scan_1 < 10) 
        # (pricing < 15.00) &
        # (pricing > 5.00) &
        # (volume > 1000000) &
        # (
        #     (bull_1 > 0) | 
        #     (bear_1 > 0)
        # ) 
        # (scan_1 < sma_scan_7)
    ) 
    return pipe
Exemple #35
0
def initialize(context):
    context.position_count = 10
    context.positions_considered = 50
    # Sector mappings
    context.sector_mappings = {
        101.0: "Basic Materials",
        102.0: "Consumer Cyclical",
        103.0: "Financial Services",
        104.0: "Real Estate",
        205.0: "Consumer Defensive",
        206.0: "Healthcare",
        207.0: "Utilites",
        308.0: "Communication Services",
        309.0: "Energy",
        310.0: "Industrials",
        311.0: "Technology"
    }
    # Create and attach an empty Pipeline.
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='my_pipeline')
    # Construct Factors.
    dv = AvgDailyDollarVolumeTraded(window_length=20)
    mkt = MarketCap(window_length=10)
    ebit_ev = EBIT_EV(window_length=255)
    spread_ebit_ev = Spread_EBIT_EV(window_length=255)
    snoa = SNOA()
    # Construct a Filter.
    net_filter = mkt.percentile_between(40.0, 100.0) & dv.percentile_between(
        40.0, 100.0) & snoa.percentile_between(0.0, 95.0)
    ebit_ev_rank = ebit_ev.rank(mask=net_filter, ascending=False)
    spread_ebit_ev_rank = spread_ebit_ev.rank(mask=net_filter, ascending=True)
    # Register outputs.
    pipe.add(ebit_ev, 'ebit_ev')
    pipe.add(ebit_ev_rank, 'ebit_ev_rank')
    pipe.add(spread_ebit_ev_rank, 'spread_ebit_ev_rank')
    # Remove rows for which the Filter returns False.
    pipe.set_screen(net_filter)
    set_long_only()
    schedule_function(rebalance,
                      date_rule=date_rules.week_start(days_offset=2),
                      time_rule=time_rules.market_open(minutes=90))