Skip to content

Instantly share code, notes, and snippets.

@kaizenlabs
Last active March 2, 2021 18:20
Show Gist options
  • Save kaizenlabs/63c10507e4d8b7f7adf5b4cdce5a9edd to your computer and use it in GitHub Desktop.
Save kaizenlabs/63c10507e4d8b7f7adf5b4cdce5a9edd to your computer and use it in GitHub Desktop.
Ray Dalio's All Weather Strategy - Algorithm Quantconnect
from datetime import datetime
from collections import *
### <summary>
### All Weather Strategy (Ray Dalio) w/ annual rebalance. Run on QuantConnect www.quantconnect.com
### #http://www.lazyportfolioetf.com/allocation/ray-dalio-all-weather/
### </summary>>
class AllWeatherStrategy(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2011, 1, 1)
self.SetEndDate(2019, 1, 31)
self.SetCash(100000)
self.monthCounter = 0
# Country index ETFs according to https://seekingalpha.com/etfs-and-funds/etf-tables/countries
self.etfs = [
(self.AddEquity('SPY', Resolution.Daily).Symbol,0.0),
(self.AddEquity('VTI', Resolution.Daily).Symbol,0.3), #Vanguard Total Stock Market ETF
(self.AddEquity('TLT', Resolution.Daily).Symbol,0.4), # iShares 20+ Year Treasury ETF (TLT)
(self.AddEquity('IEF', Resolution.Daily).Symbol,0.15), #iShares 7 – 10 Year Treasury ETF (IEF)
(self.AddEquity('GLD', Resolution.Daily).Symbol,0.075), #SPDR Gold Shares ETF (GLD), #SPDR Gold Shares (GLD)
(self.AddEquity('DBC', Resolution.Daily).Symbol,0.075) # PowerShares DB Commodity Index Tracking Fund (DBC)"
]
self.Schedule.On(self.DateRules.MonthStart(self.etfs[0][0]), self.TimeRules.AfterMarketOpen(self.etfs[0][0]), self.Rebalance)
self.leverage = 1.5
self.monthCounter = 1
# Set Benchmark
self.SetBenchmark("SPY")
# Variable to hold the last calculated benchmark value
self.lastBenchmarkValue = None
# Our inital benchmark value scaled to match our portfolio
self.BenchmarkPerformance = self.Portfolio.TotalPortfolioValue
def OnData(self, data):
benchmark = self.Securities["SPY"].Close
# Calculate the performance of our benchmark and update our benchmark value for plotting
if self.lastBenchmarkValue is not None:
self.BenchmarkPerformance = self.BenchmarkPerformance * (benchmark/self.lastBenchmarkValue)
# store today's benchmark close price for use tomorrow
self.lastBenchmarkValue = benchmark
# make our plots
self.Plot("Strategy vs Benchmark", "Portfolio Value", self.Portfolio.TotalPortfolioValue)
self.Plot("Strategy vs Benchmark", "Benchmark", self.BenchmarkPerformance)
def Rebalance(self):
if self.monthCounter is 12:
self.SetHoldings([PortfolioTarget(etf,target*self.leverage) for etf,target in self.etfs])
self.monthCounter = 1
else:
self.monthCounter = self.monthCounter+1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment