def initialize(context): NCAV = NCAVRatio() NCAVINV = InverseNCAV() schedule_function(rebalance, date_rules.week_start(), time_rules.market_open()) # Create and apply a filter representing the top 500 equities by MarketCap # every day. # Construct an average dollar volume factor PERatio = PE() Solid_PE = PERatio < 10 Short_PE = PERatio > 50 div = Dividends() Solid_Div = div >= 0.02 Short_Div = PERatio >100 LongsUniverse = Q1500US() & Solid_PE & Solid_Div#& Not_Bio#& high_dollar_volume ShortsUniverse = Q1500US() & Short_PE & Short_Div # Create filters for our long and short portfolios. longs = NCAV.top(15, mask=LongsUniverse) shortsTest = NCAVINV.top(15) shorts = NCAVINV.top(15, mask=ShortsUniverse) print "List of stocksTEST for short position : {}".format(shortsTest) print "List of stocks for short position : {}".format(shorts) Universe= (longs|shorts|shortsTest) pipe = Pipeline(columns = {'longs': longs, 'shorts': shorts, 'shortsTest': shortsTest}, screen = Universe) attach_pipeline(pipe, 'Value_Investing')
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 Q500US base_universe = Q1500US() trading_universe = Q1500US() # Factor of yesterday's close price. pricing = USEquityPricing.close.latest primary_share = IsPrimaryShare(mask=base_universe) market_cap = Market_cap(mask=base_universe) sales = Sales(mask=base_universe) industry = Industry(mask=base_universe) universe = (primary_share & (pricing > 5)) return Pipeline( # screen = base_universe, screen=universe, columns={ 'market_cap': market_cap, 'sales': sales, 'industry': industry, 'in_trading_univ': trading_universe, })
def make_pipeline(): testing_factor1 = operation_ratios.operation_revenue_growth3_month_avg.latest #operation ratios testing_factor2 = sentiment.sentiment_signal.latest #sentiment testing_factor3 = valuation_ratios.dividend_yield.latest #valuation testing_factor4 = cash_flow_statement.free_cash_flow.latest #cashflow universe = (Q1500US() & testing_factor1.notnull() & testing_factor2.notnull() & testing_factor3.notnull() & testing_factor4.notnull()) testing_factor1 = testing_factor1.rank(mask=universe, method='average') testing_factor2 = testing_factor2.rank(mask=universe, method='average') testing_factor3 = testing_factor3.rank(mask=universe, method='average') testing_factor4 = testing_factor4.rank(mask=universe, method='average') testing_factor = testing_factor2 + testing_factor3 + testing_factor4 #testing_factor1 + testing_quantiles = testing_factor.quantiles(2) pipe = Pipeline(columns={ 'testing_factor': testing_factor, 'shorts': testing_quantiles.eq(0), 'longs': testing_quantiles.eq(1) }, screen=universe) return pipe
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(): # try many types i.e. # Yes: operation_ratios.revenue_growth.latest, operation_ratios.operation_margin, sentiment testing_factor1 = operation_ratios.operation_margin.latest testing_factor2 = operation_ratios.revenue_growth.latest testing_factor3 = sentiment.sentiment_signal.latest universe = (Q1500US() & testing_factor1.notnull() & testing_factor2.notnull() & testing_factor3.notnull()) testing_factor1 = testing_factor1.rank(mask=universe, method='average') testing_factor2 = testing_factor2.rank(mask=universe, method='average') testing_factor3 = testing_factor3.rank(mask=universe, method='average') testing_factor = testing_factor1 + testing_factor2 + testing_factor3 testing_quantiles = testing_factor.quantiles(2) pipe = Pipeline(columns={ 'testing_factor': testing_factor, 'shorts': testing_quantiles.eq(0), 'longs': testing_quantiles.eq(1) }, screen=universe) 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 """ pipe = Pipeline() # Base universe set to the Q1500US. base_universe = Q1500US() # Get returns of base universe stocks starting from 12 months ago (252 trading days ago). returns_12m = Returns(window_length=252, mask=base_universe) # Get returns of base universe stocks starting from 2 months ago (42 trading days ago). returns_2m = Returns(window_length=42, mask=base_universe) # Get returns of base universe stocks starting from 12 months and ending 2 months ago. returns_diff = returns_12m - returns_2m # Divide those returns into deciles. returns_diff_decile = returns_diff.deciles() # Filter to select securities to long longs = (returns_diff_decile.eq(9)) pipe.add(longs, 'longs') # Filter to select securities to short shorts = (returns_diff_decile.eq(0)) pipe.add(shorts, 'shorts') # Filter for all securities that we want to trade securities_to_trade = (longs | shorts) pipe.set_screen(securities_to_trade) 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(): sentiment_factor = stocktwits.bull_minus_bear.latest not_near_earnings_announcement = ~( (BusinessDaysUntilNextEarnings() <= 2) | (BusinessDaysSincePreviousEarnings() <= 2)) new_info = (BusinessDaysSincePreviousEvent( inputs=[stocktwits.asof_date.latest]) <= 1) not_accounced_acq_target = ~IsAnnouncedAcqTarget() universe = (Q1500US() & sentiment_factor.notnull() & not_near_earnings_announcement & not_accounced_acq_target & new_info) # A classifier to separate the stocks into quantiles based on sentiment rank. sentiment_quantiles = sentiment_factor.rank(mask=universe, method='average').quantiles(2) # pipe = Pipeline(columns={ 'sentiment': sentiment_quantiles, 'shorts': sentiment_factor <= -2, 'longs': sentiment_factor >= 2.5, }, screen=universe) return pipe
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 """ # Filter for stocks in the Q1500US universe. For more detail, see this post: # https://www.quantopian.com/posts/the-q500us-and-q1500us universe = Q1500US() # Create a Returns factor with a 5-day lookback window for all # securities in our Q1500US Filter. recent_returns = Returns(window_length=context.returns_lookback, mask=universe) # 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) # Add a filter to the pipeline such that only high-return and low-return # securities are kept. securities_to_trade = (low_returns | high_returns) # Create a pipeline object with the defined columns and screen. pipe = Pipeline(columns={ 'low_returns': low_returns, 'high_returns': high_returns, }, screen=securities_to_trade) return pipe
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(): """ Create our pipeline. """ # Base universe set to the Q1500US. base_universe = Q1500US() # 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(25) # Filter to select securities to long. longs = percent_difference.bottom(25) # 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 initialize(context): NCAV = NCAVRatio() schedule_function(rebalance, date_rules.week_start(), time_rules.market_open()) # Construct the custom factor # Create and apply a filter representing the top 500 equities by MarketCap # every day. # Construct an average dollar volume factor PERatio = PE() Solid_PE = PERatio < 10 div = Dividends() Solid_Div = div > 0.02 universe = Q1500US( ) & Solid_PE & Solid_Div #& Not_Bio#& high_dollar_volume # Create filters for our long and short portfolios. longs = NCAV.top(15, mask=universe) pipe = Pipeline(screen=longs) attach_pipeline(pipe, 'Value_Investing')
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 before_trading_start(context, data): """ Called every month before market open. """ context.output = pipeline_output('my_pipeline') # Go long in securities for which the 'longs' value is True context.longs = context.output[context.output['longs']].index.tolist() # Go short in securities for which the 'shorts' value is True. context.shorts = context.output[context.output['shorts']].index.tolist() base_universe = Q1500US() returns_past_12_months = Returns(window_length=252, mask=base_universe) returns_past_2_months = Returns(window_length=42, mask=base_universe) returns_relevant = returns_past_12_months - returns_past_2_months returns_relevant_deciles = returns_relevant.deciles() longs = (returns_relevant_deciles.eq(9)) shorts = (returns_relevant_deciles.eq(0)) WML_returns = context.output['returns_relevant'][ context.output['longs']].sum() - context.output['returns_relevant'][ context.output['shorts']].sum() #std_dev = StdDev(inputs=[WML_returns], window_length=126) std_dev = np.std(WML_returns) if std_dev < 0.12: context.long_leverage, context.short_leverage = 0.5, -0.5 else: context.long_leverage, context.short_leverage = .5 ( .12 / std_dev), -.5 (.12 / std_dev)
def make_pipeline(): sentiment_factor = sentiment.sentiment_signal.last universe = (Q1500US()&sentiment_factor.not_null()) pipe = Pipeline(columns={'sentiment':sentiment_factor, 'longs':(sentiment_factor>=4), 'shorts':(sentiment_factor<=-2)}, screen = universe) return pipe
def make_pipeline(): sentiment_factor=sentiment.sentiment_signal.latest universe = (Q1500US() & sentiment_factor.notnull()) sentiment_quantiles = sentiment_factor.rank(mask=universe, method='average').quantiles(2) pipe = Pipeline(columns={'sentiment':sentiment_factor, 'longs':(sentiment_factor >= 4), 'shorts':(sentiment_factor <= -2), }, screen=universe) return pipe
def make_pipeline(): minprice = USEquityPricing.close.latest > 5 not_announced_acq_target = ~IsAnnouncedAcqTarget() pipe = Pipeline(screen=Q1500US() & minprice & not_announced_acq_target) sectors = Sector() pipe.add(sectors, 'sector') pipe.add(BusinessDaysSincePreviousEarnings(), 'PE') return pipe
def make_pipeline(): close = USEquityPricing.close open_ = USEquityPricing.open high = USEquityPricing.high low = USEquityPricing.low pipe = Pipeline( columns = { 'close': close.latest,}, screen = Q1500US()) return pipe
def make_pipeline(): # Base universe set to the Q500US base_universe = Q1500US() # Factor of yesterday's close price. yesterday_close = USEquityPricing.close.latest pipe = Pipeline(screen=base_universe, columns={ 'close': yesterday_close, }) 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 initialize(context): EntVal = NetCash() schedule_function(rebalance, date_rules.week_start(), time_rules.market_open()) # Create and apply a filter representing the top 500 equities by MarketCap # every day. # Construct an average dollar volume factor NegEnt = EntVal > 1 LongsUniverse = Q1500US()#& NegEnt longs = EntVal.top(25, mask=LongsUniverse) hold = Q1500US() & NegEnt pipe = Pipeline(screen = longs, columns = {'Longs':longs}) attach_pipeline(pipe, 'Value_Investing') pipe2 = Pipeline(screen = hold, columns = None) attach_pipeline(pipe2, 'Hold')
def make_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 Q500US base_universe = Q1500US() # Factor of yesterday's close price. yesterday_close = USEquityPricing.close.latest pipe = Pipeline(screen=base_universe, columns={ 'close': yesterday_close, }) return pipe
def make_pipeline(): sentiment_factor = sentiment.sentiment_signal.latest universe = (Q1500US() & sentiment_factor.notnull()) sentiment_quantiles = sentiment_factor.rank(mask=universe, method="average").quantiles(2) sentiment_pipeline = Pipeline( columns={ "sentiment": sentiment_quantiles, "longs": sentiment_quantiles.eq(0), "shorts": sentiment_quantiles.eq(1), }, screen = universe) return sentiment_pipeline
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 initialize(context): # try many types i.e. # Yes: operation_ratios.revenue_growth.latest, operation_ratios.operation_margin, sentiment testing_factor1 = operation_ratios.operation_margin.latest testing_factor2 = operation_ratios.revenue_growth.latest testing_factor3 = sentiment.sentiment_signal.latest universe = (Q1500US() & testing_factor1.notnull() & testing_factor2.notnull() & testing_factor3.notnull()) testing_factor1 = testing_factor1.rank(mask=universe, method='average') testing_factor2 = testing_factor2.rank(mask=universe, method='average') testing_factor3 = testing_factor3.rank(mask=universe, method='average') combined_alpha = testing_factor1 + testing_factor2 + testing_factor3 # Schedule Tasks # -------------- # Create and register a pipeline computing our combined alpha and a sector # code for every stock in our universe. We'll use these values in our # optimization below. pipe = Pipeline( columns={ 'alpha': combined_alpha, 'sector': Sector(), }, # combined_alpha will be NaN for all stocks not in our universe, # but we also want to make sure that we have a sector code for everything # we trade. screen=combined_alpha.notnull() & Sector().notnull(), ) algo.attach_pipeline(pipe, 'pipe') # Schedule a function, 'do_portfolio_construction', to run once a week # ten minutes after market open. algo.schedule_function( do_portfolio_construction, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open( minutes=MINUTES_AFTER_OPEN_TO_TRADE), half_days=False, )
def make_pipeline(): """ Function to create a pipeline """ pipe = Pipeline() # Base universe set to the Q1500US base_universe = Q1500US() pipe.add(YOY_Slope(), 'YOY-Slope') loser_returns = YOY_Slope.percentile_between(YOY_Slope(),0,10,mask=base_universe) winner_returns = YOY_Slope.percentile_between(YOY_Slope(),90,100,mask=base_universe) pipe.set_screen(loser_returns | winner_returns) pipe.add(loser_returns, 'loser_returns') pipe.add(winner_returns, 'winner_returns') return pipe
def make_pipeline(): # 5-day sentiment moving average factor. sentiment_factor = sentiment.sentiment_signal.latest # Our universe is made up of stocks that have a non-null sentiment signal and are in the Q1500US. universe = (Q1500US() & sentiment_factor.notnull()) # A classifier to separate the stocks into quantiles based on sentiment rank. sentiment_quantiles = sentiment_factor.rank(mask=universe, method='average').quantiles(2) # Go short the stocks in the 0th quantile, and long the stocks in the 2nd quantile. pipe = Pipeline(columns={ 'sentiment': sentiment_quantiles, 'longs': (sentiment_factor >= 4), 'shorts': (sentiment_factor <= 2), }, screen=universe) return pipe
def make_pipeline(): Alpha_factor = operation_ratios.revenue_growth.latest Alpha2 = earnings_ratios.dps_growth.latest Alpha3 = asset_classification.value_score.latest base_universe = get_tradeable_stocks() universe = (Q1500US() & Alpha_factor.notnull() & Alpha2.notnull() & Alpha3.notnull() & base_universe) ##Rankin Alpha_factor = Alpha_factor.rank(mask=universe, method='average') Alpha2 = Alpha2.rank(mask=universe, method='average') Alpha3 = Alpha3.rank(mask=universe, method='average') Alpha_factor = Alpha_factor + Alpha2 + Alpha3 pipe = Pipeline(columns={ 'Alpha_factor': Alpha_factor, 'longs': Alpha_factor > 1500, 'shorts': Alpha_factor < 500 }, screen=universe) return pipe
def make_pipeline(context): NCAV_Rto = NCAV_Ratio() #filters Low_NCAV = NCAV_Rto >= 2 is_profitable = morningstar.income_statement.gross_profit >= 0 universe = Q1500US() & Low_NCAV & is_profitable securities_to_trade = (universe) pipe = Pipeline( columns={ 'NCAV': NCAV_Rto, 'profit': morningstar.income_statement.gross_profit.latest, 'longs': universe, }, screen = securities_to_trade ) return pipe