Advertisement
cjc5013

Dual Moving Average Template

Sep 26th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. # Simple Moving Average Trend Following Strategy using two moving averages
  2. # This strategy goes long our "risk asset" if the short MA is above the long MA
  3. # We will exit our "risk asset" and go long our "safe asset" if the short MA is below the long MA
  4.  
  5.  
  6. def initialize(context):      
  7.     #Schedule our "trade" function, to run everyday 5 minutes before the close:
  8.     schedule_function(trade, date_rules.every_day(), time_rules.market_close(minutes=5))
  9.    
  10.     #Set up our assets.  Ill make the "risk asset" = SPY and the "safe asset" = AGG
  11.     #Feel free to change these to your liking
  12.     context.risk_asset = sid(8554) #SPY
  13.     context.safe_asset = sid(25485) #AGG
  14.  
  15.     #Lets set up our moving average lengths:
  16.     #Feel free to change these to your liking
  17.     context.short_ma_length = 20
  18.     context.long_ma_length = 100
  19.    
  20. def trade(context, data):
  21.    
  22.     #Lets grab some historical data for our risk asset
  23.     history = data.history(context.risk_asset, 'close', 200, '1d')
  24.        
  25.     #Calculate our moving averages:
  26.     #Notice we are slicing our rolling historical data we just grabbed:
  27.     SMA_short = history[-context.short_ma_length:].mean()
  28.     SMA_long = history[-context.long_ma_length:].mean()
  29.    
  30.     if SMA_short > SMA_long:
  31.         order_target_percent(context.risk_asset, 1.0)
  32.         order_target_percent(context.safe_asset, 0.0)
  33.         print('We are long our risk asset')
  34.        
  35.     else:
  36.         order_target_percent(context.risk_asset, 0.0)
  37.         order_target_percent(context.safe_asset, 1.0)
  38.         print('We are long our safe asset')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement