def initialize(context): set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.00)) schedule_function(func=rebalance, date_rule=date_rules.month_start(days_offset=5), time_rule=time_rules.market_open(), half_days=True) schedule_function(close_orders, date_rule=date_rules.week_end(), time_rule=time_rules.market_close()) set_do_not_order_list(security_lists.leveraged_etf_list) context.acc_leverage = 1.00 context.holdings = 10 context.profit_taking_factor = 0.01 context.profit_target = {} context.profit_taken = {} context.entry_date = {} context.stop_pct = 0.75 context.stop_price = defaultdict(lambda: 0) pipe = Pipeline() attach_pipeline(pipe, 'ranked_stocks') factor1 = momentum_factor_1() pipe.add(factor1, 'factor_1') factor2 = momentum_factor_2() pipe.add(factor2, 'factor_2') factor3 = momentum_factor_3() pipe.add(factor3, 'factor_3') factor4 = momentum_factor_4() pipe.add(factor4, 'factor_4') factor5 = efficiency_ratio() pipe.add(factor5, 'factor_5') mkt_screen = market_cap() stocks = mkt_screen.top(3000) factor_5_filter = factor5 > 0.031 total_filter = (stocks & factor_5_filter) pipe.set_screen(total_filter) factor1_rank = factor1.rank(mask=total_filter, ascending=False) pipe.add(factor1_rank, 'f1_rank') factor2_rank = factor2.rank(mask=total_filter, ascending=False) pipe.add(factor2_rank, 'f2_rank') factor3_rank = factor3.rank(mask=total_filter, ascending=False) pipe.add(factor3_rank, 'f3_rank') factor4_rank = factor4.rank(mask=total_filter, ascending=False) pipe.add(factor4_rank, 'f4_rank') combo_raw = (factor1_rank + factor2_rank + factor3_rank + factor4_rank) / 4 pipe.add(combo_raw, 'combo_raw') pipe.add(combo_raw.rank(mask=total_filter), 'combo_rank')
def make_pipeline(context): """ A function to create our pipeline (dynamic security selector). The pipeline is used to rank securities based on different factors, including builtin facotrs, or custom factors that you can define. Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ # Create a pipeline object. pipe = Pipeline() # Create a dollar_volume factor using default inputs and window_length. # This is a builtin factor. dollar_volume = AverageDollarVolume(window_length=1) pipe.add(dollar_volume, 'dollar_volume') # Create a recent_returns factor with a 5-day returns lookback. This is # a custom factor defined below (see RecentReturns class). recent_returns = Returns(window_length=context.returns_lookback) pipe.add(recent_returns, 'recent_returns') # Define high dollar-volume filter to be the top 5% of securities by dollar volume. high_dollar_volume = dollar_volume.percentile_between(95, 100) # Define high and low returns filters to be the bottom 10% and top 10% of # securities in the high dollar-volume group. low_returns = recent_returns.percentile_between(0, 10, mask=high_dollar_volume) high_returns = recent_returns.percentile_between(90, 100, mask=high_dollar_volume) # Factors return a scalar value for each security in the entire universe # of securities. Here, we add the recent_returns rank factor to our pipeline # and we provide it with a mask such that securities that do not pass the mask # (i.e. do not have high dollar-volume), are not considered in the ranking. pipe.add(recent_returns.rank(mask=high_dollar_volume), 'recent_returns_rank') # Add a filter to the pipeline such that only high-return and low-return # securities are kept. pipe.set_screen(low_returns | high_returns) # Add the low_returns and high_returns filters as columns to the pipeline so # that when we refer to securities remaining in our pipeline later, we know # which ones belong to which category. pipe.add(low_returns, 'low_returns') pipe.add(high_returns, 'high_returns') return pipe
def make_pipeline(): #context.features = ['RSI', 'MACD', 'EMA','SMA_5','SMA_10','ADX'] base_universe = Q500US() sector = mstar.asset_classification.morningstar_sector_code.latest sectors_311 = sector.eq(311) returns_1 = Returns(window_length=2) rsi = RSI(inputs=[USEquityPricing.close]) macd = MovingAverageConvergenceDivergenceSignal( mask=base_universe ) ema = ExponentialWeightedMovingAverage( mask=base_universe, inputs=[USEquityPricing.close], window_length=30, decay_rate=(1 - (2.0 / (1 + 15.0))) ) mean_5 = SimpleMovingAverage( inputs=[USEquityPricing.close], window_length=5, mask=base_universe ) mean_10 = SimpleMovingAverage( inputs=[USEquityPricing.close], window_length=10, mask=base_universe ) bb = BollingerBands( inputs=[USEquityPricing.close], window_length=20, k=2 ) diluted_eps = Fundamentals.diluted_eps_earnings_reports.latest growth_score = Fundamentals.growth_score.latest tangible_bv = Fundamentals.tangible_book_value.latest return Pipeline( columns={ 'returns_1': returns_1, 'RSI': rsi, 'MACD': macd, 'EMA': ema, 'SMA_5': mean_5, 'SMA_10': mean_10, 'bb_upper': bb.upper, 'bb_middle': bb.middle, 'bb_lower': bb.lower, 'diluted_eps': diluted_eps, 'growth_score': growth_score, 'tangible_bv': tangible_bv }, screen=(base_universe & sectors_311), )
def make_pipeline(): pipe = Pipeline() # Set the universe to the QTradableStocksUS & stocks with Sector and Top 2000 by MarketCap universe = MarketCap().top(2000, mask = QTradableStocksUS()) & Sector().notnull() #filter more with momentum and volarility filter(lowest 600 volatility stocks) momentum = Momentum() volatility = Volatility() volatility_rank = volatility.rank(mask=universe, ascending=True) pipe.set_screen(universe & (volatility_rank.top(600)) & (momentum>1)) # Creating Price_to_book,Price_to_earnings, and return_on_assets, return_on_Equity, Return on Invested Capital Objects, and Dividend_yield Object and Rank them #Create Price to book and Price to Earning and rank them, the lower the ratio, the better pb = Price_to_Book() pb_rank = pb.rank(mask=universe, ascending=True) pe = Price_to_Earnings() pe_rank = pe.rank(mask=universe, ascending=True) #Create Return on Assets, Return on Equity, Return on Invested Capital and Dividend Yield Class and rank them,the higher the ratio, the better roa = Return_on_Assets() roa_rank = roa.rank(mask=universe, ascending=False) roe = Return_on_Equity() roe_rank = roe.rank(mask=universe, ascending=False) roic = Return_on_Invested_Capital() roic_rank = roic.rank(mask=universe, ascending=False) earnings_yield = Earnings_Yield() EY_rank = earnings_yield.rank(ascending=False, mask=universe) dy = Dividend_Yield() dy_rank = dy.rank(mask=universe, ascending=False) #Give 1 weight forall metrics such as P/e,P/B,Dividend Yield,Return on Assets,Equity and Invested Capital the_ranking_score = (pb_rank+pe_rank+dy_rank+roa_rank+roe_rank+roic_rank*2 + EY_rank)/8 # Rank the combo_raw and add that to the pipeline pipe.add(the_ranking_score.rank(mask=universe), 'ranking_score') return pipe
def make_pipeline(investment_set): """ This will return the selected stocks by market cap, dynamically updated. """ # Base universe base_universe = investment_set yesterday_close = USEquityPricing.close.latest pipe = Pipeline(screen=base_universe, columns={ 'close': yesterday_close, 'sector': Sector() }) return pipe
def make_pipeline(): returns = Returns(window_length=2) sentiment = stocktwits.bull_minus_bear.latest msg_volume = stocktwits.total_scanned_messages.latest # make_pipeline() specifically returns Pipeline(...) # Pipeline(...) looks to be a dataframe. return Pipeline(columns={ 'daily_returns': returns, 'sentiment': sentiment, 'msg_volume': msg_volume, }, )
def make_pipeline(context): """ A function to build out filtered stock list by sectors. """ # Hold sector object, which will be used as a column in the pipeline, identifying # each stock's sector. stocks_sector = Sector() # Possible short version of a pipeline without filters return Pipeline( columns={ 'sector_code': stocks_sector } )
def initialize(context): EntVal = NetCash() schedule_function(rebalance, date_rules.week_start(), time_rules.market_open()) # Create and apply a filter representing the top 500 equities by MarketCap # every day. # Construct an average dollar volume factor NegEnt = EntVal > 1 LongsUniverse = Q1500US()#& NegEnt longs = EntVal.top(25, mask=LongsUniverse) hold = Q1500US() & NegEnt pipe = Pipeline(screen = longs, columns = {'Longs':longs}) attach_pipeline(pipe, 'Value_Investing') pipe2 = Pipeline(screen = hold, columns = None) attach_pipeline(pipe2, 'Hold')
def make_history_pipeline(factors, universe, n_fwd_days=5): # Call .rank() on all factors and mask out the universe factor_ranks = { name: f().rank(mask=universe) for name, f in factors.iteritems() } # Get cumulative returns over last n_fwd_days days. We will later shift these. factor_ranks['Returns'] = Returns(inputs=[USEquityPricing.open], mask=universe, window_length=n_fwd_days) pipe = Pipeline(screen=universe, columns=factor_ranks) return pipe
def make_pipeline(context): pipe = Pipeline() # Q1500US - вселенная из 1500 самых ликвидных активов universe = Q1500US() market_cap = MarketCap(mask=universe) market_cap_rank = market_cap.rank() # берем половину активов с большой капитализацией market_cap_high = market_cap_rank.top(750) quality = Quality(mask=market_cap_high) quality_rank = quality.rank() # 100 самых целесообразных в плане бизнеса qualit = quality_rank.top(100) book_to_price = BookToPrice(mask=qualit) book_to_price_rank = book_to_price.rank() # 50 недооцененных в низким b/p highbp = book_to_price_rank.top(15) securities_to_trade = (highbp) pipe = Pipeline(columns={ 'highbp': highbp, }, screen=securities_to_trade) return pipe
def make_pipeline(): dollar_vol = AverageDollarVolume(window_length=20) is_liq = dollar_vol.top(1000) # impact = sentiment.sentiment_signal.latest sentiment_score = sentiment.sentiment_signal.latest return Pipeline( columns={ # 'impact': impact, 'sentiment': sentiment_score }, screen=is_liq )
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
def make_pipeline(context): out_xli = (USEquityPricing.close.latest / OwnShift(window_length=58) [context.XLI] - 1) < -0.07 out_dbb = (USEquityPricing.close.latest / OwnShift(window_length=58) [context.DBB] - 1) < -0.07 out_bil = (USEquityPricing.close.latest / OwnShift(window_length=58) [context.BIL] - 1) < -0.60/100 in_spy = ((USEquityPricing.close.latest / OwnMax(window_length = 252) [context.SPY]) < 0.7) pipe = Pipeline(columns={ 'out_xli': out_xli, 'out_dbb': out_dbb, 'out_bil': out_bil, 'in_spy': in_spy, }, ) return pipe
def make_pipeline(context): sids = StaticAssets([context.leveraged, context.no_leveraged]) base_universe = sids yesterday_close = PrevClose() close_to_close = Returns(window_length=2) pipe = Pipeline(screen=base_universe, columns={ 'yesterday_close': yesterday_close, 'close_to_close': close_to_close, }) return pipe
def make_pipeline(): """ Create and return our pipeline. We break this piece of logic out into its own function to make it easier to test and modify in isolation. In particular, this function can be copy/pasted into research and run by itself. """ # By appending .latest to the imported morningstar data, we get builtin Factors # so there's no need to define a CustomFactor value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest quality = Fundamentals.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 = Fundamentals.market_cap.latest >= 500000000 price_filter = USEquityPricing.close.latest >= 5 universe = QTradableStocksUS() & price_filter & mkt_cap_filter # Construct a Factor representing the rank of each asset by our value # quality metrics. We aggregate them together here using simple addition # after zscore-ing them combined_rank = (value.zscore() + quality.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, mask=universe) shorts = combined_rank.bottom(NUM_SHORT_POSITIONS, 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_rank': combined_rank, 'quality': quality, 'value': value, 'sector': sector }, screen=long_short_screen) return pipe
def make_pipeline(): base_universe = QTradableStocksUS() sentiment_score = SimpleMovingAverage( inputs = [stocktwits.bull_minus_bear], window_length = 3) top_bottom_scores = ( sentiment_score.top(350)|sentiment_score.bottom(350)) return Pipeline( columns = {'sentiment_score': sentiment_score}, screen=(base_universe & top_bottom_scores))
def make_pipeline(): base_universe = Q500US() yesterday_close = USEquityPricing.close.latest returns = Returns(window_length=2) returns_over_5p = returns > 0.05 pipe = Pipeline( screen = base_universe & returns_over_5p, columns = { 'close': yesterday_close, 'return':returns } ) return pipe
def make_pipeline(): """ A function to create our dynamic stock selector (pipeline). Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ # Base universe set to the Q1500US # base_universe = Q1500US() # initial asset funnel # base_universe = Q1500US() base_universe = Q500US() yesterday_close = USEquityPricing.close.latest # roll_mean = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=base_universe) bb = BollingerBands(inputs=[USEquityPricing.close], window_length=10, k=1, mask=base_universe) # bb = BollingerBands(inputs = context.aapl, window_length=10, k=1) upper_band = bb.upper mean_band = bb.middle lower_band = bb.lower # print bb # print upper_band percent_diff_upper = (upper_band - mean_band) / mean_band # shorts = percent_diff_upper.top(30) percent_diff_lower = (lower_band - mean_band) / mean_band longs = lower_band.top(20) shorts = upper_band.bottom(30) # print shorts # print longs securities_to_trade = (shorts | longs) #------------------------------------------------- # mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close],window=10,mask=base_universe) # mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],window=10,mase=base_universe) # percent_diff = (mean_10 - mean_30)/mean_30 # shorts = percent_diff.top(25) # longs = percent_diff.bottom(25) # securities_to_trade = (shorts | longs) #------------------------------------------------- # Factor of yesterday's close price. pipe = Pipeline( columns={ 'longs': longs, 'shorts': shorts, }, screen=(securities_to_trade), ) return pipe
def make_pipeline(): # Universe Q1500US base_universe = Q1500US() # Energy Sector sector = morningstar.asset_classification.morningstar_sector_code.latest energy_sector = sector.eq(309) # Make Mask of 1500US and Energy base_energy = base_universe & energy_sector # Dollar Volume (30 Days) Grab the Info dollar_volume = AverageDollarVolume(window_length=30) # Grab the top 5% in avg dollar volume high_dollar_volume = dollar_volume.percentile_between(95, 100) # Combine the filters top_five_base_energy = base_energy & high_dollar_volume # 10 Day mean close mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=top_five_base_energy) # 30 Day mean close mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=top_five_base_energy) # Percent Difference percent_difference = (mean_10 - mean_30) / mean_30 # List of Shorts shorts = percent_difference < 0 # List of Longs longs = percent_difference > 0 # Final Mask/Filter for anything in shorts or longs securities_to_trade = (shorts | longs) # Return Pipeline return Pipeline(columns={ 'longs': longs, 'shorts': shorts, 'perc_diff': percent_difference }, screen=securities_to_trade)
def make_pipeline(): sentiment_factor = sentiment.sentiment_signal.latest universe = (Q1500US() & sentiment_factor.notnull()) sentiment_quantiles = sentiment_factor.rank(mask=universe, method='average').quantiles(2) pipe = Pipeline(columns={ 'sentiment': sentiment_factor, 'longs': (sentiment_factor >= 4), 'shorts': (sentiment_factor <= -2) }, screen=universe) return pipe
def make_pipeline(): # Screen out penny stocks and low liquidity securities. dollar_volume = AverageDollarVolume(window_length=20) is_liquid = dollar_volume.rank(ascending=False) < 1000 # Add pipeline factors impact = alphaone_free.impact_score.latest sentiment = alphaone_free.article_sentiment.latest return Pipeline(columns={ 'impact': impact, 'sentiment': sentiment, }, screen=is_liquid)
def make_pipeline(): base_universe = QTradableStocksUS() sentiment_score = SimpleMovingAverage( inputs=[stocktwits.bull_minus_bear], window_length=3, ) return Pipeline(columns={ 'sentiment_score': sentiment_score, }, screen=(base_universe & sentiment_score.notnull()))
def make_pipeline(context): alpha_factor, screen = create_factor() # Winsorize to remove extreme outliers alpha_winsorized = alpha_factor.winsorize(min_percentile=0.02, max_percentile=0.98, mask=screen) # Zscore and rank to get long and short (positive and negative) alphas to use as weights alpha_rank = alpha_winsorized.rank().zscore() return Pipeline(columns={'alpha_factor': alpha_rank}, screen=screen, domain=US_EQUITIES)
def make_pipeline(sec_list, context): """ A function to create our dynamic stock selector (pipeline). Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ # Return Factors mask = SecurityInList() mask.securities = sec_list mask = mask.eq(1) yr_returns = Returns(window_length=context.return_period, mask=mask) pipe = Pipeline(screen=mask, columns={'yr_returns': yr_returns}) return pipe
def make_pipeline(): dollar_volume = AverageDollarVolume(window_length=20) is_liquid = dollar_volume.top(1000) impact = alphaone_free.impact_score.latest sentiment = alphaone_free.article_sentiment.latest return Pipeline(columns={ 'impact': impact, 'sentiment': sentimenet }, screen=is_liquid)
def make_pipeline(): sentiment_score = SimpleMovingAverage( inputs=[stocktwits.bull_minus_bear], window_length=3, # filtering mask=QTradableStocksUS()) return Pipeline( columns={ 'sentiment_score': sentiment_score, }, # つまり、sentiment_scoreが null ではない銘柄は全部投資対象に入れる screen=sentiment_score.notnull())
def make_pipeinit(): factors = make_factor() pipeline_columns = {} for f in factors.keys(): for days_ago in reversed(range(WINDOW_LENGTH)): pipeline_columns[f + '-' + str(days_ago)] = Factor_N_Days_Ago( [factors[f](mask=QTradableStocksUS())], window_length=days_ago + 1, mask=QTradableStocksUS()) pipe = Pipeline(columns=pipeline_columns, screen=QTradableStocksUS()) return pipe
def make_pipeline_buy(): base_universe = QTradableStocksUS() mktcap = morningstar.valuation.market_cap.latest mktcap_filter = mktcap > 10000000000 all_filters = mktcap_filter & base_universe pipe = Pipeline( columns={ 'mktcap_filter' : mktcap_filter, }, screen=all_filters ) return pipe
def make_pipeline(): # define our fundamental factor pipeline pipe = Pipeline() return_on_equity = Latest([Fundamentals.roe_af]) reinvestment_rate = Fundamentals.reinvest_rate_af.latest momentum = Momentum() #do standardization return_on_equity = return_on_equity.zscore() reinvestment_rate = reinvestment_rate.zscore() momentum = momentum.zscore() total_z = 0.34 * return_on_equity + 0.16 * reinvestment_rate + 0.5 * momentum # we also get daily returns returns = Returns(window_length=2) # we compute a daily rank of both factors, this is used in the next step, # which is computing portfolio membership QTradableStocksUS total_z_rank = total_z.rank(mask=Q1500US()) buy = total_z_rank.top(200) sell = total_z_rank.bottom(200) # Define our universe, screening out anything that isn't in the top or bottom 200 universe = Q1500US() & (buy | sell) pipe = Pipeline(columns={ 'total_z': total_z, 'Returns': returns, 'total_z_rank': total_z_rank, 'buy': buy, 'sell': sell }, screen=universe) return pipe
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