def make_pipeline(): base_universe = Q1500US() yesterday_close = PrevClose() yesterday_volume = PrevVolume() dollar_volume = AverageDollarVolume(window_length=30) # rsi = RSI()#default window_length = 15 # rsi_under_60 = rsi < 60 ## gap = today_open / yesterday_close - 1 では出来ない. ## TypeError: unsupported operand type(s) for /: 'BoundColumn' and 'BoundColumn' # gap = Gap() #ToDo この範囲を色々変えてみる. high_dollar_volume = dollar_volume.percentile_between(98, 100) pipe = Pipeline( columns = { 'yesterday_close': yesterday_close, 'yesterday_volume': yesterday_volume, 'yesterday_turnover': yesterday_close * yesterday_volume, 'dollar_volume': dollar_volume, 'high_dollar_volume': high_dollar_volume, # 'gap': gap, # 'rsi': rsi, }, screen = base_universe & high_dollar_volume #& rsi_under_60 ) return pipe
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 make_pipeline(): # UNIVERSE Q1500US base_universe = Q1500US() # ENERGY SECTOR (OR: sector = Sector()) sector = morningstar.asset_classification.morningstar_sector_code.latest energy_sector = sector.eq(309) # MAKE MASK OF 1500US & 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 AVERAGE DOLLAR VOLUME high_dollar_volume = dollar_volume.percentile_between(95, 100) # COMBINE THE FILTERS top_five_base_energy = base_energy & high_dollar_volume # GRAB THE 10-day & 30-day MEAN CLOSE mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mast=top_five_base_energy) mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mast=top_five_base_energy) # PERCENT DIFFERNENCE percent_difference = (mean_10 - mean_30) / mean_30 # LIST OF SHORTS & LONGS shorts, longs = (percent_difference < 0), (percent_difference > 0) # FINAL MASK/FILTER FOR ANYTHING IN SHORTS / LONGS securities_to_trade = shorts & longs # RETURN THE PIPELINE return Pipeline(columns={ 'longs': longs, 'shorts': shorts, 'percent_diff': percent_difference }, screen=securities_to_trade)
def initialize(context): # set_commission(commission.PerShare(cost=0, min_trade_cost=None)) # set_slippage(slippage.FixedSlippage(spread=0)) pipe = Pipeline() attach_pipeline(pipe, 'ranked') dollar_volume = AverageDollarVolume(window_length=1) high_dollar_volume = dollar_volume.percentile_between(95, 100) alpha41 = Alpha41(mask=high_dollar_volume) vwap = VWAP(window_length=1) alpha41 = alpha41**.5 - vwap alpha41_rank = alpha41.rank(mask=high_dollar_volume) roe = ROE(mask=high_dollar_volume) combo_raw = (alpha41_rank) pipe.add(combo_raw, 'combo_raw') pipe.set_screen(roe > .005) schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0, minutes=1)) context.long_leverage = .5 context.short_leverage = -.5 context.short_num = 20 context.long_num = 20
def make_pipeline(): base_universe = Q1500US() sector = morningstar.asset_classification.morningstar_sector_code.latest energy_sector = sector.eq(309) base_energy = base_universe & energy_sector dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between(95, 100) top_half_base_energy = base_energy & high_dollar_volume mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=top_half_base_energy) mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=top_half_base_energy) percent_difference = (mean_10 - mean_30) / mean_30 shorts = percent_difference < 0 longs = percent_difference > 0 securities_to_trade = (shorts | longs) return Pipeline(columns={ 'longs': longs, 'shorts': shorts, 'percent_diff': percent_difference }, screen=securities_to_trade)
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 my_pipeline(context): """ A function to create our dynamic stock selector (pipeline). Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ pipe = Pipeline() # span stands for past 120 days, need doulbe window length to get 120 data point. ewma120 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_long, span=context.look_back_long) pipe.add(ewma120, "ewma120") ewma60 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_middle, span=context.look_back_middle) pipe.add(ewma60, "ewma60") ewma15 = EWMA.from_span([USEquityPricing.close], window_length=2 * context.look_back_short, span=context.look_back_short) pipe.add(ewma15, "ewma15") pipe.add(Latest(inputs=[USEquityPricing.close]), "yes_price") momentum = (ewma120 - ewma60).abs() + (ewma60 - ewma15).abs() middle_momentum = momentum.percentile_between(0, 5) # Create a dollar volume factor. dollar_volume = AverageDollarVolume(window_length=1, mask=middle_momentum) pipe.add(dollar_volume, 'dollar_volume') # Pick the top 10% of stocks ranked by dollar volume. high_dollar_volume = dollar_volume.percentile_between(90, 100) pipe.set_screen(high_dollar_volume) return pipe
def make_pipeline(): pipe = Pipeline() # Base universe set to the QTradableStocksUS base_universe = QTradableStocksUS() #AverageDollarVolume dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between(99, 100) # Factor of yesterday's close price. yesterday_close = USEquityPricing.close.latest #price latest_close = EquityPricing.close.latest above_10 = latest_close > 10 #LongPattern LongPattern = (CloseYesterday(inputs = [USEquityPricing.close]) - CloseBeforeYesterday(inputs =[USEquityPricing.close])) / (CloseYesterday(inputs = [USEquityPricing.close])) #pipe.add(LongPattern, 'LongPattern') #LongPatternZscore LongPattern_Zscore = LongPattern.zscore() high_returns = LongPattern_Zscore.percentile_between(99,100) low_returns = LongPattern_Zscore.percentile_between(0,99) #securities_to_trade securities_to_trade = (high_returns | low_returns ) #volume volume_day_before_yeseterday = ValueDaybeforeYesterday(inputs =[USEquityPricing.volume]) volume_change_mean = ChangeAverage(inputs = [USEquityPricing.volume], window_length = 5) my_screen = base_universe & high_dollar_volume & securities_to_trade & above_10 pipe.set_screen(my_screen) return pipe
def make_pipeline(): # Base universe filter. base_universe = Q1500US() # Sector Classifier as Filter energy_sector = sector.eq(309) # Masking Base Energy Stocks base_energy = base_universe & energy_sector # Dollar volume factor dollar_volume = AverageDollarVolume(window_length=30) # Top half of dollar volume filter high_dollar_volume = dollar_volume.percentile_between(95,100) # Final Filter Mask top_half_base_energy = base_energy & high_dollar_volume # 10-day close price average. mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=top_half_base_energy) # 30-day close price average. mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=top_half_base_energy) # Percent difference factor. percent_difference = (mean_10 - mean_30) / mean_30 # Create a filter to select securities to short. shorts = percent_difference < 0 # Create a filter to select securities to long. longs = percent_difference > 0 # Filter for the securities that we want to trade. securities_to_trade = (shorts | longs) return Pipeline( columns={ 'longs': longs, 'shorts': shorts, 'percent_diff':percent_difference }, screen=securities_to_trade )
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(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(): dollar_volume = AverageDollarVolume(window_length=1) high_dollar_volume = dollar_volume.percentile_between(99, 100) pipe = Pipeline( screen = high_dollar_volume, columns = {'dollar_volume': dollar_volume} ) return pipe
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): """ 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(): """ A function to create our dynamic stock selector (pipeline). Documentation on pipeline can be found here: https://www.quantopian.com/help#pipeline-title """ # Create a dollar volume factor. dollar_volume = AverageDollarVolume(window_length=1) # Pick the top 1% of stocks ranked by dollar volume. high_dollar_volume = dollar_volume.percentile_between(99, 100) pipe = Pipeline( # screen = (high_dollar_volume & Q500US()), screen=Q1500US(), columns={'dollar_volume': dollar_volume}) return pipe
def make_pipeline(context): pipe = Pipeline() base_universe = QTradableStocksUS() dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between(98, 100) close_day_before_yeseterday = ValueDaybeforeYesterday( inputs=[USEquityPricing.close]) volume_day_before_yeseterday = ValueDaybeforeYesterday( inputs=[USEquityPricing.volume]) pipe.add(close_day_before_yeseterday, "close_day_before_yeseterday") my_screen = base_universe & high_dollar_volume pipe.set_screen(my_screen) return pipe
def make_pipeline(): base_universe = Q1500US() yesterday_close = PrevClose() yesterday_volume = PrevVolume() dollar_volume = AverageDollarVolume(window_length=30) #ToDo この範囲を色々変えてみる. high_dollar_volume = dollar_volume.percentile_between(98, 100) pipe = Pipeline(columns={ 'yesterday_close': yesterday_close, 'yesterday_volume': yesterday_volume, 'yesterday_turnover': yesterday_close * yesterday_volume, 'dollar_volume': dollar_volume, 'high_dollar_volume': high_dollar_volume, }, screen=base_universe & high_dollar_volume) return pipe
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(): 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) high_dollar_volume = dollar_volume.percentile_between(90, 100) latest_close = USEquityPricing.close.latest above_20 = latest_close > 20 tradeable_filter = high_dollar_volume & above_20 return Pipeline(columns={'percent_difference': percent_difference}, screen=tradeable_filter)
def initialize(context): # Create and attach an empty Pipeline. pipe = make_pipeline() attach_pipeline(pipe, 'pipe') context.stock = pd.DataFrame(index=np.arange(500), columns=['name', 'Bollinger Up', 'Bollinger Down', 'Long_Order', 'Short_Order']) context.stock.fillna(value=0) dollar_volume = AverageDollarVolume(window_length=30) high_dollar_volume = dollar_volume.percentile_between(97, 100) pipe.set_screen(high_dollar_volume) latest_close = USEquityPricing.close.latest pipe.add(latest_close, 'Close') BB = BollingerBands(window_length = 30, k=1) pipe.add(BB, 'Bollinger Bands') schedule_function( func=myfunc, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=120), )
def initialize(context): # Create, register and name a pipeline in initialize. pipe = Pipeline() attach_pipeline(pipe, 'dollar_volume_10m_pipeline') # Construct a 100-day average dollar volume factor and add it to the pipeline. dollar_volume = AverageDollarVolume(window_length=100) pipe.add(dollar_volume, 'dollar_volume') #Create high dollar-volume filter to be the top 2% of stocks by dollar volume. high_dollar_volume = dollar_volume.percentile_between(99, 100) # Set the screen on the pipelines to filter out securities. pipe.set_screen(high_dollar_volume) context.dev_multiplier = 2 context.max_notional = 1000000 context.min_notional = -1000000 context.days_traded = 0 schedule_function(func=process_data_and_order, date_rule=date_rules.every_day())
def make_pipeline(context): """ A function to create our pipeline (dynamic stock selector). The pipeline is used to rank stocks based on different factors, including builtin factors, 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. # Create a dollar_volume factor using default inputs and window_length. # This is a builtin factor. dollar_volume = AverageDollarVolume(window_length=1) # Define high dollar-volume filter to be the top 5% of stocks by dollar volume. high_dollar_volume = dollar_volume.percentile_between(95, 100) # Create a recent_returns factor with a 5-day returns lookback for all securities # in our high_dollar_volume Filter. This is a custom factor defined below (see # RecentReturns class). recent_returns = Returns(window_length=context.returns_lookback, mask=high_dollar_volume) # 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) high_returns = recent_returns.percentile_between(90, 100) # Define a column dictionary that holds all the Factors pipe_columns = { 'low_returns': low_returns, 'high_returns': high_returns, 'recent_returns': recent_returns, 'dollar_volume': dollar_volume } # Add a filter to the pipeline such that only high-return and low-return # securities are kept. pipe_screen = (low_returns | high_returns) # Create a pipeline object with the defined columns and screen. pipe = Pipeline(columns=pipe_columns, screen=pipe_screen) return pipe
def my_pipeline(context): pipe = Pipeline() revenue_growth = morningstar.operation_ratios.revenue_growth.latest dil_eps_growth = morningstar.earnings_ratios.diluted_eps_growth.latest net_income_growth = morningstar.operation_ratios.net_income_growth.latest operation_income_growth = morningstar.operation_ratios.operation_income_growth.latest #Filters # Only consider the top 10% of stocks ranked by dollar volume. dollar_volume = AverageDollarVolume(window_length=1) high_dollar_volume = dollar_volume.percentile_between(90, 100) #Traditional growth stocks metrics: >25% growth in all related factors rev_filter = revenue_growth > 0.20 eps_filter = dil_eps_growth > 0.20 income_filter = net_income_growth > 0.20 opin_filter = operation_income_growth > 0.20 # Create a regression factor with SPY. regression = RollingLinearRegressionOfReturns( target=context.target_asset, returns_length=context.returns_length, regression_length=context.regression_length, mask=high_dollar_volume, ) alpha = regression.alpha beta = regression.beta correlation = regression.r_value low_beta = (beta < context.beta_threshold) & \ (beta > -context.beta_threshold) high_beta = ~low_beta pipe.add(alpha, 'alpha') pipe.add(beta, 'beta') pipe.add(correlation, 'correlation') pipe.add(low_beta, 'low_beta') pipe.add(high_beta, 'high_beta') pipe.set_screen(rev_filter & eps_filter & income_filter & opin_filter & high_dollar_volume) return pipe pass
def make_pipeline(): # PREPARE MASKS ## CATEGORICAL MASKS universe_filter = Q1500US() sector_filter = morningstar.asset_classification.morningstar_sector_code.latest.eq(309) # 309 is energy sector # exchange_filter = morningstar.share_class_reference.exchange_id.latest.eq('NYS') base_filter = ( universe_filter & sector_filter # & exchange_filter ) ## NUMERIC/FACTOR MASKS volume_ma30 = AverageDollarVolume(window_length=30) volume_ma30_filter = volume_ma30.percentile_between(95, 100) # mkt_cap_filter = morningstar.Fundamentals.market_cap.latest < 100000000 base_filter = ( base_filter & volume_ma30_filter # & mkt_cap_filter ) close_ma30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=base_filter) close_ma10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=base_filter) pct_diff = (close_ma10 - close_ma30) / close_ma30 shorts_filter = pct_diff < 0 longs_filter = pct_diff > 0 base_filter = ( base_filter & (shorts_filter | longs_filter) ) return Pipeline( columns={ 'Close MA30': close_ma30, 'Pct Diff': pct_diff, 'Longs': longs_filter, 'Shorts': shorts_filter }, screen=base_filter )
def make_pipeline(): base_universe = Q1500US() yesterday_close = PrevClose() yesterday_volume = PrevVolume() dollar_volume = AverageDollarVolume(window_length=30) static_assets = StaticAssets(symbols('NFLX', 'GPRO', 'TSLA', 'FCX', 'AMZN', 'TWTR', 'M', 'AAL','SWKS', 'GOOG_L', 'BIIB', 'CELG', 'AL', 'SNE', 'AMGN','FB', 'PCLN', 'GILD', 'MYL', 'AVGO', 'WYNN', 'HAL','AMBA','DAL', 'EBAY', 'LVS', 'YHOO')) #ToDo この範囲を色々変えてみる. high_dollar_volume = dollar_volume.percentile_between(98, 100) pipe = Pipeline( columns = { 'yesterday_close': yesterday_close, 'yesterday_volume': yesterday_volume, 'yesterday_turnover': yesterday_close * yesterday_volume, 'dollar_volume': dollar_volume, 'high_dollar_volume': high_dollar_volume, }, screen = base_universe & high_dollar_volume, # screen = static_assets & high_dollar_volume, ) 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(): 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 = 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
# import groupings # ---------------- rbics_economy_number = RBICSFocus.l1_id.latest rbics_economy = RBICSFocus.l1_name.latest # Defining universe criteria # -------------------------- avg_day_dv_200 = AverageDollarVolume(window_length=200) mcap = Fundamentals.mkt_val.latest price = EquityPricing.close.latest volume = EquityPricing.volume.latest # Set Universe # ------------ universe = ( avg_day_dv_200.percentile_between(5, 100) & (price > 5.0) & (mcap > 100e6) & EquityMetadata.security_type.latest.eq("SHARE") & EquityMetadata.is_primary.latest & volume.notnull() ) universe_top500 = mcap.top(500, mask=universe) # Creating custom factors # ----------------------- class lt_mom(CustomFactor): inputs = [EquityPricing.close] window_length = 252
def initialize(context): context.lookback = 252 # Period to calculate slope and draw down context.maxlever = 1.0 # Leverage context.profittake = 1.96 # 95% bollinger band for profit take context.minimumreturn = 0.1 # Entry if annualized slope is over this level context.maxdrawdown = 0.12 # Avoid security with too much drawdown context.market_impact = 0.2 # Max order is 10% of market trading volume context.weights = {} # Slope at the time of entry. 0 if not to trade context.drawdown = {} # Draw down at the time of entry context.shares = {} # Daily target share schedule_function(regression, date_rules.every_day(), time_rules.market_open(minutes=45)) schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes=90) schedule_function(trail_stop, date_rules.every_day(), time_rules.market_open(minutes=30)) # Run trailing stop and execution every 30 minutes. for m in range(1, 391): if m % 30 == 0: schedule_function(execute, date_rules.every_day(), time_rules.market_open(minutes = m)) # Create and attach our pipeline (top dollar-volume selector), defined below. attach_pipeline(high_dollar_volume_pipeline(), 'top_dollar_volume') def high_dollar_volume_pipeline(): # Create a pipeline object. pipe = Pipeline() # Create a factor for average dollar volume over the last 62 day (1 quarter equivalent). dollar_volume = AverageDollarVolume(window_length=62) 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 before_trading_start(context, data): context.pipe_output = pipeline_output('top_dollar_volume') context.security_list = context.pipe_output.index # Calculate the slopes for different assetes def regression(context, data): prices = data.history(context.security_list, 'open', context.lookback, '1d') X=range(len(prices)) # Add column of ones so we get intercept A=sm.add_constant(X) for s in context.security_list: # Price movement sd = prices[s].std() # Price points to run regression Y = prices[s].values # If all empty, skip if isnan(Y).any(): continue # Run regression y = ax + b results = sm.OLS(Y,A).fit() (b, a) =results.params # a is daily return. Multiply by 252 to get annualized trend line slope slope = a / Y[-1] * 252 # Daily return regression * 1 year if slope > 0: dd = drawdown(Y) if slope < 0: dd = drawdown(-Y) # Currently how far away from regression line? delta = Y - (dot(a,X) + b) # Don't trade if the slope is near flat slope_min = max(dd, context.minimumreturn) # Max drawdown and minimum return # Current gain if trading gain = get_gain(context, s) # Exits if s in context.weights and context.weights[s] != 0: # Long but slope turns down, then exit if context.weights[s] > 0 and slope < 0: context.weights[s] = 0 log.info('v %+2d%% Slope turn bull %3s - %s' %(gain*100, s.symbol, s.security_name)) # Short but slope turns upward, then exit if context.weights[s] < 0 and 0 < slope: context.weights[s] = 0 log.info('^ %+2d%% Slope turn bear %3s - %s' %(gain*100, s.symbol, s.security_name)) # Profit take, reaches the top of 95% bollinger band if delta[-1] > context.profittake * sd and s in context.weights and context.weights[s] > 0: context.weights[s] = 0 log.info('//%+2d%% Long exit %3s - %s'%(gain*100, s.symbol, s.security_name)) # Profit take, reaches the top of 95% bollinger band if delta[-1] < - context.profittake * sd and context.weights[s] < 0: context.weights[s] = 0 log.info('\\%+2d%% Short exit %3s - %s' %(gain*100, s.symbol, s.security_name)) # Entry else: # Trend is up and price crosses the regression line if slope > slope_min and delta[-1] > 0 and delta[-2] < 0 and dd < context.maxdrawdown: context.weights[s] = slope context.drawdown[s] = slope_min log.info('/ Long a = %+.2f%% %3s - %s' %(slope*100, s.symbol, s.security_name),gain) # Trend is down and price crosses the regression line if slope < -slope_min and delta[-1] < 0 and delta[-2] > 0 and dd < context.maxdrawdown: context.weights[s] = slope context.drawdown[s] = slope_min log.info('\ Short a = %+.2f%% %3s - %s' %(slope*100, s.symbol, s.security_name)) def get_gain(context, s): if s in context.portfolio.positions: cost = context.portfolio.positions[s].cost_basis amount = context.portfolio.positions[s].amount price = context.portfolio.positions[s].last_sale_price if cost == 0: return 0 if amount > 0: gain = price/cost - 1 elif amount < 0: gain = 1 - price/cost else: gain = 0 return gain def trade(context, data): w = context.weights record(leverage_pct = context.account.leverage*100.) record(longs = sum(context.portfolio.positions[s].amount > 0 for s in context.portfolio.positions)) record(shorts = sum(context.portfolio.positions[s].amount < 0 for s in context.portfolio.positions)) positions = sum(w[s] != 0 for s in w) held_positions = [p for p in context.portfolio.positions if context.portfolio.positions[p].amount != 0] context.securities = context.security_list.tolist() + held_positions for s in context.securities: if s not in w: context.shares.pop(s,0) context.drawdown.pop(s,0) elif w[s] == 0: context.shares.pop(s,0) context.drawdown.pop(s,0) context.weights.pop(s,0) elif w[s] > 0: context.shares[s] = context.maxlever/positions elif w[s] < 0: context.shares[s] = -context.maxlever/positions def execute(context,data): open_orders = get_open_orders() for s in context.shares: if not data.can_trade(s) or s in open_orders: continue order_target_percent(s, context.shares[s]) # We are entering into position when slope exceeds the drawdown # If we experience the drawdown again, stop loss def trail_stop(context, data): print get_datetime() print 'Positions: %s' % str(context.portfolio.positions.keys()) prices = data.history(context.portfolio.positions.keys(), 'price', context.lookback, '1d') for s in context.portfolio.positions: if s not in context.weights or context.weights[s] == 0: context.shares[s] = 0 continue if s not in prices or s in get_open_orders(): continue gain = get_gain(context, s) if context.portfolio.positions[s].amount > 0: if drawdown(prices[s].values) > context.drawdown[s]: log.info('x %+2d%% Long stop loss %3s - %s' %(gain * 100, s.symbol, s.security_name)) context.weights[s] = 0 context.shares[s] = 0 elif context.portfolio.positions[s].amount < 0: if drawdown(-prices[s].values) > context.drawdown[s]: log.info('x %+2d%% Short stop loss %3s - %s' %(gain * 100, s.symbol, s.security_name)) context.weights[s] = 0 context.shares[s] = 0 # Reference http://stackoverflow.com/questions/22607324/start-end-and-duration-of-maximum-drawdown-in-python def drawdown(xs): if len(xs) == 0: return 0. i = np.argmax(np.maximum.accumulate(xs) - xs) # end of the period if len(xs[:i]) == 0: return 0. j = np.argmax(xs[:i]) # start of period return abs((xs[i] - xs[j]) / xs[j])
def make_pipeline(): # PIPE ( 1 ) # queries quantopians q1500us read more for details on filter base_universe_pipe = Q1500us() # PIPE ( 2 ) # filters for the energy sector energy_sector_pipe = sector.eq(309) # PIPE ( 3 ) # filter 1500US and Energy Sector base_energy_pipe = base_universe_pipe & energy_sector_pipe # PIPE ( 4 ) # queries Dollar Volume (30 Days) Grab the Data dollar_volume_pipe = AverageDollarVolume(window_length=30) # PIPE ( 5 ) # Filters highest 10% in dollar_volume_pipe high_dollar_volume_pipe = dollar_volume_pipe.percentile_between(90,100) # PIPE ( 6 ) # Filters top 50 results based on the open value in high_dollar_volume set top_open_prices_pipe = USEquityPricing.open.latest.top(50, mask = high_dollar_volume_pipe) # PIPE ( 7 ) # Filters highest 10% based on the close value in top_open_prices_pipe high_close_price_pipe = USEquityPricing.close.latest.percentile_between(90, 100, mask = top_open_prices_pipe) # PIPE ( 8 ) # Combine the filters (pipes) top_ten_base_energy_pipe = base_energy_pipe & high_dollar_volume_pipe # PIPE ( 9 ) # (10 Day) Mean Close mean_10 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=10, mask=top_ten_base_energy_pipe) # (30 Day) Mean Close mean_30 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length = 30, mask = top_ten_base_energy_pipe) # Percentage Difference percent_difference = (mean_10 - mean_30) / mean_30 # Execute trade on short condition to List of Shorts shorts = percent_difference < 0 # Execute trade on long condition to List of Longs longs = percent_difference > 0 # Final Pipe filter for anything in Shorts or Longs (Lists) securities_to_trade = (shorts | longs) # Return the pipeline ####################### # Bollinger Bands # ####################### df['Close: 20 Day Mean'] = df['Close'].rolling(20).mean() # Upper Band = 20MA + 2*std(20) df['UpperBand'] = df['Close: 20 Day Mean'] + 2*(df['Close'].rolling(20).std()) # Lower Band = 20MA - 2*std(20) df['LowerBand'] = df['Close: 20 Day Mean'] - 2*(df['Close'].rolling(20).std()) # Graph that whole party df[['Close', 'Close: 20 Day Mean', 'Upper', 'Lower']].plot(figsize=(16,6)) return Pipeline(columns = {'longs': longs, 'shorts': shorts, 'perc_diff': percent_difference }, screen = securities_to_trade)
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
def make_pipeline(context): #create pipeline pipe = Pipeline() #use built in factor AverageDollarVolume to screen for liquid stocks avg_dollar_volume = AverageDollarVolume(window_length=1) pipe.add(avg_dollar_volume, 'avg_dollar_volume') #use built in factor Returns to get returns over the recent_lookback window recent_returns = Returns(window_length=context.returns_lookback) pipe.add(recent_returns, 'recent_returns') #filter out stocks in the top % of dollar volume high_dollar_volume = avg_dollar_volume.percentile_between(95, 100) #rank the recent returns in the high dollar volume group and add to pipe pipe.add(recent_returns.rank(mask=high_dollar_volume), 'recent_returns_rank') #get stocks with the highest and lowest returns 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) #add high and low returns as columns to pipeline for easier data mgmt pipe.add(high_returns, 'high_returns') pipe.add(low_returns, 'low_returns') ######Earnings Announcement Risk Framework############# # https://www.quantopian.com/data/eventvestor/earnings_calendar # EarningsCalendar.X is the actual date of the announcement # E.g. 9/12/2015 pipe.add(EarningsCalendar.next_announcement.latest, 'next') pipe.add(EarningsCalendar.previous_announcement.latest, 'prev') # BusinessDaysX is the integer days until or after the closest # announcement. So if AAPL had an earnings announcement yesterday, # prev_earnings would be 1. If it's the day of, it will be 0. # For BusinessDaysUntilNextEarnings(), it is common that the value # is NaaN because we typically don't know the precise date of an # earnings announcement until about 15 days before ne = BusinessDaysUntilNextEarnings() pe = BusinessDaysSincePreviousEarnings() pipe.add(ne, 'next_earnings') pipe.add(pe, 'prev_earnings') # The number of days before/after an announcement that you want to # avoid an earnings for. # pipe.set_screen ( (ne.isnan() | (ne > 3)) & (pe > 3) ) #####Set Pipe based on the desired framework###### #screen the pipeline by the high and low returns(and high dollar volume, implicitly pipe.set_screen(high_returns | low_returns | ((ne.isnan() | (ne > 3)) & (pe > 3))) # pipe.set_screen(high_returns | low_returns) return pipe