Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.07 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.filters import Q500US
  5.  
  6.  
  7. def initialize(context):
  8. #Schedule our rebalance function to run once a month
  9. schedule_function(rebalance , date_rules.month_end(), time_rules.market_close(minutes=10))
  10. schedule_function(stops, date_rules.every_day(), time_rules.market_close(minutes=14))
  11.  
  12. #This code simply "attaches" our pipeline to this algo. This code never changes
  13. algo.attach_pipeline(make_pipeline(), 'pipeline')
  14.  
  15. #Grab SPY for the Trend Following Filter
  16. context.spy = sid(8554)
  17.  
  18. # Specify percentage based intial protective stop and trailing stop (TS) levels
  19.  
  20. context.IPS = 0.8
  21. context.TS = 0.8
  22.  
  23. # Dictionary to hold trailing stop prices {stock1:TS1, etc...}
  24. context.TS_prices={}
  25.  
  26.  
  27. def make_pipeline():
  28.  
  29. # Base universe set to the Q500US
  30. universe = Q500US()
  31.  
  32. # This is pipeline code
  33. # All we are doing is making an object, 'pipe' containing the current 500 most liquid US stocks
  34. pipe = Pipeline(screen=universe)
  35. return pipe
  36.  
  37. def before_trading_start(context, data):
  38.  
  39. # Called every day before market open, this grabs the output from our function "make_pipeline"
  40. context.output = algo.pipeline_output('pipeline')
  41.  
  42. # Here we grab in "index" of our pipeline
  43. # This makes a list of securities "context.security_list" containing 500 stocks
  44. context.security_list = context.output.index
  45.  
  46. def rebalance(context, data):
  47. #This code is for our Trend Following Regime Filter:
  48. #We get the history for SPY, current price for SPY and calculates the moving average
  49. spy_history = data.history(context.spy,"close", 200, "1d")
  50. spy_MA = spy_history.mean()
  51. spy_current = data.current(context.spy,'price')
  52.  
  53. #This code grabs the pricing history for all 500 stocks in our universe
  54. #This DataFrame, "history", contains 253 rows (days) and 500 columns (one for each stock)
  55. history = data.history(context.security_list,"close", 253, "1d")
  56.  
  57. #This grabs the current momentum for each stock
  58. #Default is 105 days (5 months) lookback
  59. #We use .iloc[-1] to get the last value (most recent momentum measure)
  60. current_momentum = history.pct_change(105).iloc[-1]
  61.  
  62. #Here we use "nlargest" to grab the 20 stocks with the best momentum
  63. top_n_stock = current_momentum.nlargest(20)
  64.  
  65. #Loop through all stocks in our portfolio, selling any that arent still in the top 20 based on momentum
  66. for security in context.portfolio.positions:
  67. if security not in top_n_stock:
  68. order_target_percent(security, 0.0)
  69.  
  70. #Here we buy new stocks
  71. #We first check if the current price of SPY is abve its 200 day MA
  72. #We then loop through our "top_n_stock" list (20 with best momentum) and buy each we 5% of our portfolio
  73. if spy_current > spy_MA:
  74. for x in top_n_stock.index:
  75. if x not in context.portfolio.positions:
  76. order_target_percent(x , 0.05)
  77.  
  78. def stops(context, data):
  79.  
  80. for stock in context.portfolio.positions:
  81. current_price = data.current(stock, 'price')
  82. current_position = context.portfolio.positions[stock].amount
  83. cost_basis = context.portfolio.positions[stock].cost_basis
  84.  
  85. # initial protective stop (IPS)
  86. IPS_price = context.IPS * cost_basis
  87.  
  88. # trailing stop (TS)
  89. context.TS_price[stock] = max(context.TS_prices[stock] if stock in context.TS_prices
  90. else 0,context.TS * current_price)
  91.  
  92. # Apply stops
  93. if (current_position > 0) and ((current_price < context.TS_prices[stock]) or (current_price < IPS_price)):
  94. order_target_percent(stock, 0)
  95. del context.TS_prices[stock]
  96. print('Stopped out of {} at price = {}, cost_basis = {}'.format(stock, round(current_price,4), round(cost_basis,4)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement