def initialize(context):
    window_length = 3
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='sentiment_metrics')
    dollar_volume = AvgDailyDollarVolumeTraded()

    # Add our AvgSentiment factor to the pipeline using a 3 day moving average
    pipe.add(
        AvgSentiment(inputs=[sentdex.sentiment_signal],
                     window_length=window_length), "avg_sentiment")

    # Screen out low liquidity securities.
    pipe.set_screen((dollar_volume > 10**7))
    context.shorts = None
    context.longs = None
    # context.spy = sid(8554)

    # Set commissions and slippage to zero to evaluate alpha generation
    # of the strategy
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))
    set_slippage(slippage.FixedSlippage(spread=0))

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(hours=1))
    schedule_function(record_vars, date_rules.every_day(),
                      time_rules.market_close())
示例#2
0
def initialize(context):
    # Create pipeline
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='factors')
    pipe.add(PsychSignal(), "psychsignal_sentiment")

    #Screen out penny stocks and low liquidity securities
    dollar_volume = AverageDollarVolume(window_length=20)

    # Only look at top 1000 most liquid securities
    liquidity_rank = dollar_volume.rank(ascending=False) < 200
    pipe.set_screen((dollar_volume > 10**7) & (liquidity_rank))

    # Set our shorts and longs and define our benchmark
    context.spy = sid(8554)
    context.shorts = None
    context.longs = None

    schedule_function(rebalance, date_rules.every_day())
    schedule_function(cancel_open_orders, date_rules.every_day(),
                      time_rules.market_close())
    set_commission(commission.PerShare(cost=0,
                                       min_trade_cost=0))  # no cost to trading

    set_slippage(slippage.FixedSlippage(spread=0))
def initialize(context):

    # Get continuous futures for VX...
    context.future = continuous_future('VX', adjustment=None)

    # Pulling VIX Spot data
    my_pipe = Pipeline()
    attach_pipeline(my_pipe, 'my_pipeline')
    my_pipe.add(GetVIX(inputs=[cboe_vix.vix_open]), 'vix')

    # Schedule function for stop loss
    '''
    time_interval = 30
    
    total_minutes = 6*60 + (60 - time_interval)
    
    for i in range(1, total_minutes):
        # Every 30 minutes run schedule
        if (i == 1) or (i % time_interval == 0):
            # This will start at 9:31AM and will run every 30 minutes
            schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=i))#,calendar=calendars.US_EQUITIES)
    '''

    # Rebalance function for trading VX futures
    schedule_function(rebalance,
                      date_rules.every_day(),
                      time_rules.market_open(minutes=30),
                      calendar=calendars.US_EQUITIES)

    context.enter_roll = 0.12
    context.exit_roll = 0.10
    context.lvg = 0.6
示例#4
0
def make_pipeline(context):
    pipe = Pipeline()
    
    # Add the two factors defined to the pipeline
    liquidity = Liquidity()
    pipe.add(liquidity, 'liquidity')
    
    quality = Quality()
    pipe.add(quality, 'roe')
    
    mkt_cap = MarketCap()
    pipe.add(mkt_cap, 'market cap')
    top_2000 = mkt_cap.top(1000)
    #1000 for best backtest result
    
    liquidity_rank = liquidity.rank(mask=top_2000)
    pipe.add(liquidity_rank, 'liq_rank')
    top_500 = liquidity_rank.top(200)
    #200 for best backtest result
    
    quality_rank = quality.rank(mask=top_500)
    pipe.add(quality_rank, 'roe_rank')
    
    # Set a screen to ensure that only the top 2000 companies by market cap 
    # with a roe > ___ are returned
    pipe.set_screen(top_500)
    return pipe
示例#5
0
def initialize(context):
    # set_commission(commission.PerShare(cost=0, min_trade_cost=None))
    # set_slippage(slippage.FixedSlippage(spread=0))

    pipe = Pipeline()
    attach_pipeline(pipe, 'ranked')
    dollar_volume = AverageDollarVolume(window_length=1)
    high_dollar_volume = dollar_volume.percentile_between(95, 100)
    alpha41 = Alpha41(mask=high_dollar_volume)
    vwap = VWAP(window_length=1)
    alpha41 = alpha41**.5 - vwap

    alpha41_rank = alpha41.rank(mask=high_dollar_volume)
    roe = ROE(mask=high_dollar_volume)

    combo_raw = (alpha41_rank)
    pipe.add(combo_raw, 'combo_raw')

    pipe.set_screen(roe > .005)

    schedule_function(func=rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(hours=0, minutes=1))

    context.long_leverage = .5
    context.short_leverage = -.5
    context.short_num = 20
    context.long_num = 20
示例#6
0
def make_pipeline(context):
    # Create our pipeline  
    pipe = Pipeline()  
    
    universe_filters = Q500US
    # Get PEADS Suprise factor
    factor = EarningsSurprises.eps_pct_diff_surp.latest
    # Get days since announcement
    days = BusinessDaysSinceEarningsSurprisesAnnouncement()
    # Get Sentiment Score
    article_sentiment = alphaone.article_sentiment.latest
  

    longs_factor = (factor >= 75) 
    shorts_factor = (factor <= -75)
    
    long_stocks = universe_filters() & longs_factor & article_sentiment.notnan() \
        & (article_sentiment >= 0.01)
    short_stocks = universe_filters() & shorts_factor & article_sentiment.notnan() \
        & (article_sentiment <= -0.01)

    # Add long/shorts to the pipeline  
    pipe.add(long_stocks, "longs")
    pipe.add(short_stocks, "shorts")
    pipe.add(days, 'days')
    pipe.add(article_sentiment, "sentiment")
    pipe.add(factor, "factor")
    pipe.set_screen(factor.notnan())
    return pipe  
示例#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
    """
    pipe = Pipeline()

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

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

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

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

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

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

    pipe.set_screen(securities_to_trade)

    return pipe
示例#8
0
def initialize(context):
    context.asset = sid(8554)
    context.count = 0
    context.burst_pri = 0.1
    context.time = 0
    context.timelap = 0
    context.volthreshold = 800000
    context.position = 0.5
    context.techsignal = 1.0
    pipe = Pipeline()
    attach_pipeline(pipe, 'my_pipeline')
    pipe.add(getindex(inputs=[cboe_vix.vix_close]), 'VixClose')
    pipe.add(getindex(inputs=[cboe_vxv.close]), 'VxvClose')
    schedule_function(func=start,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open())
    schedule_function(func=mood,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close())
    schedule_function(func=techind,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close())
    schedule_function(func=end,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close())
示例#9
0
def initialize(context):

    context.long_leverage = 0.50
    context.short_leverage = -0.50

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

    # Get the share class using .latest to get the most recent value
    share_class = morningstar.share_class_reference.is_primary_share.latest

    # Create and apply a filter representing the top 2000 equities by MarketCap every day
    # Mask out non primary share classes
    # This is an approximation of the Russell 2000
    mkt_cap = MarketCap()
    top_2000 = mkt_cap.top(2000, mask=share_class.eq(1))
    pipe.set_screen(top_2000)

    # add a 10 day returns factor to the pipeline
    # note we are declaring the window_length here becase no default was declared
    returns_10 = Returns(window_length=10)
    pipe.add(returns_10, 'returns_10')
    # add a factor to rank the returns, mask this with the top_2000 filters
    pipe.add(returns_10.rank(mask=top_2000, ascending=False),
             'returns_10_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)
示例#10
0
def make_pipeline(context):
    # Create our pipeline
    pipe = Pipeline()

    # Instantiating our factors
    factor = PercentSurprise()

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

    # Filter down to stocks in the top/bottom
    longs = (factor >= context.min_surprise) & (factor <= context.max_surprise)

    # Set our pipeline screens
    # Filter down stocks using sentiment
    article_sentiment = alphaone.article_sentiment.latest
    top_universe = is_liquid & longs & article_sentiment.notnan() & (
        article_sentiment > .45)

    # Add longs to the pipeline
    pipe.add(top_universe, "longs")
    pipe.add(BusinessDaysSincePreviousEarnings(), 'pe')

    return pipe
示例#11
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 make_pipeline(context, sma_window_length, market_cap_limit):
    pipe = Pipeline()

    # Now only stocks in the top N largest companies by market cap
    market_cap = MarketCap()
    top_N_market_cap = market_cap.top(market_cap_limit)

    #Other filters to make sure we are getting a clean universe
    is_primary_share = morningstar.share_class_reference.is_primary_share.latest
    is_not_adr = ~morningstar.share_class_reference.is_depositary_receipt.latest

    #### TREND FITLER ##############
    #### We don't want to trade stocks that are below their sma_window_length(100) moving average price.
    if context.use_stock_trend_filter:
        latest_price = USEquityPricing.close.latest
        sma = SimpleMovingAverage(inputs=[USEquityPricing.close],
                                  window_length=sma_window_length)
        above_sma = (latest_price > sma)
        initial_screen = (above_sma & top_N_market_cap & is_primary_share
                          & is_not_adr)
        log.info("Init: Stock trend filter ON")
    else:  #### TREND FITLER OFF  ##############
        initial_screen = (top_N_market_cap & is_primary_share & is_not_adr)
        log.info("Init: Stock trend filter OFF")

    pipe.add(market_cap, "market_cap")

    pipe.set_screen(initial_screen)

    return pipe
示例#13
0
def initialize(context):
    context.max_notional = 100000.1  
    context.min_notional = -100000.0
    context.stockpct= 0.1

    pipe = Pipeline()
    attach_pipeline(pipe, name='my_pipeline')
    pvol_factor = Parkinson(window_length=30)
    pvol_filter = pvol_factor.bottom(500)

    sma_30 = SimpleMovingAverage(inputs= [USEquityPricing.close], window_length=30)
    sma_10 = SimpleMovingAverage(inputs= [USEquityPricing.close], window_length=10)
    sma_5 = SimpleMovingAverage(inputs= [USEquityPricing.close], window_length=5)
    priceclose= PriceRange(window_length=1)
    price_filter= (priceclose > 10)
    dollar_volume= AvgDailyDollarVolumeTraded(window_length=30)
    dv_filter = dollar_volume > 100 * 10**5
    context.account.leverage= 1
    positive_movement= (sma_5 > sma_10)
    positive_movement_long= (sma_10 > sma_30)
    pipe.add(dv_filter, 'dv_filter')
    pipe.add(pvol_factor, 'pvol_factor')
    pipe.add(pvol_filter, 'pvol_filter')
    pipe.add(price_filter, 'price_filter')
    pipe.add(positive_movement, 'positive_movement')
    pipe.add(positive_movement_long, 'positive_movement_long')
    
    pipe.set_screen(price_filter & dv_filter & positive_movement & pvol_filter & positive_movement_long)
    schedule_function(func=trader, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0, minutes=5))
    schedule_function(func=liquidate, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0, minutes=1))
def my_pipeline(context):
    """
    A function to create our dynamic stock selector (pipeline). Documentation on
    pipeline can be found here: https://www.quantopian.com/help#pipeline-title
    """
    pipe = Pipeline()
    
    # span stands for past 120 days, need doulbe window length to get 120 data point.
    ewma120 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_long, span=context.look_back_long)
    pipe.add(ewma120, "ewma120")
    ewma60 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_middle, span=context.look_back_middle)
    pipe.add(ewma60, "ewma60")
    ewma15 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_short, span=context.look_back_short)
    pipe.add(ewma15, "ewma15")
    
    pipe.add(Latest(inputs=[USEquityPricing.close]), "yes_price")

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

    return pipe
def initialize(context):

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

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

    ev_ebitda = morningstar.valuation_ratios.ev_to_ebitda.latest > 0
    market_cap = morningstar.valuation.market_cap > 1e9

    pipe.add(piotroski, 'piotroski')
    pipe.set_screen(((piotroski >= 7) | (piotroski <= 3)) & ev_ebitda
                    & market_cap)
    context.is_month_end = False
    schedule_function(set_month_end, date_rules.month_end(1))
    schedule_function(trade_long, date_rules.month_end(),
                      time_rules.market_open())
    schedule_function(trade_short, date_rules.month_end(),
                      time_rules.market_open())
    schedule_function(trade, date_rules.month_end(), time_rules.market_close())

    # set the slippage and commision for the portfolio
    set_slippage_and_commisions()
def pipeline(context):

    # create pipeline
    pipe = Pipeline()

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

    return pipe
示例#17
0
def make_pipeline():
    minprice = USEquityPricing.close.latest > 5
    not_announced_acq_target = ~IsAnnouncedAcqTarget()
    pipe = Pipeline(screen=Q1500US() & minprice & not_announced_acq_target)
    
    sectors = Sector()
    pipe.add(sectors, 'sector')
    pipe.add(BusinessDaysSincePreviousEarnings(), 'PE')
    return pipe
def pipeline(context):

    # create pipeline
    pipe = Pipeline()

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

    return pipe
示例#19
0
def Data_Pull_TVF():

    Data_Pipe_TVF = Pipeline()
    Data_Pipe_TVF.add(SPY_proxy(), 'SPY Proxy')
    Data_Pipe_TVF.add(Div_Yield(), 'Dividend Yield')
    Data_Pipe_TVF.add(Price_to_Book(), 'Price to Book')
    Data_Pipe_TVF.add(Price_to_TTM_Sales(), 'Price / TTM Sales')
    Data_Pipe_TVF.add(Price_to_TTM_Cashflows(), 'Price / TTM Cashflow')

    return Data_Pipe_TVF
示例#20
0
def initialize(context):
    # SPY
    context.spy = sid(8554)
    context.gold = []
    pipe = Pipeline()
    pipe.add(Gold(), 'gold')
    attach_pipeline(pipe, 'gold')
    #que haga el rebalanceo de cada dia
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
示例#21
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()

    # Basic value and quality metrics.
    value = Value()
    pipe.add(value, "value")
    quality = Quality()
    pipe.add(quality, "quality")

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

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

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

    # Construct and add a Factor representing the average rank of each asset by our
    # value and quality metrics.
    # By applying a mask to the rank computations, we remove any stocks that failed
    # to meet our initial criteria **before** computing ranks.  This means that the
    # stock with rank 10.0 is the 10th-lowest stock that passed `initial_screen`.
    combined_rank = (value.rank(mask=initial_screen) +
                     quality.rank(mask=initial_screen))
    pipe.add(combined_rank, 'combined_rank')

    # 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.top(200)
    shorts = combined_rank.bottom(200)

    # The final output of our pipeline should only include
    # the top/bottom 200 stocks by our criteria.
    pipe.set_screen(longs | shorts)

    pipe.add(longs, 'longs')
    pipe.add(shorts, 'shorts')

    return pipe
示例#22
0
def initialize(context):

    # UNIVERSE DECLARATION
    universe = QTradableStocksUS()

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

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

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

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

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

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

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

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

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

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

    # COMMISSION SETTINGS (CAN BE ADJUSTED - SET TO INTERACTIVE BROKERS COMMISSION PRICING)
    set_commission(
        us_equities=commission.PerShare(cost=0.005, min_trade_cost=1))
示例#23
0
def initialize(context):
    # Robinhood only allows long positions, use this trading
    # guard in case
    set_long_only()

    # Since we are trading with Robinhood we can set this to $0!
    set_commission(commission.PerTrade(cost=0))

    # Define the instruments in the portfolio:
    context.sidsLongVol = sid(38054)  #VXX
    context.sidsShortVol = sid(40516)  #XIV
    context.sidsShortSPY = sid(22887)  #EDV
    context.sidsLongSPY = sid(8554)  #SPY

    context.ivts = []
    context.ivts_medianfiltered = []
    context.threshold = 1
    context.wait_trigger = False
    context.vixpipe = None

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

    fetch_csv(vxstUrl,
              symbol='VXST',
              date_column='Date',
              pre_func=addFields,
              post_func=shift_data)

    fetch_csv(vx1Url,
              symbol='VX1',
              date_column='Trade Date',
              pre_func=addFieldsVX,
              post_func=shift_dataVX)

    fetch_csv(vx2Url,
              symbol='VX2',
              date_column='Trade Date',
              pre_func=addFieldsVX,
              post_func=shift_dataVX)

    fetch_csv(vxvUrl,
              symbol='VXV',
              date_column='Date',
              pre_func=addFieldsVXV,
              post_func=shift_dataVXV)

    # Rebalance every day after market open.
    schedule_function(ordering_logic,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open())
示例#24
0
def high_dollar_volume_pipeline():
    # Create a pipeline object.
    pipe = Pipeline()

    # Create a factor for average dollar volume over the last 63 day (1 quarter equivalent).
    dollar_volume = AverageDollarVolume(window_length=63)
    pipe.add(dollar_volume, 'dollar_volume')

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

    return pipe
示例#25
0
def initialize(context):
    pipe = Pipeline()
    attach_pipeline(pipe, 'vix_pipeline')
    close = Latest(inputs=[USEquityPricing.close], window_length=1)
    pipe.add(close, 'Close')
    context.vxx = sid(38054)
    context.vxz = sid(38055)
    context.ivts = []
    context.vxx_weight = 0.0
    context.vxz_weight = 0.0
    fetch_csv(vxvurl,symbol='vxv', skiprows=2, date_column='Date', pre_func=addFieldsVXV)
    fetch_csv(vixurl,symbol='vix',skiprows=1,date_column='Date',pre_func=addFieldsVIX)
    schedule_function(ordering_logic, date_rule=date_rules.every_day(), time_rule=time_rules.market_close())
示例#26
0
def make_pipeline(context):
    """
    A function to create our pipeline (dynamic security selector). The pipeline is used
    to rank securities based on different factors, including builtin facotrs, or custom 
    factors that you can define. Documentation on pipeline can be found here:
        https://www.quantopian.com/help#pipeline-title
    """

    # Create a pipeline object.
    pipe = Pipeline()

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

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

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

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

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

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

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

    return pipe
def make_pipeline():

    pipe = Pipeline()

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

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

    momentum = Momentum()

    volatility = Volatility()

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

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

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

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

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

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

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

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

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


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


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

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

    return pipe
示例#28
0
def make_pipeline(context):
    # Create our pipeline
    pipe = Pipeline()

    # Instantiating our factors
    factor = EarningsSurprises.eps_pct_diff_surp.latest
    # Time of day that the earnings report happened
    # BTO - before the open, DTM - during the market,
    # AMC - after market close
    time_of_day = EarningsSurprises.act_rpt_code.latest

    # Filter down to stocks in the top/bottom according to
    # the earnings surprise
    longs = (factor >= context.min_surprise) & (factor <= context.max_surprise)
    shorts = (factor <= -context.min_surprise) & (factor >=
                                                  -context.max_surprise)

    # Set our pipeline screens
    # Filter down stocks using sentiment
    article_sentiment = alphaone.article_sentiment.latest
    top_universe = universe_filters() & longs & article_sentiment.notnan() \
        & (article_sentiment > .30)
    bottom_universe = universe_filters() & shorts & article_sentiment.notnan() \
        & (article_sentiment < -.50)

    # Add long/shorts to the pipeline
    pipe.add(top_universe, "longs")
    pipe.add(bottom_universe, "shorts")
    pipe.add(days_since_earnings(), 'pe')
    pipe.add(time_of_day, 'time_of_day')
    pipe.set_screen(factor.notnan())
    return pipe
示例#29
0
def initialize(context):
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='factors')

    value = Value()
    momentum = Momentum()
    quality = Quality()
    volatility = Volatility()

    pipe.add(value, "value")
    pipe.add(momentum, "momentum")
    pipe.add(quality, "quality")
    pipe.add(volatility, "volatility")

    dollar_volume = AverageDollarVolume(window_length=20)

    # Screen out low liquidity securities.
    pipe.set_screen(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())
    schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())
示例#30
0
def initialize(context):
    pipe = Pipeline()
    pipe = attach_pipeline(pipe, name='factors')

    value = Value()
    momentum = Momentum()
    quality = Quality()
    volatility = Volatility()

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

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

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

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

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

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

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

    my_screen = base_universe & high_dollar_volume
    pipe.set_screen(my_screen)
    return pipe
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()
示例#35
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 make_pipeline(context):
    """
    A function to create our pipeline (dynamic security selector). The pipeline is used
    to rank securities based on different factors, including builtin facotrs, or custom 
    factors that you can define. Documentation on pipeline can be found here:
        https://www.quantopian.com/help#pipeline-title
    """
    
    # Create a pipeline object. 
    pipe = Pipeline()
    
    # Create a dollar_volume factor using default inputs and window_length.
    # This is a builtin factor.
    dollar_volume = AverageDollarVolume(window_length=1)
    pipe.add(dollar_volume, 'dollar_volume')
    
    # Create a recent_returns factor with a 5-day returns lookback. This is
    # a custom factor defined below (see RecentReturns class).
    recent_returns = Returns(window_length=context.returns_lookback)
    pipe.add(recent_returns, 'recent_returns')
    
    # Define high dollar-volume filter to be the top 5% of securities by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(95, 100)
    
    # Define high and low returns filters to be the bottom 10% and top 10% of
    # securities in the high dollar-volume group.
    low_returns = recent_returns.percentile_between(0,10,mask=high_dollar_volume)
    high_returns = recent_returns.percentile_between(90,100,mask=high_dollar_volume)
    
    # Factors return a scalar value for each security in the entire universe
    # of securities. Here, we add the recent_returns rank factor to our pipeline
    # and we provide it with a mask such that securities that do not pass the mask
    # (i.e. do not have high dollar-volume), are not considered in the ranking.
    pipe.add(recent_returns.rank(mask=high_dollar_volume), 'recent_returns_rank')
    
    # Add a filter to the pipeline such that only high-return and low-return
    # securities are kept.
    pipe.set_screen(low_returns | high_returns)
    
    # Add the low_returns and high_returns filters as columns to the pipeline so
    # that when we refer to securities remaining in our pipeline later, we know
    # which ones belong to which category.
    pipe.add(low_returns, 'low_returns')
    pipe.add(high_returns, 'high_returns')
    
    return pipe
def 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())
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
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
示例#40
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