def make_pipeline(): ''' Create pipeline. ''' # Base universe base_universe = QTradableStocksUS() # Latest p/e ratio. pe_ratio = Fundamentals.pe_ratio.latest # Number of stocks invested long and short at the same time num = 60 # Top 60 and bottom 60 stocks ranked by p/e ratio top_pe_stocks = pe_ratio.top(num, mask=base_universe) bottom_pe_stocks = pe_ratio.bottom(num, mask=base_universe) # Calculate the RSI indicator and the ranking for the stocks rsi = RSI(inputs=[USEquityPricing.close], window_length=14, mask=base_universe) oversold = rsi < 30 and rsi.bottom(num) overbought = rsi > 70 and rsi.top(num) #mean = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=15, mask=base_universe) #mean_new = mean close_price =USEquityPricing.close.latest #calculate the Bollinger Bands: upperBB, middleBB, lowerBB = BollingerBands(mask=base_universe, window_length=20, k=2) # Select securities to short shorts = overbought and upperBB < close_price and top_pe_stocks #shorts =upperBB < close_price and top_pe_stocks # Select securities to long longs = oversold and close_price < lowerBB and bottom_pe_stocks #longs = close_price < lowerBB and bottom_pe_stocks # All securities that want to trade (fulfilling the criteria) securities_to_trade = (shorts | longs) return Pipeline( columns={ 'rsi': rsi, 'upperBB' :upperBB, 'lowerBB':lowerBB, '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)) return Pipeline( columns={ 'RSI': rsi, 'SMA_short': short_sma, 'SMA_long': long_sma, 'symbol': symbol, }, screen=symbol, )
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 = Q1500US() sector = Sector() # screen is based off of returns returns = Returns(window_length=2) # check if stock price has good strength, but not necessarily overbought rsi = RSI() price = USEquityPricing.close.latest # creating filter by specifying the type of returns desired top_return_stocks = returns.top(1, mask=base_universe, groupby=sector) pipe = Pipeline( columns={ 'rsi': rsi, 'price': price }, # filter top return stocks, and stocks that are not being overbought # but are not too oversold either screen=base_universe & top_return_stocks & (20 < rsi < 80) # the above is equivalent to: choose stocks from the base universe that have had the top returns in their sectors and have a good RSI value ) return pipe
def make_pipeline(context): base_universe = Q500US() # 昨日の終値 yesterday_close = USEquityPricing.close.latest yesterday_volume = USEquityPricing.volume.latest dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between( context.high_dollar_volume_thresh_min, context.high_dollar_volume_thresh_max) sector = Sector() rsi = RSI(inputs=[USEquityPricing.close]) pipe = Pipeline(screen=base_universe & high_dollar_volume, columns={ 'high_dollar_volume': high_dollar_volume, 'sector': sector, 'rsi': rsi, 'roa': ROA(), 'roe': ROE(), 'normalized_basic_eps': NormalizedBasicEps(), 'net_income_growth': NetIncomeGrowth(), 'pe': PE(), 'book_value_yield': BookValueYield(), 'dividend_yield': DividendYield(), 'period_ending_date': PeriodEndingDate(), 'prev_close': yesterday_close, }) return pipe
def make_pipeline(): have_market_cap = morningstar.valuation.market_cap.latest.notnull() avg_volume = SimpleMovingAverage(inputs=[USEquityPricing.volume], window_length=50) filter_volume = avg_volume > 500000 last_price = Latest(inputs=[USEquityPricing.close], window_length=1) filter_price = last_price > 1 dollar_volume = AverageDollarVolume(window_length=50) filter_dollar_volume = dollar_volume > 2500000 sma_150 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=150) filter_sma_150 = USEquityPricing.close.latest > sma_150 atr_10_percent = atr_10days_percent() filter_atr_10 = atr_10_percent > 4 rsi = RSI(inputs=[USEquityPricing.close], window_length=3) filter_overbought = rsi < 30 atr_10 = atr_10days() stocks_to_trade = have_market_cap & filter_volume & filter_price & filter_dollar_volume & filter_sma_150 & filter_atr_10 & filter_overbought return Pipeline(columns={ 'stocks': stocks_to_trade, 'rsi': rsi, 'atr': atr_10 }, screen=(stocks_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) rsi_7 = RSI(inputs=[USEquityPricing.close], window_length=10) percent_difference = (mean_close_10 - mean_close_30) / mean_close_30 rsi_under_35 = (rsi_7 < 35) latest_close = USEquityPricing.close.latest dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between(85, 100) filters = high_dollar_volume & rsi_under_35 return Pipeline(columns={ '10_day_mean_close': mean_close_10, 'latest_close_price': latest_close, 'percent_difference': percent_difference, 'dollar_value': dollar_volume }, screen=filters)
def initialize(context): set_slippage( slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1)) set_commission(commission.PerShare( cost=0.000, min_trade_cost=0.00)) # Assume Robinhood zero-commissions # Filter order: # 1. MktCap > X # filters stocks with minimum size # 2. Volume > X # filters stocks with minimum volume # 3. X < SMA_200 & X < SMA_10 # filter stocks with gaps more likely to fill # 4. Y < RSI < X # filters stocks with (+) momentum and strong trend mkt_cap = MarketCap() last_close = LastClose() dollar_volume = AverageDollarVolume(window_length=10) sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200) sma_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10) rsi = RSI(inputs=[USEquityPricing.close], window_length=15) mkt_cap_rank = mkt_cap.rank(ascending=False) mkt_cap_filter = (mkt_cap_rank < 4000) #sma_filter = (last_close > sma_10) # & (last_close < sma_200) # shouldnt be last close, should be open price dollar_volume_filter = (dollar_volume > 100000) rsi_filter = (rsi > 15) & (rsi < 50) pipe = Pipeline( columns={ 'mkt_cap_rank': mkt_cap_rank, 'last_close': last_close, '$volume': dollar_volume, 'sma_200%': last_close / sma_200, 'sma_10%': last_close / sma_10, 'rsi/50': rsi / 50 }, screen=(mkt_cap_filter & dollar_volume_filter & rsi_filter ) # & sma_filter) ) attach_pipeline(pipe, name='my_pipeline') for i in range(2, 5): schedule_function( # This will execute buys at 9:31AM openFunction, date_rules.week_start( days_offset=i), #do not run on Mondays (poor success) time_rules.market_open(minutes=1), False #exclude half days ) schedule_function( # This will sell open positions before close closeFunction, date_rules.week_start( days_offset=i), #do not run on Mondays (poor success) time_rules.market_close(minutes=30), False #exclude half days )
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(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(): """ A function to create our dynamic stock selector (pipeline). Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ rsi = RSI(inputs=[USEquityPricing.close], window_length=10) symbol = SidInList(sid_list=(8554)) return Pipeline( columns={ 'RSI': rsi, 'symbol': symbol, }, screen=symbol, )
def make_pipeline(): """ Create our pipeline. """ # Base universe set to the QTradableStocksUS. base_universe = QTradableStocksUS() # 50-day close price average. mean_50 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=base_universe) # 180-day close price average. mean_180 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=base_universe) bollinger_bands = BollingerBands(window_length=20, k=2) lower_band = bollinger_bands.lower upper_band = bollinger_bands.upper percent_difference = (mean_50 - mean_180) / mean_50 RSI_Factor = RSI(inputs=[USEquityPricing.close], window_length=30, mask=base_universe) RSI_Filter = RSI_Factor > 98 # Filter to select securities to short. shorts = percent_difference.top(20) | (USEquityPricing.close > upper_band) longs = percent_difference.bottom(20) | (USEquityPricing.close < lower_band) securities_to_trade = (percent_difference.top(50) | percent_difference.bottom(50)) return Pipeline(columns={ 'longs': longs, 'shorts': shorts }, screen=(securities_to_trade))
def make_pipeline(context): # Parameters fast_ma_periods = context.fast_ma_periods slow_ma_periods = context.slow_ma_periods assets = context.assets # Define factors. if context.fast_ma_type == 'sma': ma_fast = SimpleMovingAverage(inputs=[EquityPricing.close], window_length=fast_ma_periods) else: ma_fast = EWMA.from_span( inputs=[EquityPricing.close], window_length=fast_ma_periods * 2 + 20, span=fast_ma_periods, ) if context.slow_ma_type == 'sma': ma_slow = SimpleMovingAverage(inputs=[EquityPricing.close], window_length=slow_ma_periods) else: ma_slow = EWMA.from_span( inputs=[EquityPricing.close], window_length=slow_ma_periods * 2 + 20, span=slow_ma_periods, ) last_close_price = EquityPricing.close.latest rsi = RSI(inputs=[EquityPricing.close], window_length=context.rsi_period) # Define a filter. base_universe = StaticAssets(assets) # define pipeline pipe = Pipeline(columns={ 'price': last_close_price, 'fast_ma': ma_fast, 'slow_ma': ma_slow, 'rsi': rsi }, screen=base_universe) return pipe
def make_pipeline(): base_universe = Q1500US() yesterday_close = PrevClose() today_open = USEquityPricing.open dollar_volume = AverageDollarVolume(window_length=30) ## gap = today_open / yesterday_close - 1 では出来ない. ## TypeError: unsupported operand type(s) for /: 'BoundColumn' and 'BoundColumn' gap = Gap() rsi = RSI() #default window_length = 15 rsi_under_60 = rsi < 60 #ToDo この範囲を色々変えてみる. high_dollar_volume = dollar_volume.percentile_between(98, 100) pipe = Pipeline( columns={ 'close': yesterday_close, 'today_open': today_open.latest, 'dollar_volume': dollar_volume, 'high_dollar_volume': high_dollar_volume, 'gap': gap, }, screen=base_universe & high_dollar_volume & rsi_under_60, ) return pipe
symbols('WCLD'), symbols('ARKF'), symbols('ARKG'), symbols('ARKW'), symbols('STAG'), symbols('IRT'), symbols('CHNG'), ] # Define factors. fast_ma = SimpleMovingAverage(inputs=[EquityPricing.close], window_length=fast_ma_periods) slow_ma = SimpleMovingAverage(inputs=[EquityPricing.close], window_length=slow_ma_periods) # ema = EWMA.from_span(inputs=[EquityPricing.close], window_length=slow_ma_periods*2+20, span=slow_ma_periods,) rsi = RSI(inputs=[EquityPricing.close], window_length=5) price = EquityPricing.close.latest sell = (price < fast_ma) & (price < slow_ma) buy = (price > fast_ma) & (price > slow_ma) # Define a filter. base_universe = StaticAssets(assets) # define pipeline pipe = Pipeline( columns={ 'yersterday_price': price, 'ma_fast': fast_ma, 'ma_slow': slow_ma, #'ema': ema, 'rsi': rsi,
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
remove_ticker = ticker2 else: remove_ticker = ticker1 if remove_ticker in tickers: tickers.remove(remove_ticker) assets = [] for t in tickers: assets.append(symbols(t)) return_6m = PercentChange(inputs=[EquityPricing.close], window_length=126) return_1m = PercentChange(inputs=[EquityPricing.close], window_length=21) return_2w = PercentChange(inputs=[EquityPricing.close], window_length=10) stoch_k = FastStochasticOscillator( [EquityPricing.close, EquityPricing.low, EquityPricing.high]) stoch_d = SimpleMovingAverage(inputs=[stoch_k], window_length=4) rsi = RSI(inputs=[EquityPricing.close]) base_universe = StaticAssets(assets) pipe = Pipeline( columns={ 'return_6m': return_6m, 'return_1m': return_1m, 'return_2w': return_2w, 'stoch_d': stoch_d, 'rsi': rsi }, screen=base_universe & (return_2w >= return_1m) #& (return_2w > 0) & (stoch_d > 0) ) pipeline_result = run_pipeline(pipe, '2020-08-25', '2020-08-25') m = np.median(pipeline_result['return_6m'])