Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Simple Moving Average Trend Following Strategy using two moving averages
- # This strategy goes long our "risk asset" if the short MA is above the long MA
- # We will exit our "risk asset" and go long our "safe asset" if the short MA is below the long MA
- def initialize(context):
- #Schedule our "trade" function, to run everyday 5 minutes before the close:
- schedule_function(trade, date_rules.every_day(), time_rules.market_close(minutes=5))
- #Set up our assets. Ill make the "risk asset" = SPY and the "safe asset" = AGG
- #Feel free to change these to your liking
- context.risk_asset = sid(8554) #SPY
- context.safe_asset = sid(25485) #AGG
- #Lets set up our moving average lengths:
- #Feel free to change these to your liking
- context.short_ma_length = 20
- context.long_ma_length = 100
- def trade(context, data):
- #Lets grab some historical data for our risk asset
- history = data.history(context.risk_asset, 'close', 200, '1d')
- #Calculate our moving averages:
- #Notice we are slicing our rolling historical data we just grabbed:
- SMA_short = history[-context.short_ma_length:].mean()
- SMA_long = history[-context.long_ma_length:].mean()
- if SMA_short > SMA_long:
- order_target_percent(context.risk_asset, 1.0)
- order_target_percent(context.safe_asset, 0.0)
- print('We are long our risk asset')
- else:
- order_target_percent(context.risk_asset, 0.0)
- order_target_percent(context.safe_asset, 1.0)
- print('We are long our safe asset')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement