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 """ primary = Q500US() # IsPrimaryShare() sma7 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=7) sma3 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=3) sma21 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=21) above_10 = sma3 > 10 #dollar_volume = AverageDollarVolume(window_length=60) #high_dollar_volume = dollar_volume.percentile_between(85, 100,mask = above_10 & primary) smaRatio = sma7 / sma21 sma_rank = smaRatio.rank() shorts = sma_rank.percentile_between(90, 100) longs = sma_rank.percentile_between(0, 10) # Create a dollar volume factor. # Pick the top 1% of stocks ranked by dollar volume. #high_dollar_volume = high_dollar_volume & primary morn_cyc = SuperSector() Close = USEquityPricing.close.latest returns = Returns(window_length=10) returns_slice = returns[sid(8554)] spy_correlations = returns.pearsonr(target=returns_slice, correlation_length=30) LowBeta = (spy_correlations >= -0.39) & (spy_correlations <= 0.39) #LowBeta1 = spy_correla pipe = Pipeline( screen=primary & above_10, columns={ #'dollar_volume': dollar_volume, 'longs': longs, 'shorts': shorts, 'sma_rank': sma_rank, 'ratioCy': smaRatio, 'SpyCor': LowBeta, 'Q500': Q500US(), 'Close': Close }) return pipe
def make_pipeline(): """ Create our pipeline. """ pricing = USEquityPricing.close.latest # Volatility filter (I made it sector neutral to replicate what UBS did). Uncomment and # change the percentile bounds as you would like before adding to 'universe' # vol=Volatility(mask=Q500US()) # sector=morningstar.asset_classification.morningstar_sector_code.latest # vol=vol.zscore(groupby=sector) # vol_filter=vol.percentile_between(0,100) # Liquidity filter (Uncomment and change the percentile bounds as you would like before # adding to 'universe' # liquidity=Liquidity(mask=Q500US()) # I included NaN in liquidity filter because of the large amount of missing data for shares out # liquidity_filter=liquidity.percentile_between(0,75) | liquidity.isnan() universe = ( Q500US() & (pricing > 5) # & liquidity_filter # & volatility_filter ) return Pipeline(screen=universe)
def make_pipeline(): print(get_datetime()) # Base universe set to the Q500US base_universe = Q500US() lastclose = USEquityPricing.close.latest # macd pipeline factor myFactor = MACD() signal = MACD_s() plus = (myFactor > 0) mac_s = (myFactor > signal) # sma difference mean_close_25 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=base_universe) limit_bound = mean_close_25 * 0.95 upper_bound = mean_close_25 * 1.04 lower_bound = mean_close_25 * 0.99 checks_l = lastclose < lower_bound # holder longs = plus & mac_s & checks_l # securities to trade securities_to_trade = (longs) return Pipeline(columns={'longs': longs}, screen=(securities_to_trade))
def make_pipeline(): base_universe = Q500US() ROA = Fundamentals.roa.latest ROE = Fundamentals.roe.latest EV_EBITDA = Fundamentals.ev_to_ebitda.latest Enterprise_value = Fundamentals.enterprise_value.latest PE = Fundamentals.pe_ratio.latest PB = Fundamentals.pb_ratio.latest PS = Fundamentals.ps_ratio.latest rsi = pfactors.RSI(inputs=[USEquityPricing.close], window_length=14) #pipeline variables....winsorize to omit outliers, and zscore to normalize return Pipeline( columns={ 'RSI': rsi.zscore().winsorize(min_percentile=0.05, max_percentile=0.95), #'PE': PE.zscore().winsorize(min_percentile = 0.05, max_percentile = 0.95), 'Enterprise value': Enterprise_value.zscore().winsorize( 0.05, 0.95), #'ROA' : ROA.zscore().winsorize(0.05, 0.95), 'ROE': ROE.zscore().winsorize(0.05, 0.95), 'PB': PB.zscore().winsorize(0.05, 0.95), 'PS': PS.zscore().winsorize(0.05, 0.95), #'EV_EBITDA':EV_EBITDA.zscore().winsorize(0.05, 0.95) })
def make_pipeline(): universe = Q500US() close = USEquityPricing.close.latest total_yield = Fundamentals.total_yield.latest top_yield = total_yield.top(100, mask = universe) mom_score_6 = mom_score() mom_score_6 = mom_score_6.top(30, mask = top_yield) pipe = Pipeline( columns = { 'close':close, 'total_yield':total_yield, 'mask':top_yield, 'mom_score':mom_score_6 }, screen = universe & top_yield & mom_score_6 ) return pipe
def initialize(context): # 空のパイプラインを作ります pipe = Pipeline() # research では run_pipeline # algorithm では,initilize 内で attach_pipeline を実行して,パイプラインを毎日実行するように設定します. # ほしいデータを定義 # pipeline 用に定義された 移動平均 SimpleMovingAverage を使う SMA10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10) SMA30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30) pipe.add(SMA10, 'SMA10') pipe.add(SMA30, 'SMA30') ## raw_weights raw_weights = (SMA10 - SMA30) / SMA30 abs_raw_weights = raw_weights.abs() pipe.add(raw_weights, 'raw_weights') pipe.add(abs_raw_weights, 'abs_raw_weights') pipe.set_screen(Q500US()) attach_pipeline(pipe, "my_pipeline") # 毎週月曜日にどの銘柄を保有するか決定する schedule_function(rebalance, date_rules.week_start(), time_rules.market_open()) # 毎週金曜日の取引時間終了時に持っている銘柄を全部クローズする. schedule_function(all_position_close, date_rule=date_rules.week_end(days_offset=0), time_rule=time_rules.market_close())
def initialize(context): # 空のパイプラインを作ります pipe = Pipeline() # research では run_pipeline # algorithm では,initilize 内で attach_pipeline を実行して,パイプラインを毎日実行するように設定します. # ほしいデータを定義 # pipeline 用に定義された 移動平均 SimpleMovingAverage を使う SMA10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10) SMA30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30) pipe.add(SMA10, 'SMA10') pipe.add(SMA30, 'SMA30') ## raw_weights raw_weights = (SMA10 - SMA30) / SMA30 abs_raw_weights = raw_weights.abs() pipe.add(raw_weights, 'raw_weights') pipe.add(abs_raw_weights, 'abs_raw_weights') pipe.set_screen(Q500US()) attach_pipeline(pipe, "my_pipeline") # Rebalance every Monday (or the first trading day if it's a holiday) # at market open. schedule_function(rebalance, date_rules.week_start(), time_rules.market_open()) schedule_function(all_position_close, date_rule=date_rules.week_end(), time_rule=time_rules.market_close())
def make_pipeline(context): ## symbol universe base_universe = Q500US() if False else Q1500US() ## filters # 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() is_cyclical = SuperSector().eq(SuperSector.CYCLICAL) is_defensive = SuperSector().eq(SuperSector.DEFENSIVE) is_sensitive = SuperSector().eq(SuperSector.SENSITIVE) sector = Sector() close = USEquityPricing.close # For filter tradeable_stocks = (primary_share & common_stock & not_depositary & not_otc & not_wi & not_lp_name & not_lp_balance_sheet & have_market_cap & (is_cyclical | is_defensive | is_sensitive)) dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between(98, 100) myscreen = (base_universe & tradeable_stocks & high_dollar_volume) # Pipeline pipe = Pipeline(columns={ 'yesterday_close': close.latest, 'day_before_yesterday_close': PrevClose(), 'day_before_yesterday_volume': PrevVolume(), 'morningstar_sector_code': sector, }, screen=myscreen) return pipe
def make_pipeline(): # Base universe set to the Q500US universe = Q500US() roe = Fundamentals.roe.latest pipe = Pipeline(columns={'roe': roe}, screen=universe) return pipe
def make_pipeline(): base_universe = Q500US() # 一週間のリターンをとりあえず過去5日間のリターンと考える fiveday_return = Returns(window_length=5) pipe = Pipeline(screen=base_universe, columns={ 'fiveday_return': fiveday_return, }) return pipe
def make_pipeline(context): # Use a universe of just the top 500 US stocks universe = Q500US() sector = Sector() # Determine if the market is trending up or down. If the market is trending down then just buy bonds. If it is trending up then buy stocks # This is not an optimal solution and will obviously not work in all future market crashes spy_ma_fast_slice = SMA( inputs=[USEquityPricing.close], window_length=context.TF_FAST_LOOKBACK)[context.SPY] spy_ma_slow_slice = SMA( inputs=[USEquityPricing.close], window_length=context.TF_SLOW_LOOKBACK)[context.SPY] spy_ma_fast = SMA(inputs=[spy_ma_fast_slice], window_length=1) spy_ma_slow = SMA(inputs=[spy_ma_slow_slice], window_length=1) # If the 100 moving average crosses the 10 then alter the trend up variable trend_up = spy_ma_fast > spy_ma_slow # Get simple factors to determine "quality" companies cash_return = ms.cash_return.latest.rank(mask=universe) fcf_yield = ms.fcf_yield.latest.rank(mask=universe) roic = ms.roic.latest.rank(mask=universe) rev_growth = ms.revenue_growth.latest.rank(mask=universe) value = (cash_return + fcf_yield).rank(mask=universe) # Find sentiment rank using https://www.quantopian.com/posts/sentiment-as-a-factor sentiment_score = SMA( inputs=[sentiment.sentiment_signal], window_length=30, ) sentiment_score_zscore = sentiment_score.zscore() sentiment_overall_rank = sentiment_score_zscore.rank( mask=universe, groupby=sector).demean() # Combine factors to create one single ranking system quality = roic + rev_growth + value + sentiment_overall_rank # Create a 'momentum' factor by looking back over the last 140 days (20 weeks). momentum = Returns(window_length=context.MOMENTUM_LOOKBACK_DAYS) # Filters for top quality and momentum to use in the selection criteria top_quality = quality.top(context.TOP_ROE_QTY, mask=universe) top_quality_momentum = momentum.top(context.TARGET_SECURITIES, mask=top_quality) # Only return values to be used in the selection criteria by using the screen parameter pipe = Pipeline(columns={ 'trend_up': trend_up, 'top_quality_momentum': top_quality_momentum, }, screen=top_quality_momentum) return pipe
def initialize(context): # how many days to look back volatility and returns context.lookback = 3 * 252 # 3 years context.long_leverage = 1.0 #set_benchmark(sid(41382)) #SPLV pipe = Pipeline() attach_pipeline(pipe, 'lvhy') # This is an approximation of the S&P 500 top_500 = Q500US() # Q1500US() volatility = Volatility(window_length=context.lookback) pipe.add(volatility, 'volatility') # Rank factor 1 and add the rank to our pipeline volatility_rank = volatility.rank(mask=top_500) pipe.add(volatility_rank, 'volatility_rank') syield = Yield() pipe.add(syield, 'yield') # Rank factor 2 and add the rank to our pipeline yield_rank = syield.rank(mask=top_500) pipe.add(yield_rank, 'yield_rank') # Take the average of the two factor rankings, add this to the pipeline combo_raw = (volatility_rank + yield_rank) / 2 pipe.add(combo_raw, 'combo_raw') # Rank the combo_raw and add that to the pipeline pipe.add(combo_raw.rank(mask=top_500), 'combo_rank') # Set a screen to capture max top 100 best stocks pipe.set_screen(top_500) # 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) # Schedule my plotting function schedule_function(func=record_vars, date_rule=date_rules.every_day(), time_rule=time_rules.market_close(), half_days=True)
def make_pipeline(): """ Create our pipeline. """ # To make the program more flexible, we allow for the possibility of having two universes, # one for estimating HHI and one for trading stocks after sorting by changes in HHI estimation_universe = Q500US() trading_universe = Q500US() pricing = USEquityPricing.close.latest # Note that if we don't filter for primary share class, we double count sales for dual class stocks primary_share = IsPrimaryShare(mask=estimation_universe) sales = Sales(mask=estimation_universe) industry = Industry(mask=estimation_universe) universe = (primary_share & (pricing > 5)) return Pipeline(screen=universe, columns={ 'sales': sales, 'industry': industry, 'in_trading_univ': trading_universe })
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
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') pipe.add(sma_10, 'sma_10') pipe.add(sma_50, 'sma_50') pipe.set_screen(Q500US() & (sma_10 > sma_50) & ((st.bull_scored_messages.latest * 0.35) > st.bear_scored_messages.latest) & (st.bear_scored_messages.latest > 10) ) return pipe
def make_pipeline(context): """ Builds a Pipeline with Bollinger bands for top NUM_SYMBOLS stocks by market cap in the tech sector. Starts out from the Q500US base universe. """ # Base universe of top 500 US stocks. base_universe_filter = Q500US() # Stocks of only tech sector. tech_sector = Sector(mask=base_universe_filter) tech_universe_filter = base_universe_filter & tech_sector.eq(311) # Top 10 tech stocks with largest market cap. mkt_cap_filter = morningstar.valuation.market_cap.latest top_mkt_cap_tech_filter = mkt_cap_filter.top(context.NUM_SYMBOLS, mask=tech_universe_filter) # Bollinger band factor with Stdev factor 2. lower_band_factor, middle_factor, upper_band_factor = BollingerBands( window_length=22, k=2, mask=top_mkt_cap_tech_filter) # Percent difference between (price, lower_band) and (price, upper_band). price = USEquityPricing.close.latest buy_percent_factor = ((lower_band_factor - price) * 100) / price sell_percent_factor = ((price - upper_band_factor) * 100) / price # Mean reversion buy and sell filters. # Sell when price exceeds upper-band and buy when price is below lower-band. buy_filter = buy_percent_factor > 0 sell_filter = sell_percent_factor > 0 # Build and return the Pipeline. pipe_bbands = Pipeline(columns={ 'buy_percent': buy_percent_factor, 'lower_band': lower_band_factor, 'buy': buy_filter, 'price': price, 'sell': sell_filter, 'upper_band': upper_band_factor, 'sell_percent': sell_percent_factor }, screen=top_mkt_cap_tech_filter) return pipe_bbands
def make_pipeline(): # Base Universe. base_universe = Q500US() # Define Sectors of Assumed Growth sector = morningstar.asset_classification.morningstar_sector_code.latest tech_sector = sector.eq(311) healthcare_sector = sector.eq(206) # Revenue Growth revenue_growth = morningstar.operation_ratios.revenue_growth.latest high_revenue_growth = revenue_growth.percentile_between(80,100,mask = base_universe) # Return on Invested Capital roic = morningstar.operation_ratios.roic.latest high_roic = roic.percentile_between(80,100,mask = high_revenue_growth) # Filtering ROIC as growth adds value long_value_roic = high_roic #> wacc # Filters high_growth = (long_value_roic & high_revenue_growth & (tech_sector | healthcare_sector)) securities_to_trade = high_growth return Pipeline( columns = { 'Sector': sector, 'Revenue Growth': revenue_growth, 'ROIC': roic, 'High Growth': high_growth, }, screen = securities_to_trade)
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 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(): 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(): # Base universe set to the Q500US universe = Q500US() roe = Fundamentals.roe.latest new_returns = Returns(window_length=5, mask=universe) new_returns = new_returns.zscore() returns_range = new_returns.percentile_between(1, 30) new_volatility = AnnualizedVolatility(mask=universe) new_volatility = new_volatility.zscore() volatility_range = new_volatility.percentile_between(1, 30) pipe = Pipeline(columns={ 'roe': roe, 'returns': returns_range, 'volatility': volatility_range }, screen=universe) return pipe
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(context): # Use a universe of just the top 500 US stocks universe = Q500US() # Get simple factors to determine "quality" companies cash_return_latest = ms.cash_return.latest fcf_yield_latest = ms.fcf_yield.latest roic_latest = ms.roic.latest rev_growth_latest = ms.revenue_growth.latest cash_return = cash_return_latest.rank(mask=universe) fcf_yield = fcf_yield_latest.rank(mask=universe) roic = roic_latest.rank(mask=universe) rev_growth = rev_growth_latest.rank(mask=universe) value = (cash_return + fcf_yield).rank(mask=universe) # Combine factors to create one single ranking system quality = value + roic + rev_growth # Create a 'momentum' factor by looking back over the last 140 days (20 weeks) momentum = Returns(window_length=context.MOMENTUM_LOOKBACK_DAYS) # Filters for top quality and momentum to use in the selection criteria top_quality = quality.top( context.TOP_ROE_QTY, mask=universe) & cash_return_latest.notnull( ) & fcf_yield_latest.notnull() & roic_latest.notnull( ) & rev_growth_latest.notnull() top_quality_momentum = momentum.top(context.TARGET_SECURITIES, mask=top_quality) # Only return values to be used in the selection criteria by using the screen parameter pipe = Pipeline(columns={ 'top_quality_momentum': top_quality_momentum, }, screen=top_quality_momentum) 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(): # define our fundamental factor pipeline pipe = Pipeline() # market value,book_to_market,return_on_equity and reinvestment_rate data gets fed in here market_value = Latest([Fundamentals.mkt_val]) book_to_market = 1 / Latest([Fundamentals.pbk_af]) return_on_equity = Latest([Fundamentals.roe_af]) reinvestment_rate = Fundamentals.reinvest_rate_af.latest # and momentum as lagged returns momentum = Momentum() # we also get daily returns returns = Returns(window_length=2) # we compute a daily rank of all factors, this is used in the next step, # which is computing portfolio membership QTradableStocksUS market_value_rank = market_value.rank(mask=Q500US()) book_to_market_rank = book_to_market.rank(mask=Q500US()) return_on_equity_rank = return_on_equity.rank(mask=Q500US()) reinvestment_rate_rank = reinvestment_rate.rank(mask=Q500US()) momentum_rank = momentum.rank(mask=Q500US()) # Grab the top and bottom 50 for each factor biggest = market_value_rank.top(50) smallest = market_value_rank.bottom(50) highpb = book_to_market_rank.top(50) lowpb = book_to_market_rank.bottom(50) robust = return_on_equity_rank.top(50) weak = return_on_equity_rank.bottom(50) conservative = reinvestment_rate_rank.top(50) aggressive = reinvestment_rate_rank.bottom(50) top = momentum_rank.top(50) bottom = momentum_rank.bottom(50) # Define our universe, screening out anything that isn't in the top or bottom 50 for each factor universe = Q500US() & (biggest | smallest | highpb | lowpb | top | bottom | robust | weak | conservative | aggressive) pipe = Pipeline(columns={ 'market_value': market_value, 'book_to_market': book_to_market, 'return_on_equity': return_on_equity, 'reinvestment_rate': reinvestment_rate, 'momentum': momentum, 'Returns': returns, 'market_value_rank': market_value_rank, 'book_to_market_rank': book_to_market_rank, 'return_on_equity_rank': return_on_equity_rank, 'reinvestment_rate_rank': reinvestment_rate_rank, 'momentum_rank': momentum_rank, 'biggest': biggest, 'smallest': smallest, 'highpb': highpb, 'lowpb': lowpb, 'top': top, 'bottom': bottom, 'robust': robust, 'weak': weak, 'conservative': conservative, 'aggressive': aggressive }, screen=universe) return pipe
'Price Oscillator': Price_Oscillator, 'Return on Invest Capital': Return_On_Total_Invest_Capital, '39 Week Returns': Returns_39W, 'Trendline': Trendline, 'Vol 3M': Vol_3M, 'Working Capital to Assets': Working_Capital_To_Assets, } return all_factors factors = make_factors() # In[4]: universe = Q500US() # Define universe and select factors to use n_fwd_days = 5 # number of days to compute returns over # Differently to source I changed rank to zscore! # In[5]: # Define and build the pipeline def make_history_pipeline(factors, universe, n_fwd_days=5): # Call .rank() on all factors and mask out the universe factor_zscore = { name: f().zscore(mask=universe) for name, f in factors.iteritems() } # Get cumulative returns over last n_fwd_days days. We will later shift these.
filtro2 = filtro.isnull() # Filtrar los elementos nulos filtro2 = filtro.matches( 'RegEx') # Filtrar los elementos que coincidan con una expresión regular filtro2 = filtro.notnull() # Filtrar los elementos no nulos filtro2 = filtro.startswith( 'prefijo' ) # Filtrar los elementos que empiecen con el prefijo especificado # Filtros incorporados from quantopian.pipeline.filters import QTradableStocksUS # Universo comercial utilizado en el concurso Quantopian. from quantopian.pipeline.filters import Q500US # Un universo predeterminado que contiene aproximadamente 500 acciones estadounidenses cada día. from quantopian.pipeline.filters import Q1500US # Un universo predeterminado que contiene aproximadamente 1500 acciones estadounidenses cada día. from quantopian.pipeline.filters import Q3000US # Un universo predeterminado que contiene aproximadamente 3000 acciones estadounidenses cada día. filtro = QTradableStocksUS() filtro = Q500US() filtro = Q1500US() filtro = Q3000US() # Clasificadores clasificador = filtro.relabel( funcion) # Crear clasificador a partir de una función # Clasificaciones de factores clasificación = factor1.quartiles() # Clasificar en quartiles clasificación = factor1.quintiles() # Clasificar en quintiles clasificación = factor1.deciles() # Clasificar en deciles clasificación = factor1.quantiles() # Clasificar en quantiles # Dominios from quantopian.pipeline.domain import AR_EQUITIES # Bolsa de Buenos Aires
def make_pipeline(): # Create a reference to our trading universe base_universe = Q500US() # Get net income net_income = Fundamentals.net_income_cash_flow_statement.latest # Get operating cash flow op_cash_flow = Fundamentals.cash_flow_from_continuing_operating_activities.latest # Get return on assets roa = Fundamentals.roa.latest # Get long term debt long_term_debt = Fundamentals.long_term_debt.latest long_term_debt_1yr_ago = Previous(inputs=[Fundamentals.long_term_debt], window_length=252) # Get change in current ratio current_ratio = Fundamentals.current_ratio.latest current_ratio_1yr_ago = Previous(inputs=[Fundamentals.current_ratio], window_length=252) # Get shares issued share_issued = Fundamentals.share_issued.latest share_issued_1yr_ago = Previous(inputs=[Fundamentals.share_issued], window_length=252) # Get gross margin gross_margin = Fundamentals.gross_margin.latest gross_margin_1yr_ago = Previous(inputs=[Fundamentals.gross_margin], window_length=252) # Get asset turnover ratio assets_turnover = Fundamentals.assets_turnover.latest assets_turnover_1yr_ago = Previous(inputs=[Fundamentals.assets_turnover], window_length=252) # Get earnings yield earnings_yield = Fundamentals.earning_yield.latest # Get price to book ratio pb_ratio = Fundamentals.pb_ratio.latest inventory_turnover = Fundamentals.inventory_turnover.latest # Get return on invested capital roic = Fundamentals.roic.latest roic_5yr_avg = SimpleMovingAverage(inputs=[Fundamentals.roic], window_length=5 * 252) # Get f score f_score = Fscore(inputs=[ net_income, roa, op_cash_flow, op_cash_flow - net_income, long_term_debt - long_term_debt_1yr_ago, current_ratio - current_ratio_1yr_ago, share_issued - share_issued_1yr_ago, gross_margin - gross_margin_1yr_ago, assets_turnover - assets_turnover_1yr_ago ]) # Get sector sector_code = Fundamentals.morningstar_sector_code.latest # Return Pipeline containing close_price and # sentiment_score that has our trading universe as screen return Pipeline(columns={ 'earnings_yield': earnings_yield, 'pb_ratio': pb_ratio, 'roic': roic, 'roic_5yr_avg': roic_5yr_avg, 'f_score': f_score, 'sector_code': sector_code }, screen=base_universe)
def make_pipeline(context): ## symbol universe base_universe = Q500US() if False else Q1500US() ## filters # 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() is_cyclical = SuperSector().eq(SuperSector.CYCLICAL) is_defensive = SuperSector().eq(SuperSector.DEFENSIVE) is_sensitive = SuperSector().eq(SuperSector.SENSITIVE) # Filter for stocks that pass all of our previous filters. tradeable_stocks = ( primary_share &common_stock ¬_depositary ¬_otc ¬_wi ¬_lp_name ¬_lp_balance_sheet &have_market_cap #&(is_cyclical) #&(is_defensive) #&(is_sensitive) &(is_cyclical | is_defensive | is_sensitive) ) # ToDo この範囲を色々変えてみる. dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between(98, 100) daily_volatility = AnnualizedVolatility(window_length=20)/math.sqrt(252) sme20 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=20) rsi = RSI(inputs=[USEquityPricing.close]) #sector = ms.asset_classification.morningstar_sector_code sector = Sector() static_sectors = (sector.eq(311) | sector.eq(309) | sector.eq(103) | sector.eq(101) | sector.eq(308) | sector.eq(206) ) if context.static_asset: myscreen = StaticSids(context.special_sids) #context.special_assets else: myscreen = (base_universe & tradeable_stocks & high_dollar_volume ) # & static_sectors pipe = Pipeline( columns={ 'prev_close': PrevClose(), 'prev_volume': PrevVolume(), 'prev_turnover': PrevClose()*PrevVolume(), 'dollar_volume': dollar_volume, 'high_dollar_volume': high_dollar_volume, 'daily_volatility': daily_volatility, 'sma20': sme20, 'rsi': rsi, 'morningstar_sector_code': sector, }, screen=myscreen, ) return pipe
""" # Rebalance every day, 1 hour after market open. schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1)) # Record tracking variables at the end of each day. schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close()) schedule_function(frb, date_rules.month_start(), time_rules.market_open()) # Create our dynamic stock selector. attach_pipeline(make_pipeline(), 'my_pipeline') base_universe = Q500US() # Custom factor for MACD class MACD(CustomFactor): inputs = [USEquityPricing.close] window_length = 60 mask = base_universe # The initial value for EMA is taken as trialing SMA def ema(self, data, window): c = 2.0 / (window + 1) ema = np.mean(data[-(2 * window) + 1:-window + 1], axis=0) for value in data[-window + 1:]: ema = (c * value) + ((1 - c) * ema)