def make_pipeline():
    # 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)
Ejemplo n.º 2
0
def make_pipeline10():
    # Create Filters for Masks First
    latest_close = USEquityPricing.close.latest
    small_price = latest_close < 5

    # Classifier
    nyse_filter = exchange.eq('NYS')

    # Pass in the mask
    mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=10,
                                        mask=small_price)
    mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=30,
                                        mask=small_price)

    percent_difference = (mean_close_10 - mean_close_30) / mean_close_30

    perc_diff_check = percent_difference > 0

    final_filter = perc_diff_check & nyse_filter

    return Pipeline(columns={
        'Percent Difference': percent_difference,
        '30 Day Mean Close': mean_close_30,
        'Latest Close': latest_close,
        'Positive Percent Diff': perc_diff_check
    },
                    screen=final_filter)
Ejemplo n.º 3
0
def make_pipeline():

    mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=10)

    mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=30)

    rsi_7 = RSI(inputs=[USEquityPricing.close], window_length=10)

    percent_difference = (mean_close_10 - mean_close_30) / mean_close_30

    rsi_under_35 = (rsi_7 < 35)

    latest_close = USEquityPricing.close.latest
    dollar_volume = AverageDollarVolume(window_length=30)
    high_dollar_volume = dollar_volume.percentile_between(85, 100)

    filters = high_dollar_volume & rsi_under_35

    return Pipeline(columns={
        '10_day_mean_close': mean_close_10,
        'latest_close_price': latest_close,
        'percent_difference': percent_difference,
        'dollar_value': dollar_volume
    },
                    screen=filters)
Ejemplo n.º 4
0
def make_pipeline():
    # Base universe filter.
    base_universe = QTradableStocksUS()

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

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

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

    # Create a filter to select securities to short.
    shorts = percent_difference.top(50)

    # Create a filter to select securities to long.
    longs = percent_difference.bottom(50)

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

    return Pipeline(
        columns={
            'longs': longs,
            'shorts': shorts
        },
        screen=(securities_to_trade),
    )
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
    )
Ejemplo n.º 6
0
def initialize(context):
    # 空のパイプラインを作ります
    pipe = Pipeline()
    # research では run_pipeline 
    # algorithm では,initilize 内で attach_pipeline を実行して,パイプラインを毎日実行するように設定します.
    
    # ほしいデータを定義
    # pipeline 用に定義された 移動平均 SimpleMovingAverage を使う
    SMA10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10)
    SMA30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30)
    pipe.add(SMA10, 'SMA10') 
    pipe.add(SMA30, 'SMA30') 
  
    ## raw_weights 
    raw_weights = (SMA10 - SMA30) / SMA30
    abs_raw_weights = raw_weights.abs()
    pipe.add(raw_weights, 'raw_weights')
    pipe.add(abs_raw_weights, 'abs_raw_weights')
    
    pipe.set_screen(Q500US())
    
    attach_pipeline(pipe, "my_pipeline") 

    # 毎週月曜日にどの銘柄を保有するか決定する
    schedule_function(rebalance,
                      date_rules.week_start(),
                      time_rules.market_open())

    # 毎週金曜日の取引時間終了時に持っている銘柄を全部クローズする.
    schedule_function(all_position_close,
                      date_rule = date_rules.week_end(days_offset=0),
                      time_rule = time_rules.market_close())
Ejemplo n.º 7
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
    """

    sma_short = 35
    sma_long = 50

    short_sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                    window_length=sma_short)
    long_sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                   window_length=sma_long)
    rsi = RSI(inputs=[USEquityPricing.close], window_length=10)

    symbol = SidInList(sid_list=(8554))  # SPY 500

    return Pipeline(
        columns={
            'RSI': rsi,
            'SMA_short': short_sma,
            'SMA_long': long_sma,
            'symbol': symbol,
        },
        screen=symbol,
    )
Ejemplo n.º 8
0
def make_pipeline():

    value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest
    quality = Fundamentals.roe.latest
    sentiment_score = SimpleMovingAverage(inputs=[stocktwits.bull_minus_bear],window_length=3,)

    twitter_score = SimpleMovingAverage(inputs=[twitter_withretweets.bull_bear_msg_ratio],window_length=3,)    

    news_score = SimpleMovingAverage(inputs=[sentiment.sentiment_signal], window_length=5)

    total_revenue = Fundamentals.total_revenue.latest

    growth = Fundamentals.sustainable_growth_rate.latest
    
    operation_margin = Fundamentals.operation_margin.latest
    
    net_margin = Fundamentals.net_margin.latest

    rec_corredor = SimpleMovingAverage( inputs = [ConsensusRecommendations.total], window_length=3, )

    universe = QTradableStocksUS()
    
    value_winsorized = value.winsorize(min_percentile=0.17, max_percentile=0.83)
    quality_winsorized = quality.winsorize(min_percentile=0.17, max_percentile=0.83)
    sentiment_score_winsorized = sentiment_score.winsorize(min_percentile=0.17,                                                                             max_percentile=0.83)
    twitter_score_winsorized = twitter_score.winsorize(min_percentile=0.17, max_percentile=0.83)
    news_score_winsorized = news_score.winsorize(min_percentile=0.17, max_percentile=0.83)
    total_revenue_winsorized = total_revenue.winsorize(min_percentile=0.17, max_percentile=0.83)
    growth_winsorized = growth.winsorize(min_percentile=0.17, max_percentile=0.83)
    operation_margin_winsorized = operation_margin.winsorize(min_percentile=0.17, max_percentile=0.83)
    net_margin_winsorized = net_margin.winsorize(min_percentile=0.17, max_percentile=0.83)
    rec_corredor_winsorized = rec_corredor.winsorize(min_percentile=0.17, max_percentile=0.83)

    combined_factor = (
        1*value_winsorized.zscore()  
        + 6*quality_winsorized.zscore()
        + 1*sentiment_score_winsorized.zscore()
        + 5*twitter_score_winsorized.zscore()
        + 1*news_score_winsorized.zscore()
        + 6*growth_winsorized.zscore()
        + 1*operation_margin_winsorized.zscore()
        + 1*net_margin_winsorized.zscore()
        + 6*total_revenue_winsorized.zscore()
        + 9*rec_corredor_winsorized.zscore()
    )

    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
Ejemplo n.º 9
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 QTradableStocksUS
    base_universe = QTradableStocksUS()

    stocktwits_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    ).zscore()

    sentdex_score = SimpleMovingAverage(
        inputs=[sentiment.sentiment_signal],
        window_length=3,
    ).zscore()

    combined_score = (stocktwits_score + sentdex_score) / 2

    pipe = Pipeline(columns={
        'sentiment': combined_score,
    },
                    screen=base_universe)
    return pipe
Ejemplo n.º 10
0
def initialize(context):
    # 空のパイプラインを作ります
    pipe = Pipeline()
    # research では run_pipeline
    # algorithm では,initilize 内で attach_pipeline を実行して,パイプラインを毎日実行するように設定します.

    # ほしいデータを定義
    # pipeline 用に定義された 移動平均 SimpleMovingAverage を使う
    SMA10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=10)
    SMA30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=30)
    pipe.add(SMA10, 'SMA10')
    pipe.add(SMA30, 'SMA30')

    ## raw_weights
    raw_weights = (SMA10 - SMA30) / SMA30
    abs_raw_weights = raw_weights.abs()
    pipe.add(raw_weights, 'raw_weights')
    pipe.add(abs_raw_weights, 'abs_raw_weights')

    pipe.set_screen(Q500US())

    attach_pipeline(pipe, "my_pipeline")

    # Rebalance every Monday (or the first trading day if it's a holiday)
    # at market open.
    schedule_function(rebalance, date_rules.week_start(),
                      time_rules.market_open())

    schedule_function(all_position_close,
                      date_rule=date_rules.week_end(),
                      time_rule=time_rules.market_close())
Ejemplo n.º 11
0
def make_pipeline(context):
    # ベースユニバース
    base_universe = QTradableStocksUS()
    # make_pipelineを実行するのは before_trading_start(08:45ET)
    # 最新のプライスは前日の終値。
    yesterday_close = USEquityPricing.close.latest
    min_price = yesterday_close >= context.MyLeastPrice
    max_price = yesterday_close <= context.MyMostPrice

    tradeable_stocks = base_universe & min_price & max_price
    base_universe = AverageDollarVolume(
        window_length=20, mask=tradeable_stocks).percentile_between(6, 40)

    short_sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                    window_length=3,
                                    mask=base_universe)
    long_sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                   window_length=45,
                                   mask=base_universe)

    percent_difference = (short_sma - long_sma) / long_sma

    #stocks_worst = percent_difference.bottom(context.MaxCandidates)
    stocks_worst = percent_difference.bottom(context.MaxBuyOrdersAtOnce)

    pipe = Pipeline(columns={
        'percent_difference': percent_difference,
        'close': yesterday_close,
    },
                    screen=stocks_worst)

    return pipe
def new_pipeline():
    latest_close = USEquityPricing.close.latest
    small_price_stocks = latest_close < 5

    mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=30,
                                        mask=small_price_stocks)
    mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=10,
                                        mask=small_price_stocks)

    # using a classifier to check filter only stocks that belong to the NYSE
    nyse_filter = exchange.eq('NYS')

    percent_difference = (mean_close_10 - mean_close_30) / mean_close_30
    percent_difference_filter = percent_difference > 0
    combined_filter = percent_difference_filter & nyse_filter

    return Pipeline(columns={
        '30-Day Mean Close Price':
        mean_close_30,
        'Latest Close Price':
        latest_close,
        'Percent Difference':
        percent_difference,
        'Positive Percentage Difference Filter':
        percent_difference_filter,
    },
                    screen=combined_filter)
Ejemplo n.º 13
0
def make_pipeline():

    latest_close = USEquityPricing.close.latest
    small_price = latest_close < 5

    mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=30,
                                        mask=small_price)
    mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=10,
                                        mask=small_price)

    percent_diff = (mean_close_10 - mean_close_30) / mean_close_30

    perc_filter = percent_diff > 0

    #     Combine Filters
    final_filter = perc_filter & small_price

    return Pipeline(columns={
        '30 Day Mean Close': mean_close_30,
        'Percent Diff': percent_diff,
        'Latest Close': latest_close,
        'Percent Filter': perc_filter
    },
                    screen=final_filter)
def new_pipeline():
    latest_close = USEquityPricing.close.latest
    small_price_stocks = latest_close < 5

    mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=30,
                                        mask=small_price_stocks)
    mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=10,
                                        mask=small_price_stocks)

    percent_difference = (mean_close_10 - mean_close_30) / mean_close_30
    percent_difference_filter = percent_difference > 0
    combined_filter = percent_difference_filter

    return Pipeline(columns={
        '30-Day Mean Close Price':
        mean_close_30,
        'Latest Close Price':
        latest_close,
        'Percent Difference':
        percent_difference,
        'Positive Percentage Difference Filter':
        percent_difference_filter,
    },
                    screen=combined_filter)
Ejemplo n.º 15
0
def make_pipeline():
    """
    Create our pipeline.
    """

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

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

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

    percent_difference = (mean_10 - mean_30) / mean_30

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

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

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

    return Pipeline(
        columns={
            'longs': longs,
            'shorts': shorts
        },
        screen=(securities_to_trade),
    )
Ejemplo n.º 16
0
def make_pipeline():

    # Base universe set to the QTradableStocksUS
    base_universe = QTradableStocksUS()

    #mean average difference 用乖離當作判斷依據
    mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=10,
                                  mask=base_universe)
    mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=30,
                                  mask=base_universe)
    percent_diff = (mean_10 - mean_30) / mean_30

    #dollar vol filter 月交易來看流動性
    dollar_vol = AverageDollarVolume(window_length=30)
    high_dollar_vol = dollar_vol > 10000000

    #Filter to select securities to short
    shorts = percent_diff.top(100, mask=high_dollar_vol)

    #Filter to select securities to long
    longs = percent_diff.bottom(100, mask=high_dollar_vol)

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

    return Pipeline(columns={
        'shorts': shorts,
        'longs': longs
    },
                    screen=securities_to_trade)
def make_pipeline(context):
    base_universe = QTradableStocksUS()
    #Create Price Filter
    latest_close = USEquityPricing.close.latest
    penny_stock = latest_close < 5
    # Create Momentum Filter
    SMA200 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                 window_length=200)
    SMA20 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=20)
    momentum_filter = SMA20 > SMA200
    momentum_and_price = momentum_filter & penny_stock
    #Create Volatility Filter
    volatility = AnnualizedVolatility(inputs=[USEquityPricing.close],
                                      window_length=30,
                                      mask=base_universe)
    high_volatility = volatility.top(1, mask=momentum_and_price)

    # Combine into final filter
    final_filter = penny_stock & momentum_filter & high_volatility

    return Pipeline(columns={
        'SMA200': SMA200,
        'SMA20': SMA20,
        'Last Close': latest_close,
        'Annualized Volatility': volatility,
        'final filter': final_filter
    },
                    screen=final_filter)
Ejemplo n.º 18
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_half_base_energy = base_energy & high_dollar_volume
    mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=10,
                                  mask=top_half_base_energy)
    mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=30,
                                  mask=top_half_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)
def make_pipeline():
    # UNIVERSE Q1500US
    base_universe = Q1500US()
    # ENERGY SECTOR  (OR: sector = Sector())
    sector = morningstar.asset_classification.morningstar_sector_code.latest
    energy_sector = sector.eq(309)
    # MAKE MASK OF 1500US & 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 AVERAGE DOLLAR VOLUME
    high_dollar_volume = dollar_volume.percentile_between(95, 100)
    # COMBINE THE FILTERS
    top_five_base_energy = base_energy & high_dollar_volume
    # GRAB THE 10-day & 30-day MEAN CLOSE
    mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mast=top_five_base_energy)
    mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mast=top_five_base_energy)
    # PERCENT DIFFERNENCE
    percent_difference = (mean_10 - mean_30) / mean_30
    # LIST OF SHORTS & LONGS
    shorts, longs = (percent_difference < 0), (percent_difference > 0)
    # FINAL MASK/FILTER FOR ANYTHING IN SHORTS / LONGS
    securities_to_trade = shorts & longs
    # RETURN THE PIPELINE
    return Pipeline(columns={
        'longs': longs, 'shorts': shorts, 'percent_diff': percent_difference
    }, screen=securities_to_trade)
Ejemplo n.º 20
0
def make_pipeline():

    latest_close = USEquityPricing.close.latest
    small_price = latest_close < 5

    #classifier:
    #creates a filter to show only stocks listed on new york stock exchange.
    nyse_filter = exchange.eq("NYS")

    mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=30,
                                        mask=small_price)
    mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=10,
                                        mask=small_price)
    #*please note the mask. it is applied in simple moving average for the reason of saving computational
    #efforts

    percent_diff = (mean_close_10 - mean_close_30) / mean_close_30
    perc_filter = percent_diff > 0

    #final filter:
    final_filter = perc_filter & small_price & nyse_filter

    return Pipeline(columns={
        '30 Day Mean Close': mean_close_30,
        'Percent Diff': percent_diff,
        'Latest Close': latest_close,
        'Percent Filter': perc_filter
    },
                    screen=final_filter)
Ejemplo n.º 21
0
def make_pipeline():
    """
    Make a VWAP pipeline.
    """

    vwap = VWAP(inputs=[USEquityPricing.close, USEquityPricing.volume],
                window_length=14)

    short_sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                    window_length=35)
    long_sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                   window_length=50)

    symbol = SidInList(sid_list=(8554))  # Only show values for the S&P500

    return Pipeline(
        columns={
            'vwap': vwap,
            'close': USEquityPricing.close.latest,
            'short_sma': short_sma,
            'long_sma': long_sma,
            'symbol': symbol,
        },
        screen=symbol,
    )
def make_pipeline():
    #Predefined Factors
    value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest
    quality = Fundamentals.roe.latest
    sentiment_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    )
    value_winsorized = value.winsorize(min_percentile=0.05,
                                       max_percentile=0.95)
    quality_winsorized = quality.winsorize(min_percentile=0.05,
                                           max_percentile=0.95)
    sentiment_score_winsorized = sentiment_score.winsorize(min_percentile=0.05,
                                                           max_percentile=0.95)

    # New Factors
    total_revenue = Fundamentals.total_revenue.latest

    mean_sentiment_5day = SimpleMovingAverage(
        inputs=[sentiment.sentiment_signal], window_length=5)

    mean_sentiment_5day_winsorized = mean_sentiment_5day.winsorize(
        min_percentile=0.05, max_percentile=0.95)

    operation_ratios_latest = operation_ratios.roic.latest

    valuation_ratios_dividend_yield_latest = valuation_ratios.dividend_yield.latest

    valuation_ratios_cash_return_latest = valuation_ratios.cash_return.latest

    universe = (QTradableStocksUS() & operation_ratios_latest.notnull()
                & valuation_ratios_dividend_yield_latest.notnull()
                & valuation_ratios_cash_return_latest.notnull())
    operation_ratios_latest = operation_ratios_latest.rank(mask=universe,
                                                           method='average')
    valuation_ratios_dividend_yield_latest = valuation_ratios_dividend_yield_latest.rank(
        mask=universe, method='average')
    valuation_ratios_cash_return_latest = valuation_ratios_cash_return_latest.rank(
        mask=universe, method='average')

    combined_factor = (
        #Original
        3 * value_winsorized.zscore() + quality_winsorized.zscore() +
        sentiment_score_winsorized.zscore() +
        #New
        operation_ratios_latest + valuation_ratios_dividend_yield_latest +
        3 * valuation_ratios_cash_return_latest +
        0.5 * mean_sentiment_5day_winsorized + 3 * total_revenue)

    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
def make_pipeline():
    # The factors we create here are based on fundamentals data and a moving
    # average of sentiment data
    value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest
    quality = Fundamentals.roe.latest
    sentiment_score = SimpleMovingAverage(inputs=[stocktwits.bull_minus_bear],
        window_length=3)
    sma50 = SimpleMovingAverage(inputs=[USEquityPricing.close],                                           window_length=50)
    sma200 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=200)
    smaScore = sma50/sma200

    sizeScore = SimpleMovingAverage(inputs=[Fundamentals.size_score],window_length=3)
    
    growthScore = SimpleMovingAverage(inputs=[Fundamentals.growth_score],window_length=3)

    universe = QTradableStocksUS()
    
    # We winsorize our factor values in order to lessen the impact of outliers
    # For more information on winsorization, please see
    # https://en.wikipedia.org/wiki/Winsorizing
    value_winsorized = value.winsorize(min_percentile=0.05, max_percentile=0.95)
    quality_winsorized = quality.winsorize(min_percentile=0.05, max_percentile=0.95)
    sentiment_score_winsorized = sentiment_score.winsorize(min_percentile=0.05,                                                                             max_percentile=0.95)
    smaScore_winsorized =smaScore.winsorize(min_percentile=0.05, max_percentile=0.95)
    sizeScore_winsorized = sizeScore.winsorize(min_percentile=0.05, max_percentile=0.95)
    growthScore_winsorized = growthScore.winsorize(min_percentile=0.05, max_percentile=0.95)
    # Here we combine our winsorized factors, z-scoring them to equalize their influence
    combined_factor = (
        value_winsorized.zscore() + 
        quality_winsorized.zscore() + 
        sentiment_score_winsorized.zscore() +
        smaScore_winsorized.zscore() +
        sizeScore_winsorized.zscore() + 
        growthScore_winsorized.zscore()
    )

    # Build Filters representing the top and bottom baskets of stocks by our
    # combined ranking system. We'll use these as our tradeable universe each
    # day.
    longs = combined_factor.top(TOTAL_POSITIONS//2, mask=universe)
    shorts = combined_factor.bottom(TOTAL_POSITIONS//2, mask=universe)

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

    # Create pipeline
    pipe = Pipeline(
        columns={
            'longs': longs,
            'shorts': shorts,
            'combined_factor': combined_factor
        },
        screen=long_short_screen
    )
    return pipe
Ejemplo n.º 24
0
def make_pipeline():
    """
    """
    sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=20)
    adj_close = USEquityPricing.close.latest
    myfactor = sma / adj_close
    quantiled_myfactor = myfactor.quantiles(10)

    value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest
    quality = Fundamentals.roe.latest
    sentiment_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    )

    universe = QTradableStocksUS()

    # We winsorize our factor values in order to lessen the impact of outliers
    # For more information on winsorization, please see
    # https://en.wikipedia.org/wiki/Winsorizing
    # value_winsorized = value.winsorize(min_percentile=0.05, max_percentile=0.95)
    # quality_winsorized = quality.winsorize(min_percentile=0.05, max_percentile=0.95)
    # sentiment_score_winsorized = sentiment_score.winsorize(min_percentile=0.05,                                                                             max_percentile=0.95)
    myfactor_windorized = myfactor.winsorize(min_percentile=0.05,
                                             max_percentile=0.95)

    # Here we combine our winsorized factors, z-scoring them to equalize their influence
    combined_factor = (
        #myfactor.zscore()
        myfactor_windorized.zscore()
        # value_winsorized.zscore() +
        # quality_winsorized.zscore() +
        # sentiment_score_winsorized.zscore()
    )

    # Build Filters representing the top and bottom baskets of stocks by our
    # combined ranking system. We'll use these as our tradeable universe each
    # day.
    longs = combined_factor.top(TOTAL_POSITIONS // 2, mask=universe)
    shorts = combined_factor.bottom(TOTAL_POSITIONS // 2, mask=universe)
    # longs = combined_factor.eq(9)
    # shorts = combined_factor.eq(0)

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

    # Create pipeline
    pipe = Pipeline(columns={
        'longs': longs,
        'shorts': shorts,
        'combined_factor': combined_factor,
        'myfactor': myfactor,
        'quantiled_myfactor': quantiled_myfactor,
    },
                    screen=long_short_screen)
    return pipe
Ejemplo n.º 25
0
def initialize(context):
    set_slippage(
        slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))
    set_commission(commission.PerShare(
        cost=0.000, min_trade_cost=0.00))  # Assume Robinhood zero-commissions

    # Filter order:
    # 1. MktCap > X # filters stocks with minimum size
    # 2. Volume > X # filters stocks with minimum volume
    # 3. X < SMA_200 & X < SMA_10 # filter stocks with gaps more likely to fill
    # 4. Y < RSI < X # filters stocks with (+) momentum and strong trend

    mkt_cap = MarketCap()
    last_close = LastClose()
    dollar_volume = AverageDollarVolume(window_length=10)
    sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=200)
    sma_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                 window_length=10)
    rsi = RSI(inputs=[USEquityPricing.close], window_length=15)

    mkt_cap_rank = mkt_cap.rank(ascending=False)
    mkt_cap_filter = (mkt_cap_rank < 4000)
    #sma_filter = (last_close > sma_10) # & (last_close < sma_200) # shouldnt be last close, should be open price
    dollar_volume_filter = (dollar_volume > 100000)
    rsi_filter = (rsi > 15) & (rsi < 50)

    pipe = Pipeline(
        columns={
            'mkt_cap_rank': mkt_cap_rank,
            'last_close': last_close,
            '$volume': dollar_volume,
            'sma_200%': last_close / sma_200,
            'sma_10%': last_close / sma_10,
            'rsi/50': rsi / 50
        },
        screen=(mkt_cap_filter & dollar_volume_filter & rsi_filter
                )  # & sma_filter)
    )
    attach_pipeline(pipe, name='my_pipeline')

    for i in range(2, 5):
        schedule_function(  # This will execute buys at 9:31AM
            openFunction,
            date_rules.week_start(
                days_offset=i),  #do not run on Mondays (poor success)
            time_rules.market_open(minutes=1),
            False  #exclude half days
        )
        schedule_function(  # This will sell open positions before close
            closeFunction,
            date_rules.week_start(
                days_offset=i),  #do not run on Mondays (poor success)
            time_rules.market_close(minutes=30),
            False  #exclude half days
        )
Ejemplo n.º 26
0
def make_pipeline():

    global value
    global quality
    global sentiment_score
    global test_sentiment
    global total_revenue
    global yesterday_close
    global yesterday_volume

    value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest

    quality = Fundamentals.roe.latest

    sentiment_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    )
    sentiment_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    )

    test_sentiment = (twitter_sentiment.bull_scored_messages.latest /
                      twitter_sentiment.total_scanned_messages.latest)

    total_revenue = Fundamentals.total_revenue.latest

    yesterday_close = EquityPricing.close.latest

    yesterday_volume = EquityPricing.volume.latest

    universe = QTradableStocksUS()

    value_winsorized = value.winsorize(min_percentile=0.05,
                                       max_percentile=0.95)
    quality_winsorized = quality.winsorize(min_percentile=0.05,
                                           max_percentile=0.95)
    sentiment_score_winsorized = sentiment_score.winsorize(min_percentile=0.05,
                                                           max_percentile=0.95)

    combined_factor = (value_winsorized.zscore() +
                       quality_winsorized.zscore() +
                       sentiment_score_winsorized.zscore())

    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
Ejemplo n.º 27
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
    """

    to_exclude_symbol_filter = StaticSids([sid(40515), sid(41969), sid(38054)])
    sp_100_filter = StaticSids(getSP100())
    # exchange = Fundamentals.exchange_id.latest
    # nyse_filter = exchange.eq('NYS')

    # dollar_volume = AverageDollarVolume(window_length=10)
    # high_dollar_volume = dollar_volume.top(TOP_NUM_STOCKS_BY_DOLLAR_VOLUME)
    vol_sma = SimpleMovingAverage(inputs=[USEquityPricing.volume],
                                  window_length=90)
    price_sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                    window_length=30)

    vol_filter = ~(to_exclude_symbol_filter) & (vol_sma > VOLUME_MIN_AVG) & (
        price_sma > CLOSE_PRICE_MIN_AVG)

    weekly_high = WeeklyHigh(inputs=[USEquityPricing.high], mask=vol_filter)
    weekly_low = WeeklyLow(inputs=[USEquityPricing.low], mask=vol_filter)
    weekly_gamma_filter = WeeklyGammaFilter(inputs=[
        USEquityPricing.open, USEquityPricing.high, USEquityPricing.low,
        USEquityPricing.close
    ],
                                            mask=vol_filter)

    monthly_outside_filter = MonthlyOutsideFilter(inputs=[
        USEquityPricing.open, USEquityPricing.high, USEquityPricing.low,
        USEquityPricing.close
    ],
                                                  mask=vol_filter)

    monthly_current_open = MonthlyCurrentOpen(inputs=[USEquityPricing.open],
                                              mask=vol_filter)
    weekly_current_open = WeeklyCurrentOpen(inputs=[USEquityPricing.open],
                                            mask=vol_filter)

    pipe = Pipeline(
        screen=(weekly_gamma_filter) & (monthly_outside_filter),
        # screen = symbol_filter,
        columns={
            # 'daily_classifier': daily_classifier,
            # 'daily_high': USEquityPricing.high.latest,
            # 'daily_low': USEquityPricing.low.latest,
            'weekly_gamma_filter': weekly_gamma_filter,
            'monthly_outside_filter': monthly_outside_filter,
            'weekly_high': weekly_high,
            'weekly_low': weekly_low,
            'monthly_current_open': monthly_current_open,
            'weekly_current_open': weekly_current_open,
            'is_sp_100': sp_100_filter
        })
    return pipe
Ejemplo n.º 28
0
def make_pipeline():

    mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=10)
    mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                        window_length=30)

    percent_difference = (mean_close_10 - mean_close_30) / mean_close_30

    return Pipeline(columns={'percent_difference': percent_difference})
Ejemplo n.º 29
0
def initialize(context):

    #sell criteria the morning of -_-
    schedule_function(sellaII, date_rules.every_day(),
                      time_rules.market_open(minutes=1))

    #cancel all open orders before buy criteria
    schedule_function(sellaIII, date_rules.every_day(),
                      time_rules.market_close(minutes=8))

    #sell all (4 mins before sell all positions)
    schedule_function(selaV, date_rules.every_day(),
                      time_rules.market_close(minutes=7))

    for i in range(30, 380):
        schedule_function(sell_criteria, date_rules.every_day(),
                          time_rules.market_open(minutes=i))

    #pipeine initialization (2 mins before buy criteria)
    schedule_function(be4tradestart, date_rules.every_day(),
                      time_rules.market_close(minutes=6))

    #buy criteria (3 mins before sell criteria day of)
    schedule_function(examplee, date_rules.every_day(),
                      time_rules.market_close(minutes=5))

    schedule_function(mmarket, date_rules.every_day(),
                      time_rules.market_close(minutes=1))

    set_commission(commission.PerTrade(cost=0))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))
    set_slippage(slippage.VolumeShareSlippage(volume_limit=1, price_impact=0))

    avg_volume = AverageDollarVolume(window_length=10)
    sma_2 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                window_length=2)
    sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=200)
    avg_volumee = AverageDollarVolume(window_length=2)
    volatilityy = AnnualizedVolatility(annualization_factor=252)

    pipe_screen = ((avg_volume >= 15000000) & (sma_2 >= sma_200) &
                   (avg_volumee >= 3000000) & (sma_2 >= 5.0) &
                   (volatilityy <= 0.93))

    pipe_columns = {
        'avg voI': avg_volume,
        'sma2': sma_2,
        'sma200': sma_200,
        'avg voII': avg_volumee,
        'volatility': volatilityy
    }
    pipe = Pipeline(columns=pipe_columns, screen=pipe_screen)
    attach_pipeline(pipe, 'example')
    set_long_only()
Ejemplo n.º 30
0
def make_pipeline():
    value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest
    quality = Fundamentals.roe.latest
    sentiment_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    )

    rec_corredor = SimpleMovingAverage(
        inputs=[ConsensusRecommendations.total],
        window_length=3,
    )

    add_insider_transaction = SimpleMovingAverage(
        inputs=[
            Form3AggregatedTrades.slice(False, 90).num_unique_filers.latest
        ],
        window_length=1,
    )

    universe = QTradableStocksUS()

    value_winsorized = value.winsorize(min_percentile=0.05,
                                       max_percentile=0.95)

    quality_winsorized = quality.winsorize(min_percentile=0.05,
                                           max_percentile=0.95)

    sentiment_score_winsorized = sentiment_score.winsorize(min_percentile=0.05,
                                                           max_percentile=0.95)

    rec_corredor_winsorized = rec_corredor.winsorize(min_percentile=0.05,
                                                     max_percentile=0.95)

    add_insider_transaction_winsorized = add_insider_transaction.winsorize(
        min_percentile=0.05, max_percentile=0.95)

    combined_factor = (1 * value_winsorized.zscore() +
                       1 * quality_winsorized.zscore() +
                       1 * sentiment_score_winsorized.zscore() +
                       9 * rec_corredor_winsorized.zscore() +
                       1 * add_insider_transaction_winsorized.zscore())

    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