def my_pipeline(context): pipe = Pipeline() """ The original algorithm used the following filters: 1. common stock 2 & 3. not limited partnership - name and database check 4. database has fundamental data 5. not over the counter 6. not when issued 7. not depository receipts 8. primary share 9. high dollar volume Check Scott's notebook for more details. This updated version uses Q1500US, one of the pipeline's built-in base universes. Lesson 11 from the Pipeline tutorial offers a great overview of using multiple filters vs using the built-in base universes: https://www.quantopian.com/tutorials/pipeline#lesson11 More detail on the selection criteria of this filter can be found here: https://www.quantopian.com/posts/the-q500us-and-q1500us """ base_universe = Q1500US() # The example algorithm - mean reversion. Note the tradable filter used as a mask. sma_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=base_universe) sma_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=base_universe) rel_diff = (sma_10 - sma_30) / sma_30 top_rel_diff = rel_diff.top(context.num_short) pipe.add(top_rel_diff, 'top_rel_diff') bottom_rel_diff = rel_diff.bottom(context.num_long) pipe.add(bottom_rel_diff, 'bottom_rel_diff') return pipe
def make_pipeline(): #context.features = ['RSI', 'MACD', 'EMA','SMA_5','SMA_10','ADX'] base_universe = Q1500US() sector = mstar.asset_classification.morningstar_sector_code.latest sectors_311 = sector.eq(311) returns_5 = Returns(window_length=5) 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_5': returns_5, '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(): """ A function to create our dynamic stock selector (pipeline). Used to calculate SMA and latest close price then filter on SID. """ # n = [1, 5, 15, 25, 35, 45, 50, 100, 200] sma_short = 1 sma_long = 100 short_sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=sma_short) long_sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=sma_long) symbol = SidInList(sid_list=(8554)) # Only show values for the S&P500 return Pipeline( columns={ 'SMA_short': short_sma, 'SMA_long': long_sma, 'symbol': symbol, }, screen=symbol, )
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 make_pipeline(): value = Fundamentals.ebit.latest / Fundamentals.enterprise_value.latest quality = Fundamentals.roe.latest positived_sentiment = (twitter_sentiment.bull_scored_messages.latest / twitter_sentiment.total_scanned_messages.latest) sentiment_3day = SimpleMovingAverage(inputs=[sentiment.sentiment_signal], window_length=3) universe = QTradableStocksUS() value_winsorized = value.winsorize(min_percentile=0.05, max_percentile=0.95) quality_winsorized = quality.winsorize(min_percentile=0.05, max_percentile=0.95) sentiment_winsorized = sentiment_3day.winsorize(min_percentile=0.05, max_percentile=0.95) combined_factor = ( value_winsorized.zscore() + quality_winsorized.zscore() + ((positived_sentiment.zscore() + sentiment_winsorized.zscore()) / 2)) longs = combined_factor.top(TOTAL_POSITIONS // 2, mask=universe) shorts = combined_factor.bottom(TOTAL_POSITIONS // 2, mask=universe) long_short_screen = (longs | shorts) pipe = Pipeline(columns={ 'longs': longs, 'shorts': shorts, 'combined_factor': combined_factor }, screen=long_short_screen) return pipe
def make_pipeline(context): year_high = ATH() apr = APR() price1 = USEquityPricing.close.latest sma_100 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=100) sma_filter = (price1 > sma_100) spy = Q500US() momentum = (Latest(inputs=[USEquityPricing.close]) / SimpleMovingAverage( inputs=[USEquityPricing.close], window_length=252)) - 1 apr_filter = (apr > 0.005) new_high = (year_high <= price1) dollar_volume = AverageDollarVolume(window_length=30) high_dv = dollar_volume.percentile_between(90, 100) mkt_cap = MarketCap().top(UniverseSize) mo_filter = (momentum > 0) universe = (new_high & spy & apr_filter & mkt_cap & mo_filter & high_dv & sma_filter) mo_rank = momentum.rank(mask=universe, ascending=False) pipe=Pipeline( columns={#"year high": year_high , # "price" : price1, "mo_rank" : mo_rank, "apr" : apr, }, screen=spy ) return pipe
def make_pipeline(): # Create Filters for Masks First latest_close = USEquityPricing.close.latest small_price = latest_close < 5 # Classifier nyse_filter = exchange.eq('NYS') # Pass in the mask mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=small_price) mean_close_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=small_price) percent_difference = (mean_close_10 - mean_close_30) / mean_close_30 perc_diff_check = percent_difference > 0 final_filter = perc_diff_check & nyse_filter return Pipeline(columns={ 'Percent Difference': percent_difference, '30 Day Mean Close': mean_close_30, 'Latest Close': latest_close, 'Positive Percent Diff': perc_diff_check }, screen=final_filter)
def custom_pipeline(context): sma_10 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=10) sma_50 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=50) # for testing only small_universe = SidInList(sid_list = (24)) #changed to be easier to read. my_screen = (Q500US() & \ (sma_10 > sma_50) & \ (st.bull_scored_messages.latest > 10)) prediction = Prediction(inputs=[st.bull_scored_messages, st.bear_scored_messages, \ USEquityPricing.close, USEquityPricing.open],\ window_length=200, mask=small_universe) return Pipeline( columns={ 'sma10': sma_10, 'close': USEquityPricing.close.latest, 'prediction': prediction }, screen=my_screen)
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 """ # Set universe to our filter (the same as Q1500US()) base_universe = filter_universe() # Basic mean reversion strategy # 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 # Top and bottom 75 filters using percent_difference shorts = percent_difference.top(75) longs = percent_difference.bottom(75) # Combine these filters into a pipeline screen securities_to_trade = (shorts | longs) pipe = Pipeline(columns={ 'longs': longs, 'shorts': shorts }, screen=securities_to_trade) return pipe
def make_pipeline(): # Base universe set to the QTradableStocksUS base_universe = QTradableStocksUS() # Count 10 day min mean_10 = SimpleMovingAverage( inputs=[USEquityPricing.close], window_length=10, mask=base_universe ) # Count 30 day max mean_30 = SimpleMovingAverage( inputs=[USEquityPricing.close], window_length=30, mask=base_universe ) percent_difference = (mean_10 - mean_30) / mean_30 shorts = percent_difference.top(75) longs = percent_difference.bottom(75) # use the model pipe = Pipeline( columns={ 'longs': longs, 'shorts': shorts, 'Model': Predictor( window_length=days_for_analysis ,mask=base_universe ) } ,screen = base_universe ) return pipe
def make_pipeline(context): base_universe = Q500US() rsi_factor = RSI(window_length=5) fso_factor = FastStochasticOscillator() beta = SimpleBeta(target=sid(8554), regression_length=260) pipe = Pipeline(columns={ 'rsi': rsi_factor, 'fso': fso_factor, 'beta': beta }, screen=base_universe & rsi_factor.notnull() & fso_factor.notnull()) context.sma_short = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=20) pipe.add(context.sma_short, "sma_short") context.sma_long = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=50) pipe.add(context.sma_long, "sma_long") return pipe
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 )
def make_pipeline(): """ Create our pipeline. """ # Base universe set to the QTradableStocksUS. base_universe = QTradableStocksUS() # 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(75) # Filter to select securities to long. longs = percent_difference.bottom(75) # 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(): 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 dollar_volume = AverageDollarVolume(window_length=30) # percentile_between: Factor method returning a Filter high_dollar_volume = dollar_volume.percentile_between(90, 100) # above_20: a filter latest_close = USEquityPricing.close.latest above_20 = latest_close > 20 # Combine filters is_tradeable = high_dollar_volume & above_20 return Pipeline( columns={'percent_difference': percent_difference}, # Apply the filter screen=is_tradeable)
def make_pipeline(): base_universe = Q500US() price_moving_average_20 = SimpleMovingAverage( inputs=[USEquityPricing.close], window_length=20, mask=base_universe) current_price = USEquityPricing.close.latest twenty_day_momentum = (current_price - price_moving_average_20) / price_moving_average_20 # ''' wiki_views = wikipedia_pageviews.views.latest wiki_views_sma10 = SimpleMovingAverage(inputs=[wikipedia_pageviews.views], window_length=10, mask=base_universe) last_open = USEquityPricing.open.latest one_day_momentum = (current_price - last_open) / last_open views_spike_filter = (wiki_views - wiki_views_sma10) / wiki_views_sma10 > .2 # ''' factor1 = twenty_day_momentum + 5 * one_day_momentum longs = factor1.top(75) shorts = factor1.bottom(75) securities_to_trade = (shorts | longs) & views_spike_filter return Pipeline(columns={ 'longs': longs, 'shorts': shorts }, screen=securities_to_trade)
def make_pipeline(): """ A function to create our dynamic stock selector (pipeline). Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ sma_short = 35 sma_long = 50 short_sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=sma_short) long_sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=sma_long) rsi = RSI(inputs=[USEquityPricing.close], window_length=10) symbol = SidInList(sid_list=(8554)) # SPY 500 return Pipeline( columns={ 'RSI': rsi, 'SMA_short': short_sma, 'SMA_long': long_sma, 'symbol': symbol, }, screen=symbol, )
def make_pipeline(): base_universe = MYQ500US() # Q500US() # 一週間のリターンをとりあえず過去5日間のリターンと考える fiveday_return = Returns(window_length=5) sma30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30) remove_penny_stocks = sma30 > 10.0 remove_expensive_stocks = sma30 < 100.0 pipe = Pipeline(screen=base_universe & remove_penny_stocks & remove_expensive_stocks, columns={ 'fiveday_return': fiveday_return, }) return pipe
def make_pipeline(): # Get latest closing price close_price = USEquityPricing.close.latest # Calculate 3 day average of bull_minus_bear scores sentiment_score = SimpleMovingAverage( inputs=[stocktwits.bull_minus_bear], window_length=3, ) # Return Pipeline containing close_price # and sentiment_score return Pipeline(columns={ 'close_price': close_price, 'sentiment_score': sentiment_score, })
def make_pipeline(): universe = QTradableStocksUS() dma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200, mask=universe) close = USEquityPricing.close.latest longs = close > dma_200 securities_to_trade = (longs) return Pipeline( columns={'longs': longs}, screen=(securities_to_trade), )
def make_pipeline(): universe = StaticAssets((symbols('NFLX'))) sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length = 50) close = USEquityPricing.close.latest signal = sma > close return Pipeline( columns = { 'sma':sma, 'close':close, 'signal':signal }, screen = universe )
def initialize(context): context.spy = sid(8554) set_benchmark(context.spy) # define momentum as latest/SMA, same as to market (SPY) filter momentum = (Latest(inputs=[USEquityPricing.close]) / SimpleMovingAverage( inputs=[USEquityPricing.close], window_length=Lookback)) - 1 #mkt_cap = Latest(inputs=[morningstar.valuation.market_cap]) #very slow #universe = mkt_cap.top(UniverseSize) dollar_volume = AvgDailyDollarVolumeTraded(window_length=100) universe = dollar_volume.top(UniverseSize) momentum_rank = momentum.rank(mask=universe, ascending=False) long_filter = momentum_rank <= 0.2 * UniverseSize short_filter = momentum_rank > 0.8 * UniverseSize apr = APR() apr_filter = apr > 0.005 pipe = Pipeline() #pipe.add(momentum, 'momentum') # include for debugging pipe.add(momentum_rank, 'momentum_rank') pipe.add(apr, 'apr') pipe.add(long_filter, 'long') pipe.add(short_filter, 'short') pipe.set_screen(universe & apr_filter & (long_filter | short_filter)) pipe = attach_pipeline(pipe, name='equitylongshort') schedule_function(func=rebalance_positions, date_rule=date_rules.week_start(days_offset=2), time_rule=time_rules.market_open(hours=2), half_days=True) schedule_function(func=cancel_all, date_rule=date_rules.week_start(days_offset=2), time_rule=time_rules.market_close(), half_days=True) set_slippage( slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1)) # Default set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0)) # FSC for IB
def make_pipeline(): # Create a reference to our trading universe base_universe = QTradableStocksUS() # get latest closing price close_price = USEquityPricing.close.latest # calculate 3 day MA of bull-minus-bear scores sentiment_score = SimpleMovingAverage( inputs=[stocktwits.bull_minus_bear], window_length=3, ) # Return Pipeline containing close_price and sentiment_score return Pipeline( columns={'close_price': close_price, 'sentiment_score': sentiment_score, } screen=base_universe )
def custom_pipe(context): pipe = Pipeline() # bull_1 = st.bullish_intensity.latest # bear_1 = st.bearish_intensity.latest # volume = USEquityPricing.volume.latest sma_scan_7 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=7) # sma_scan_6 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=6) # sma_scan_5 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=5) # sma_scan_4 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=4) # sma_scan_3 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=3) # sma_scan_2 = SimpleMovingAverage(inputs = [st.total_scanned_messages], window_length=2) scan_1 = st.total_scanned_messages.latest # pipe.add(bull_1, 'bullish_intensity') # pipe.add(bear_1, 'bearish_intensity') # pipe.add(st.bear_scored_messages.latest, 'bear_scored_messages') # pipe.add(st.bull_scored_messages.latest, 'bull_scored_messages') pipe.add(scan_1, 'scan_1') # pipe.add(sma_scan_2, 'sma_scan_2') # pipe.add(sma_scan_3, 'sma_scan_3') # pipe.add(sma_scan_4, 'sma_scan_4') # pipe.add(sma_scan_5, 'sma_scan_5') # pipe.add(sma_scan_6, 'sma_scan_6') pipe.add(sma_scan_7, 'sma_scan_7') # pricing = USEquityPricing.close.latest # Base universe set to the Q500US base_universe = Q1500US() pipe.set_screen( (base_universe) # (scan_1 < 10) # (pricing < 15.00) & # (pricing > 5.00) & # (volume > 1000000) & # ( # (bull_1 > 0) | # (bear_1 > 0) # ) # (scan_1 < sma_scan_7) ) return pipe
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 initialize(context): """ Called once at the start of the algorithm. """ context.stocks = [sid(8554), sid(38054), sid(40516)] # spy, vxx, xiv context.spy = sid(8554) context.xiv = sid(40516) context.vxx = sid(38054) context.sell_price = 0 context.vix_last_price = 0 set_benchmark(sid(40516)) context.allocation = [0,0,0] # Rebalance every day, 1 hour after market open. schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(minutes=1)) #schedule_function(check_xiv, date_rules.every_day(), time_rules.market_close(minutes=60)) # Record tracking variables at the end of each day. schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close()) #Set slippage and commission #set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1)) #set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1)) # fetch VIX data pipe = Pipeline() attach_pipeline(pipe, 'my_pipeline') #get VIX at market open pipe.add(GetVIX(inputs=[cboe_vix.vix_close]), 'VixOpen') pipe.add(GetVIX(inputs=[cboe_vvix.vvix]), 'Vvix') pipe.add(GetVIXma(inputs=[cboe_vvix.vvix], window_length = 5), 'Vvix_ma5') #get VIX average in the last 2 days pipe.add(SimpleMovingAverage(inputs=[cboe_vix.vix_close], window_length=2), 'vix_mean') 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
def make_pipeline(): base_universe = Q500US() # 一週間のリターンをとりあえず過去5日間のリターンと考える # 本当は,休日の事も考えなくては行けないが,とりあえず決め打ち. fiveday_return = Returns(window_length=5) # 過去30日の移動平均を取得 sma30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30) # 移動平均が10ドル以上 remove_penny_stocks = sma30 > 10.0 # 過去30日の売買高 dollar_volume = AverageDollarVolume(window_length=30) # 上位10%だけを対象 high_dollar_volume = dollar_volume.percentile_between(90, 100) pipe = Pipeline(screen=base_universe & remove_penny_stocks & high_dollar_volume, columns={ 'fiveday_return': fiveday_return, }) return pipe
def make_pipeline(): universe = StaticAssets(symbols('SPY')) close = USEquityPricing.close.latest sma_200 = SimpleMovingAverage( inputs = [USEquityPricing.close], window_length = 200, mask = universe ) logic = close > sma_200 return Pipeline( columns = { 'close':close, 'sma_200':sma_200, 'logic':logic }, screen = universe )
def make_pipeline(): """ A function to create our dynamic stock selector (pipeline). Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ # Base universe set to the QTradableStocksUS base_universe = StaticAssets(SYMBOLS) n = 10 ma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=n, mask=base_universe) # Factor of yesterday's close price. yesterday_close = USEquityPricing.close.latest pipe = Pipeline(columns={ 'close': yesterday_close, 'ma': ma, }, screen=base_universe) return pipe
def make_pipeline(): """ pipeline を作る make_pipeline を作ったほうが,research にもコピペして使えるし,テストや修正も簡単に出来るので,幸せになれます """ # クロスモメンタム cross_momentum = CrossSectionalMomentum() # Returns で過去252分全てのクローズベースのリターンを取得 abs_momentum = Returns(input=[USEquityPricing.close], window_length = 252) # 流動性がある株式だけ取引する.過去20日間,平均1千万ドル平均の取引高(price*volume)があるものだけを取引 dollar_volume = AverageDollarVolume(window_length=20) is_liquid = (dollar_volume > le7) # 過去200日平均で株価5ドル以下のペニーストックはトレードしない. sma_200 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=200) not_a_penny_stock = (sma_200 > 5) # 不必要な銘柄は取り除く initial_screen = (is_liquid & not_a_penny_stock) # cross momentum を適用したあとに,ランク付けをする combined_rank = (cross_momentum.rank(mask=initial_screen) + abs_momentum.rank(mask=initial_screen)) # top 5 % をロング longs = combined_rank.percentile_between(95, 100) shorts = combined_rank.percentile_between(0, 5) # パイプラインにロングショートする銘柄を取得 pipe_screen = (longs | shorts) pipe_columns = { 'longs': longs, 'shorts': shorts, 'combined_rank': combined_rank, 'abs_momentum': abs_momentum, 'cross_momentum': cross_momentum, } # パイプ作成 pipe = Pipeline(columns=pipe_columns, screen=pipe_screen) return pipe
def public_opinion(): qtu = QTradableStocksUS() sentiment_stocktwits = SimpleMovingAverage( inputs=[stocktwits.bull_minus_bear], window_length=2, ) sentiment_news = SimpleMovingAverage( inputs=[sentiment.sentiment_signal], window_length=2 ) sentiment_factor = sentiment_stocktwits + sentiment_news sentiment_factor_winsorized = sentiment_factor.winsorize( min_percentile=0.10, max_percentile=0.90) sentiment_factor_rank = sentiment_factor_winsorized.rank().zscore() screen = qtu & ~sentiment_stocktwits.isnull() & ~sentiment_news.isnull() & sentiment_factor.isfinite() return sentiment_factor_rank, screen