Advertisement
cjc5013

Quality Companies in an Uptrend

Oct 8th, 2019
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.53 KB | None | 0 0
  1. import quantopian.algorithm as algo
  2. from quantopian.pipeline import Pipeline
  3. from quantopian.pipeline.data.builtin import USEquityPricing
  4. from quantopian.pipeline.data import Fundamentals
  5. from quantopian.pipeline.filters import Q500US
  6.  
  7. def initialize(context):
  8.    
  9.     #Set Slippage and attach our algo
  10.     set_slippage(slippage.FixedSlippage(spread = 0.0))
  11.     algo.attach_pipeline(make_pipeline(), 'pipeline')    
  12.    
  13.     #Schedule Functions
  14.     schedule_function(trade, date_rules.month_end() , time_rules.market_close(minutes=30))
  15.     schedule_function(trade_bonds, date_rules.month_end(), time_rules.market_close(minutes=20))
  16.    
  17.     #This is for the trend following filter
  18.     context.spy = sid(8554)
  19.     context.TF_filter = False
  20.     context.TF_lookback = 126
  21.    
  22.     #Set number of securities to buy and bonds fund (when we are out of stocks)
  23.     context.Target_securities_to_buy = 10.0
  24.     context.bonds = sid(23911)
  25.    
  26.    
  27.     context.top_n_roe_to_buy = 50 #First sort by ROE
  28.     context.relative_momentum_lookback = 126 #Momentum lookback
  29.     context.top_n_relative_momentum_to_buy = 10 #Number to buy
  30.    
  31.  
  32. def make_pipeline():
  33.  
  34.     # Base universe set to the Q500US
  35.     universe = Q500US()
  36.  
  37.     roe = Fundamentals.roe.latest
  38.  
  39.     pipe = Pipeline(columns={'roe': roe},screen=universe)
  40.     return pipe
  41.  
  42. def before_trading_start(context, data):
  43.    
  44.     context.output = algo.pipeline_output('pipeline')
  45.     context.security_list = context.output.index
  46.        
  47. def trade(context, data):
  48.  
  49.     ############Trend Following Regime Filter############
  50.     TF_hist = data.history(context.spy , "close", 140, "1d")
  51.     TF_check = TF_hist.pct_change(context.TF_lookback).iloc[-1]
  52.  
  53.     if TF_check > 0.0:
  54.         context.TF_filter = True
  55.     else:
  56.         context.TF_filter = False
  57.     ############Trend Following Regime Filter End############
  58.    
  59.     #DataFrame of Prices for our 500 stocks
  60.     prices = data.history(context.security_list,"close", 180, "1d")      
  61.     #DF here is the output of our pipeline, contains 500 rows (for 500 stocks) and one column - ROE
  62.     df = context.output  
  63.    
  64.     #Grab top 50 stocks with best ROE
  65.     top_n_roe = df['roe'].nlargest(context.top_n_roe_to_buy)
  66.     #Calculate the momentum of our top ROE stocks  
  67.     quality_momentum = prices[top_n_roe.index].pct_change(context.relative_momentum_lookback).iloc[-1]
  68.     #Grab stocks with best momentum    
  69.     top_n_by_momentum = quality_momentum.nlargest(context.top_n_relative_momentum_to_buy)
  70.            
  71.     for x in context.portfolio.positions:
  72.         if (x.sid == context.bonds):
  73.             pass
  74.         elif x not in top_n_by_momentum:
  75.             order_target_percent(x, 0)
  76.             print('GETTING OUT OF',x)
  77.    
  78.     for x in top_n_by_momentum.index:
  79.         if x not in context.portfolio.positions and context.TF_filter==True:
  80.             order_target_percent(x, (1.0 / context.Target_securities_to_buy))
  81.             print('GETTING IN',x)
  82.            
  83.  
  84.            
  85.            
  86. def trade_bonds(context , data):
  87.     amount_of_current_positions=0
  88.     if context.portfolio.positions[context.bonds].amount == 0:
  89.         amount_of_current_positions = len(context.portfolio.positions)
  90.     if context.portfolio.positions[context.bonds].amount > 0:
  91.         amount_of_current_positions = len(context.portfolio.positions) - 1
  92.     percent_bonds_to_buy = (context.Target_securities_to_buy - amount_of_current_positions) * (1.0 / context.Target_securities_to_buy)
  93.     order_target_percent(context.bonds , percent_bonds_to_buy)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement