Esempio n. 1
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
    """
    
    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 pipeline(context):

    # create pipeline
    pipe = Pipeline()

    # Add market cap
    pipe.add(mkt_cap(), 'Market Cap')

    return pipe
def initialize(context):
       # Define the instruments in the portfolio:
    context.sidsLongVol  = {sid(38054): +1.0}
    context.sidsShortVol = {sid(40516): +1.0}
    context.sidsShortSPY = {sid(22887): +1.0}
    context.sidsLongSPY  = {sid(8554): +1.0}

    context.spy = symbol('SPY')
    context.hedge = symbol('IWM')
    context.vxx = symbol('VXX')
    context.epsilon = .01
    context.ivts=[]
    context.ivts_medianfiltered = []

    pipe = Pipeline()
    attach_pipeline(pipe, 'vix_pipeline')  
    pipe.add(GetVol(inputs=[cboe_vix.vix_close]), 'vix')
    pipe.add(GetVol(inputs=[cboe_vxv.close]), 'vxv')
    

    vxstUrl = 'http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vxstcurrent.csv'
    vx1Url = 'http://www.quandl.com/api/v1/datasets/CHRIS/CBOE_VX1.csv'
    vx2Url = 'http://www.quandl.com/api/v1/datasets/CHRIS/CBOE_VX2.csv'

    fetch_csv(vxstUrl, symbol='VXST', skiprows=3,date_column='Date', pre_func=addFieldsVXST)
    fetch_csv(vx1Url, date_column='Trade Date',date_format='%Y-%m-%d', symbol='v1', post_func=rename_col)
    fetch_csv(vx2Url, date_column='Trade Date',date_format='%Y-%m-%d', symbol='v2', post_func=rename_col)

    # Calculating the contango ratio of the front and second month VIX Futures settlements
    
    context.threshold = 0.90   #contango ratio threshold
    
    schedule_function(ordering_logic,date_rule=date_rules.every_day(),time_rule=time_rules.market_open(hours=0, minutes=1))
     # Rebalance every day, 1 hour after market open.

    context.wait_trigger=False
    
    context.vixpipe = None
    
    start_date = context.spy.security_start_date
    end_date   = context.spy.security_end_date
    context.algo_hist={}
    context.returns_df = pd.DataFrame()
 
    # Get the dates when the market closes early:
    context.early_closes = get_early_closes(start_date, end_date).date
    context.slopes = Series()
    context.betas = Series()
Esempio n. 4
0
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))
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())
Esempio n. 6
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
def Data_Pull():
    """
    Attach all CustomFactors to the Pipeline

    returns
    -------
    Pipeline (numpy.array)
        An array containing all data
        needed for the algorithm

    """

    # create the pipeline for the data pull
    Data_Pipe = Pipeline()

    # attach SPY proxy
    Data_Pipe.add(SPY_proxy(), 'SPY Proxy')

    """
        ADD COMPOSITE FACTORS with Data_Pipe.add(CUSTOMFACTOR) HERE
    """
    return Data_Pipe
Esempio n. 8
0
def initialize(context):  
    set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.00))
    schedule_function(func=monthly_rebalance, date_rule=date_rules.month_start(days_offset=10), time_rule=time_rules.market_open(), half_days=True)  
    schedule_function(func=daily_rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_close(hours=1))
    
    set_do_not_order_list(security_lists.leveraged_etf_list)
    context.canary = sid(8554)
    context.acc_leverage = 1.00 
    context.min_holdings = 50
    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)
    context.no_trade_yet = True
    context.buy_stocks = False
#    context.fct_window_length_1 = 20
#    context.fct_window_length_2 = 60
#    context.fct_window_length_3 = 125
#    context.fct_window_length_4 = 252
    
    context.safe = [
      sid(23870), #IEF
      sid(23921), #TLT
      sid(25485)  #AGG
    ]
       
    pipe = Pipeline()  
    attach_pipeline(pipe, 'ranked_stocks')  
    
#    factor1 = momentum_factor_1()  
    factor1 = Returns(window_length=fct_window_length_1)  
    pipe.add(factor1, 'factor_1')   
    '''
#    factor2 = momentum_factor_2()  
    factor2 = Returns(window_length=context.fct_window_length_2)  
    pipe.add(factor2, 'factor_2')  
#    factor3 = momentum_factor_3()  
    factor3 = Returns(window_length=context.fct_window_length_3)  
    pipe.add(factor3, 'factor_3')  
#    factor4 = momentum_factor_4()  
    factor4 = Returns(window_length=context.fct_window_length_4)  
    pipe.add(factor4, 'factor_4') 
    '''    
    factor5=efficiency_ratio()
    pipe.add(factor5, 'factor_5')
    factor6 = AverageDollarVolume(window_length=20)
    pipe.add(factor6, 'factor_6')
        
    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
    total_filter = (stocks & factor_5_filter & factor_6_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')   
    combo_rank = MomentumRanking(mask=total_filter)
    pipe.add(combo_rank, 'combo_rank')
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,
    )

    growthh = Fundamentals.growth_score.latest
    value_score = Fundamentals.value_score.latest
    profitability_grade = Fundamentals.profitability_grade.latest
    basic_average_shares = Fundamentals.basic_average_shares_earnings_reports.latest

    a = Fundamentals.current_ratio.latest
    b = Fundamentals.accumulated_depreciation.latest
    c = Fundamentals.ps_ratio.latest
    d = Fundamentals.style_score.latest
    #e = Fundamentals2.turn_rate_af.latest
    #f = Fundamentals.
    #g = Fundamentals.

    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.0, max_percentile=1)

    quality_winsorized = quality.winsorize(min_percentile=0.00,
                                           max_percentile=1)

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

    growthh_winsorized = growthh.winsorize(min_percentile=0.05,
                                           max_percentile=0.95)

    value_score_winsorized = value_score.winsorize(min_percentile=0.05,
                                                   max_percentile=0.95)

    basic_average_shares_winzorized = basic_average_shares.winsorize(
        min_percentile=0.05, max_percentile=0.95)

    a_winso = a.winsorize(min_percentile=0.05, max_percentile=0.95)

    b_winso = b.winsorize(min_percentile=0.05, max_percentile=0.95)

    c_winso = c.winsorize(min_percentile=0.05, max_percentile=0.95)

    d_winso = d.winsorize(min_percentile=0.05, max_percentile=0.95)

    #e_winso = e.winsorize(min_percentile=0.05,                   max_percentile=0.95)

    #f_winso = f.winsorize(min_percentile=0.05,                   max_percentile=0.95)

    #g_winso = g.winsorize(min_percentile=0.05,                   max_percentile=0.95)

    #profitability_grade_winsorized = profitability_grade.winsorize(min_percentile=0.05,max_percentile=0.95)

    # Here we combine our winsorized factors, z-scoring them to equalize their influence
    combined_factor = (
        #(1*value_winsorized.zscore() )
        #(-1.1*quality_winsorized.zscore() )+
        #(1*sentiment_score_winsorized.zscore())
        (1.4 * growthh_winsorized.zscore()) +
        (-1.6 * value_score_winsorized.zscore()) + (0.6 * a_winso.zscore()) +
        (0.8 * b_winso.zscore()) + (2.3 * c_winso.zscore()) +
        (0.75 * d_winso.zscore())
        #(1*e_winso.zscore())
        #(f_winso.zscore())
        #(-0.1*basic_average_shares_winzorized.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(2 * 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
def make_pipeline():
    """
    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.
 
    Returns
    -------
    pipe : Pipeline
        Represents computation we would like to perform on the assets that make
        it through the pipeline screen.
    """
    # The factors we create here are based on fundamentals data and a moving
    # average of sentiment data
    total_revenue = FundaMorningstar.total_revenue.latest

    yesterday_close = EquityPricing.close.latest
    yesterday_volume = EquityPricing.volume.latest
    yesterday = yesterday_close / yesterday_volume

    quarterly_sales = FundaFactset.sales_qf.latest

    amortization_income = FundaMorningstar.amortization_income_statement.latest
    administrative_expense = FundaMorningstar.administrative_expense.latest

    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
    total_revenue_winsorized = total_revenue.winsorize(min_percentile=0.05,
                                                       max_percentile=0.95)
    yesterday_winsorize = yesterday.winsorize(min_percentile=0.05,
                                              max_percentile=0.95)
    quarterly_sales_winsorize = quarterly_sales.winsorize(min_percentile=0.05,
                                                          max_percentile=0.95)
    amortization_winsorize = amortization_income.winsorize(min_percentile=0.05,
                                                           max_percentile=0.95)
    administrative_expense_winsorize = administrative_expense.winsorize(
        min_percentile=0.05, max_percentile=0.95)

    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)

    # 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() +
                       total_revenue_winsorized.zscore() +
                       yesterday_winsorize.zscore() +
                       quarterly_sales_winsorize.zscore() +
                       administrative_expense_winsorize.zscore() +
                       amortization_winsorize.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
Esempio n. 11
0
def initialize(context):

    schedule_function(
        func=periodic_rebalance,
        date_rule=date_rules.every_day(),  #week_start(days_offset=1),
        time_rule=time_rules.market_open(hours=.5))

    schedule_function(my_rebalance, date_rules.every_day(),
                      time_rules.market_open(hours=0, minutes=1))
    #schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1, minutes=1))
    schedule_function(my_rebalance, date_rules.every_day(),
                      time_rules.market_open(hours=2, minutes=1))
    #schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=3, minutes=1))
    schedule_function(my_rebalance, date_rules.every_day(),
                      time_rules.market_open(hours=4, minutes=1))
    #schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=5, minutes=1))
    schedule_function(my_rebalance, date_rules.every_day(),
                      time_rules.market_open(hours=6, minutes=1))

    #schedule_function(
    #    do_portfolio_construction,
    #    date_rule=algo.date_rules.week_start(),
    #    time_rule=algo.time_rules.market_open(minutes=30),
    #    half_days=False,
    #    )

    for hours_offset in range(7):
        schedule_function(my_rebalance,
                          date_rules.every_day(),
                          time_rules.market_open(hours=hours_offset,
                                                 minutes=10),
                          half_days=True)


#
# set portfolis parameters
#
    set_asset_restrictions(security_lists.restrict_leveraged_etfs)
    context.acc_leverage = 1.00
    context.min_holdings = 20
    context.s_min_holdings = 10
    #
    # set profit taking and stop loss parameters
    #
    context.profit_taking_factor = 0.01
    context.profit_taking_target = 100.0  #set much larger than 1.0 to disable
    context.profit_target = {}
    context.profit_taken = {}
    context.stop_pct = 0.97  # set to 0.0 to disable
    context.stop_price = defaultdict(lambda: 0)
    #
    # Set commission model to be used
    #
    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

    # Define safe set (of bonds)
    #sid(32268) #SH
    context.safe = [
        sid(23870),  #IEF
        sid(23921),  #TLT
        #sid(8554), #SPY
    ]
    #
    # Define proxy to be used as proxy for overall stock behavior
    # set default position to be in safe set (context.buy_stocks = False)
    #
    context.canary = sid(22739)  #why not spy
    context.buy_stocks = False
    #
    # Establish pipeline
    #
    pipe = Pipeline()
    attach_pipeline(pipe, 'ranked_stocks')

    #
    # Define the four momentum factors used in ranking stocks
    #
    factor1 = simple_momentum(window_length=1)
    pipe.add(factor1, 'factor_1')
    factor2 = simple_momentum(window_length=60) / Volatility(window_length=60)
    pipe.add(factor2, 'factor_2')
    factor3 = simple_momentum(window_length=252)
    pipe.add(factor3, 'factor_3')
    factor4 = ((Momentum() / Volatility()) + Momentum())  #or Downside_Risk()
    pipe.add(factor4, 'factor_4')
    factor8 = earning_yield()
    pipe.add(factor8, 'factor8')
    factor9 = roe() + roic() + roa()
    pipe.add(factor9, 'factor9')
    factor10 = cash_return()
    pipe.add(factor10, 'factor10')
    factor11 = fcf_yield()
    pipe.add(factor11, 'factor11')
    factor12 = current_ratio()
    pipe.add(factor12, 'factor12')
    factor13 = Quality()
    pipe.add(factor13, 'factor13')
    factor14 = market_cap()
    pipe.add(factor14, 'factor14')
    factor15 = RnD_to_market() + capex()
    pipe.add(factor15, 'factor15')
    factor18 = EPS_Growth_3M()
    pipe.add(factor18, 'factor18')
    factor19 = Piotroski4()
    pipe.add(factor19, 'factor19')
    factor20 = capex()
    pipe.add(factor20, 'factor20')
    #
    # Define other factors that may be used in stock screening
    #
    #factor5 = get_fcf_per_share()
    #pipe.add(factor5, 'factor_5')
    factor6 = AverageDollarVolume(window_length=60)
    pipe.add(factor6, 'factor_6')
    factor7 = get_last_close()
    pipe.add(factor7, 'factor_7')

    #factor_4_filter = factor4 > 1.03   # only consider stocks with positive 1y growth
    #factor_5_filter = factor5 > 0.0   # only  consider stocks with positive FCF
    factor_6_filter = factor6 > .5e6  # only consider stocks trading >$500k per day
    #factor_7_filter = factor7 > 3.00  # only consider stocks that close above this value
    factor_12_filter = factor12 > .99
    #factor_8_filter = factor8 > 0
    #factor_15_filter = factor15 > factor6
    #factor_1_filter = factor1 > 1.1
    #factor_2_filter = factor2 > 1
    #factor_20_filter = factor20 > 0
    utilities_filter = Sector() != 207
    materials_filter = Sector() != 101
    energy_filter = Sector() != 309
    industrial_filter = Sector() != 310
    health_filter = Sector() != 206
    staples_filter = Sector() != 205
    real_estate_filter = Sector() != 104
    #sentiment_filter = ((0.5*st.bull_scored_messages.latest)>(st.bear_scored_messages.latest)) & (st.bear_scored_messages.latest > 10)
    consumer_cyclical_filter = Sector() != 102
    financial_filter = Sector() != 103
    communication_filter = Sector() != 308
    technology_filter = Sector != 311

    #Basic_Materials = context.output[context.output.sector == 101]
    #Consumer_Cyclical = context.output[context.output.sector == 102]
    #Financial_Services = context.output[context.output.sector == 103]
    #Real_Estate = context.output[context.output.sector == 104]
    #Consumer_Defensive = context.output[context.output.sector == 205]
    #Healthcare = context.output[context.output.sector == 206]
    #Utilities = context.output[context.output.sector == 207]
    #Communication_Services = context.output[context.output.sector == 308]
    #Energy = context.output[context.output.sector == 309]
    #Industrials = context.output[context.output.sector == 310]
    #Technology = context.output[context.output.sector == 311]
    #
    # Establish screen used to establish candidate stock list
    #
    mkt_screen = market_cap()
    cash_flow = factor10 + factor11
    price = factor14
    profitability = factor9
    #earning_quality = factor15
    stocks = QTradableStocksUS(
    )  #mkt_screen.top(3500)&profitability.top(3500)&factor19.top(2000)#&factor8.top(2000)#&price.top(2000)#&factor15.top(3000)#
    total_filter = (
        stocks
        & factor_6_filter
        #& factor_15_filter
        #& factor_8_filter
        #& factor_9_filter
        #& factor_1_filter
        #& factor_20_filter
        #& communication_filter
        #& consumer_cyclical_filter
        #& financial_filter
        #& staples_filter
        #& materials_filter
        #& industrial_filter
        #& factor_12_filter
        #& technology_filter
    )

    pipe.set_screen(total_filter)
    #
    # Establish ranked stock list
    #
    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)  #significant effect
    pipe.add(factor3_rank, 'f3_rank')
    factor4_rank = factor4.rank(mask=total_filter,
                                ascending=False)  #significant effect
    pipe.add(factor4_rank, 'f4_rank')
    factor8_rank = factor8.rank(mask=total_filter,
                                ascending=False)  #significant effect
    pipe.add(factor8_rank, 'f8_rank')
    factor9_rank = factor9.rank(mask=total_filter,
                                ascending=False)  #very big effect
    pipe.add(factor9_rank, 'f9_rank')
    factor10_rank = factor10.rank(mask=total_filter, ascending=False)
    pipe.add(factor10_rank, 'f10_rank')
    factor11_rank = factor11.rank(mask=total_filter, ascending=False)
    pipe.add(factor11_rank, 'f11_rank')
    factor13_rank = factor13.rank(mask=total_filter,
                                  ascending=False)  #may want to remove
    pipe.add(factor13_rank, 'f13_rank')
    factor14_rank = factor14.rank(mask=total_filter, ascending=True)
    pipe.add(factor14_rank, 'f14_rank')
    factor15_rank = factor15.rank(mask=total_filter, ascending=False)
    pipe.add(factor15_rank, 'f15_rank')
    factor18_rank = factor18.rank(mask=total_filter, ascending=False)
    pipe.add(factor18_rank, 'f18_rank')
    factor19_rank = factor19.rank(mask=total_filter, ascending=False)
    pipe.add(factor19_rank, 'f19_rank')
    factor20_rank = factor20.rank(mask=total_filter, ascending=False)
    pipe.add(factor20_rank, 'f20_rank')

    combo_raw = (factor8_rank + factor18_rank + factor1_rank + factor4_rank +
                 factor10_rank + factor11_rank + factor15_rank + factor9_rank +
                 factor19_rank)  #+factor14_rank*.5)
    pipe.add(combo_raw, 'combo_raw')
    pipe.add(combo_raw.rank(mask=total_filter), 'combo_rank')
Esempio n. 12
0
def initialize(context):
    set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.00))
    schedule_function(func=monthly_rebalance,
                      date_rule=date_rules.month_start(days_offset=5),
                      time_rule=time_rules.market_open(),
                      half_days=True)
    schedule_function(func=daily_rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(hours=1))

    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_cap = morningstar.valuation.market_cap.latest
    mkt_cap_rank = mkt_cap.rank(ascending=True)
    pipe.add(mkt_cap_rank, 'mkt_cap_rank')
    stocks = mkt_cap_rank.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')
Esempio n. 13
0
def initialize(context):
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='factors')
    
    pipe.add(Value(), "value")
    pipe.add(Momentum(), "momentum")
    pipe.add(Quality(), "quality")
    pipe.add(Volatility(), "volatility")
    
    sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200)
    dollar_volume = AvgDailyDollarVolumeTraded()
    
    # Screen out penny stocks and low liquidity securities.
    pipe.set_screen((sma_200 > 5) & (dollar_volume > 10**7))
    
    context.spy = sid(8554)
    context.shorts = None
    context.longs = None
    
    schedule_function(rebalance, date_rules.month_start())
    schedule_function(cancel_open_orders, date_rules.every_day(),
                      time_rules.market_close())
def make_pipeline():
    """
    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.
 
    Returns
    -------
    pipe : Pipeline
        Represents computation we would like to perform on the assets that make
        it through the pipeline screen.
    """
    # 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
    foo = Fundamentals.diluted_cont_eps_growth.latest
    var = Fundamentals.size_score.latest
    aux = Fundamentals.value_score.latest
    res = Fundamentals.accounts_payable.latest
    x = Fundamentals.accumulated_depreciation.latest
    y = Fundamentals.book_value_per_share.latest
    s = Fundamentals.working_capital_per_share.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)
    foo_winsorized = foo.winsorize(min_percentile=0.05, max_percentile=0.95)
    var_winsorized = var.winsorize(min_percentile=0.05, max_percentile=0.95)
    aux_winsorized = aux.winsorize(min_percentile=0.05, max_percentile=0.95)
    res_winsorized = res.winsorize(min_percentile=0.05, max_percentile=0.95)
    x_winsorized = x.winsorize(min_percentile=0.05, max_percentile=0.95)
    y_winsorized = y.winsorize(min_percentile=0.05, max_percentile=0.95)
    s_winsorized = s.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() -
                       foo_winsorized.zscore() + var_winsorized.zscore() +
                       aux_winsorized.zscore() - res_winsorized.zscore() -
                       x_winsorized.zscore() + y_winsorized.zscore() -
                       s_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
Esempio n. 15
0
def make_pipeline():

    base_universe = QTradableStocksUS()

    latest_close = USEquityPricing.close.latest
    latest_volume = USEquityPricing.volume.latest
    latest_close = USEquityPricing.close.latest
    mkt_cap = morningstar.valuation.market_cap.latest
    symbol_float1 = morningstar.Fundamentals.shares_outstanding.latest
    symbol_float2 = morningstar.Fundamentals.ordinary_shares_number.latest
    morningstar_sector = Sector()

    volume_3_months = AverageDollarVolume(
        window_length=66,
        mask=base_universe & (mkt_cap < 5000000000)  #masking 
    )

    volume_1_day = AverageDollarVolume(
        window_length=1,
        mask=base_universe & (mkt_cap < 5000000000)  #masking 
    )

    mean_close_30 = SimpleMovingAverage(
        inputs=[USEquityPricing.close],
        window_length=30,
        mask=base_universe & (mkt_cap < 5000000000)  #masking
    )

    rv = volume_1_day / volume_3_months

    high_52_w = High252()
    high_3_m = High66()
    low_52_w = Low252()

    # price at 30%, 50%, 60% and 90% respectively of the yearly price range
    third_range = (high_52_w - low_52_w) * (1 / 3) + low_52_w
    half_range = (high_52_w - low_52_w) * 0.5 + low_52_w
    sixty_range = (high_52_w - low_52_w) * 0.6 + low_52_w
    ninty_range = (high_52_w - low_52_w) * 0.9 + low_52_w
    fifteen_range = (high_52_w - low_52_w) * 0.15 + low_52_w

    #create the price range for potential longs
    long_range = (latest_close <= sixty_range) & (latest_close >= third_range)

    #take profit range
    tp_range = latest_close >= ninty_range

    #stop loss range
    sl_range = latest_close <= fifteen_range

    valid_open_position_range = (latest_close <=
                                 ninty_range) & (latest_close >= fifteen_range)

    #filters (the data type is a zipline pipeline filter not a df)
    # returns True or False per row (per symbol):
    close_price_filter = (latest_close < 15)
    price_under_30mva = latest_close < mean_close_30  #price under 30 mva

    #create a list of stocks for potential longs
    universe = close_price_filter & base_universe & (mkt_cap < 5000000000)

    # create the "go long" critera
    longs = price_under_30mva & long_range

    return Pipeline(columns={
        'latest_close': latest_close,
        'rv': rv,
        'stop_loss': sl_range,
        'take_profit': tp_range,
        'valid_open_position': valid_open_position_range,
        'longs': longs
    },
                    screen=universe)
def Data_Pull():

    # create the pipeline for the data pull
    Data_Pipe = Pipeline()

    # create SPY proxy
    Data_Pipe.add(SPY_proxy(), "SPY Proxy")

    # Div Yield
    Data_Pipe.add(Div_Yield(), "Dividend Yield")

    # Price to Book
    Data_Pipe.add(Price_to_Book(), "Price to Book")

    # Price / TTM Sales
    Data_Pipe.add(Price_to_TTM_Sales(), "Price / TTM Sales")

    # Price / TTM Cashflows
    Data_Pipe.add(Price_to_TTM_Cashflows(), "Price / TTM Cashflow")

    return Data_Pipe
Esempio n. 17
0
def make_pipeline():
    """
    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.

    Returns
    -------
    pipe : Pipeline
        Represents computation we would like to perform on the assets that make
        it through the pipeline screen.
    """
    # 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,
    )
    
    ppe = Fundamentals.sale_of_ppe.latest
    cap_mercado = Fundamentals.market_cap.latest
    assets = Fundamentals.assets_turnover.latest
    expenses = Fundamentals.administrative_expense.latest
    gr_loan = Fundamentals.gross_loan.latest
    universe = QTradableStocksUS()
    income_tax = Fundamentals.income_tax_payable.latest
    
    # 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)
    
    ppe_winsorized = ppe.winsorize(min_percentile=0.05,    max_percentile=0.95)
    cap_mercado_winsorized = cap_mercado.winsorize(min_percentile=0.05,    max_percentile=0.95)
    
    assets_winsorized = assets.winsorize(min_percentile=0.05,    max_percentile=0.95)
    
    expenses_winsorized = expenses.winsorize(min_percentile=0.05,    max_percentile=0.95)
    
    gr_loan_winsorized = gr_loan.winsorize(min_percentile=0.05,    max_percentile=0.95)
    
    income_tax_winsorized = income_tax.winsorize(min_percentile=0.05,    max_percentile=0.95)
    
    value_weight = 0.14
    quality_weight = 0.14
    sentiment_score_weight = 0.14
    ppe_weight = 0.10
    cap_mercado_weight = 0.4
    assets_weight = 0.5
    expenses_weight = 0.2
    gr_loan_weight = 0.5
    income_tax_weight = 0.3
    #weights
    
    # Here we combine our winsorized factors, z-scoring them to equalize their influence
    combined_factor = (
        value_winsorized.zscore() * value_weight + 
        quality_winsorized.zscore() * quality_weight + 
        sentiment_score_winsorized.zscore() * sentiment_score_weight +
        ppe_winsorized.zscore() * ppe_weight + 
        cap_mercado_winsorized.zscore() * cap_mercado_weight +
        assets_winsorized.zscore() * assets_weight +
        expenses_winsorized.zscore() * expenses_weight +
        gr_loan_winsorized.zscore() * gr_loan_weight +
        income_tax_winsorized.zscore() * income_tax_weight
    )

    # 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
Esempio n. 18
0
def make_pipeline():
    """
    Create our pipeline.
    """

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

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

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

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

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

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

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

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

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

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

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

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

    percent_difference = (mean_10 - mean_30) / mean_30

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

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

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

    return Pipeline(
        columns={
            'longs': longs,
            'shorts': shorts
        },
        screen=(securities_to_trade),
    )
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.
    """

    # Create our sentiment, value, and quality factors
    sentiment = Sentiment()
    # By appending .latest to the imported morningstar data, we get builtin Factors
    # so there's no need to define a CustomFactor
    value = morningstar.income_statement.ebit.latest / morningstar.valuation.enterprise_value.latest
    quality = morningstar.operation_ratios.roe.latest

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

    # Screen out non-desirable securities by defining our universe.
    # Removes ADRs, OTCs, non-primary shares, LP, etc.
    # Also sets a minimum $500MM market cap filter and $5 price filter
    mkt_cap_filter = morningstar.valuation.market_cap.latest >= 500000000
    price_filter = USEquityPricing.close.latest >= 5
    universe = Q1500US() & price_filter & mkt_cap_filter

    # Construct a Factor representing the rank of each asset by our sentiment,
    # value, and quality metrics. We aggregate them together here using simple
    # addition.
    #
    # By applying a mask to the rank computations, we remove any stocks that failed
    # to meet our initial criteria **before** computing ranks.  This means that the
    # stock with rank 10.0 is the 10th-lowest stock that was included in the Q1500US.
    combined_rank = (sentiment.rank(mask=universe).zscore() +
                     value.rank(mask=universe).zscore() +
                     quality.rank(mask=universe).zscore())

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

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

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

    # Create pipeline
    pipe = Pipeline(columns={
        'longs': longs,
        'shorts': shorts,
        'combined_rank': combined_rank,
        'quality': quality,
        'value': value,
        'sentiment': sentiment,
        'sector': sector,
        'market_beta': beta
    },
                    screen=long_short_screen)
    return pipe
Esempio n. 20
0
def make_pipeline():
  return Pipeline()
Esempio n. 21
0
def make_pipeline(context):
    
    # 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 stocks 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) & high_dollar_volume)
    
    # 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():
    """
    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.
    Returns
    -------
    pipe : Pipeline
        Represents computation we would like to perform on the assets that make
        it through the pipeline screen.
    """
    # 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,
    )
    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

    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
    )

    percent_difference_winsorized = percent_difference.winsorize(
        min_percentile=0.1,
        max_percentile=0.9
    )

    recent_returns = Returns(window_length=5)

    fq1_eps_cons = fe.PeriodicConsensus.slice('EPS', 'qf', 2)
    fq1_eps_cons_up = fq1_eps_cons.up.latest
    fq1_eps_cons_down = fq1_eps_cons.down.latest

    fq_tot = fq1_eps_cons_up - fq1_eps_cons_down
    fq_tot_windsorized = fq_tot.winsorize(min_percentile=0.01, max_percentile=0.99)

    # 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() +
            0.05 * percent_difference_winsorized.zscore() +
            0.05 * fq_tot_windsorized.zscore() +
            0.1 * recent_returns.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
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
Esempio n. 24
0
def make_pipeline(context):
    """
    Create our pipeline.
    """

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

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

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

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

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

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

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

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

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

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

    LowVar = 6
    HighVar = 40

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

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

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

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

    percent_difference = (ShortAvg - LongAvg) / LongAvg

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

    return Pipeline(
        columns={'stocks_worst': stocks_worst},
        screen=(securities_to_trade),
    )
Esempio n. 25
0
def make_pipeline():
    """
    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.

    Returns
    -------
    pipe : Pipeline
        Represents computation we would like to perform on the assets that make
        it through the pipeline screen.
    """
    # The factors we create here are based on fundamentals data and a moving
    # average of sentiment data
    value = Fundamentals.ebit.latest * 0.6/ Fundamentals.enterprise_value.latest 
    quality = Fundamentals.roe.latest + Fundamentals.ebit.latest 
    sentiment_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length= 21,
    )
    
    
    growth_score = Fundamentals.growth_score.latest
    #print(value)
    gross_profit = Fundamentals.gross_profit.latest
    equity_per_share_growth = Fundamentals.equity_per_share_growth.latest
      
    #dps_growth = Fundamentals.dps_growth.latest
    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
    # 0.05 - 0.95
    #dps_growth_winsorized = dps_growth.winsorize(min_percentile=0.05, max_percentile=0.95)
    
    eps_growth_winsorized = equity_per_share_growth.winsorize(min_percentile=0.05, max_percentile=0.95)
    
    gross_profit_winsorized = gross_profit.winsorize(min_percentile=0.05, max_percentile=0.95)
    
    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)
    
    growth_score_winsorized = growth_score.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() * 0.8 + 
        sentiment_score_winsorized.zscore() * 0.5 +
        growth_score_winsorized  * 0.8 +
        gross_profit_winsorized * 0.3 +  #rth
        eps_growth_winsorized * 0.8
        
    )

    # 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.top(0.45*TOTAL_POSITIONS//2, mask=universe)
    shorts = combined_factor.bottom(0.35*TOTAL_POSITIONS//2, mask=universe)
    
    longs = combined_factor.top(0.35*TOTAL_POSITIONS//2, mask=universe)
    shorts = combined_factor.bottom(0.35*TOTAL_POSITIONS//2, mask=universe)
    '''
    longs = combined_factor.top(0.8*TOTAL_POSITIONS//2, mask=universe)
    shorts = combined_factor.bottom(0.85*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
Esempio n. 26
0
def make_pipeline():
    """
    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.
 
    Returns
    -------
    pipe : Pipeline
        Represents computation we would like to perform on the assets that make
        it through the pipeline screen.
    """
    # The factors we create here are based on fundamentals data and a moving
    # average of sentiment data
    value = Fundamentals.ebit.latest
    quality = Fundamentals.roe.latest
    sentiment_score = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    )
    total_revenue = Fundamentals.total_revenue.latest

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

    positive_sentiment_pctt = (
        twitter_sentiment2.bull_scored_messages.latest /
        twitter_sentiment2.total_scanned_messages.latest)

    value_morning = Fundamentals.ebit.latest

    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)
    total_revenue_winsorized = total_revenue.winsorize(min_percentile=0.05,
                                                       max_percentile=0.95)
    positive_sentiment_pct_winsorized = positive_sentiment_pct.winsorize(
        min_percentile=0.05, max_percentile=0.95)
    positive_sentiment_pctt_winsorized = positive_sentiment_pctt.winsorize(
        min_percentile=0.05, max_percentile=0.95)
    value_morning_winsorized = value_morning.winsorize(min_percentile=0.05,
                                                       max_percentile=0.95)
    # Here we combine our winsorized factors, z-scoring them to equalize their influence
    combined_factor = (0.2 * value_winsorized.zscore() +
                       0.2 * quality_winsorized.zscore() +
                       0.2 * sentiment_score_winsorized.zscore() +
                       0.1 * total_revenue_winsorized.zscore() +
                       0.1 * positive_sentiment_pct_winsorized +
                       0.1 * positive_sentiment_pctt_winsorized +
                       value_morning_winsorized)
    # 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,
        'total_revenue': total_revenue,
        'positive_sentiment_pct': positive_sentiment_pct,
        'positive_sentiment_pctt': positive_sentiment_pctt,
        'value_morning_winsorized': value_morning
    },
                    screen=long_short_screen)
    return pipe
Esempio n. 27
0
def initialize(context):

    context.long_leverage = 0.50
    context.short_leverage = -0.50

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

    #add the two factors defined to the pipeline
    factor1 = Factor1()
    pipe.add(factor1, 'factor_1')
    factor2 = Factor2()
    pipe.add(factor2, 'factor_2')

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

    mkt_cap = MarketCap()
    top_2000 = mkt_cap.top(2000)
    pipe.set_screen(top_2000)

    # Rank factor 1 and add the rank to our pipeline
    factor1_rank = factor1.rank(mask=top_2000)
    pipe.add(factor1_rank, 'f1_rank')
    # Rank factor 2 and add the rank to our pipeline
    factor2_rank = factor2.rank(mask=top_2000)
    pipe.add(factor2_rank, 'f2_rank')
    # Take the average of the two factor rankings, add this to the pipeline
    combo_raw = (factor1_rank + factor2_rank)
    pipe.add(combo_raw, 'combo_raw')
    # Rank the combo_raw and add that to the pipeline
    pipe.add(combo_raw.rank(mask=top_2000), 'combo_rank')

    # 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)
Esempio n. 28
0
def make_pipeline():
    Universe = Q500US()
    pipe = Pipeline(screen=Universe)
    return pipe