<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/testing-the-hierarchical-risk-parity-algorithm/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://quantstrattrader.wordpress.com/2017/05/26/testing-the-hierarchical-risk-parity-algorithm/"> R – QuantStrat TradeR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This post will be a modified backtest of the <a rel="nofollow" href="https://allocatesmartly.com/adam-butler-gestaltu-adaptive-asset-allocation/" target="_blank">Adaptive Asset Allocation backtest from AllocateSmartly</a>, using the <a rel="nofollow" href="https://quantstrattrader.wordpress.com/2017/05/22/the-marcos-lopez-de-prado-hierarchical-risk-parity-algorithm/" target="_blank">Hierarchical Risk Parity algorithm from last post</a>, because Adam Butler was eager to see my results. On a whole, as Adam Butler had told me he had seen, HRP does not generate outperformance when applied to a small, carefully-constructed, diversified-by-selection universe of asset classes, as opposed to a universe of hundreds or even several thousand assets, where its theoretically superior properties result in it being a superior algorithm. </p>
<p>First off, I would like to thank one Matthew Barry, for helping me modify my HRP algorithm so as to not use the global environment for recursion. You can find his github <a rel="nofollow" href="https://github.com/mrbcuda?tab=following" target="_blank">here</a>.</p>
<p>Here is the modified HRP code.</p>
<pre>
covMat &lt;- read.csv('cov.csv', header = FALSE)
corMat &lt;- read.csv('corMat.csv', header = FALSE)

clustOrder &lt;- hclust(dist(corMat), method = 'single')$order

getIVP &lt;- function(covMat) {
  invDiag &lt;- 1/diag(as.matrix(covMat))
  weights &lt;- invDiag/sum(invDiag)
  return(weights)
}

getClusterVar &lt;- function(covMat, cItems) {
  covMatSlice &lt;- covMat[cItems, cItems]
  weights &lt;- getIVP(covMatSlice)
  cVar &lt;- t(weights) %*% as.matrix(covMatSlice) %*% weights
  return(cVar)
}

getRecBipart &lt;- function(covMat, sortIx) {
  w &lt;- rep(1,ncol(covMat))
  w &lt;- recurFun(w, covMat, sortIx)
  return(w)
}

recurFun &lt;- function(w, covMat, sortIx) {
  subIdx &lt;- 1:trunc(length(sortIx)/2)
  cItems0 &lt;- sortIx[subIdx]
  cItems1 &lt;- sortIx[-subIdx]
  cVar0 &lt;- getClusterVar(covMat, cItems0)
  cVar1 &lt;- getClusterVar(covMat, cItems1)
  alpha &lt;- 1 - cVar0/(cVar0 + cVar1)
  
  # scoping mechanics using w as a free parameter
  w[cItems0] &lt;- w[cItems0] * alpha
  w[cItems1] &lt;- w[cItems1] * (1-alpha)
  
  if(length(cItems0) > 1) {
    w &lt;- recurFun(w, covMat, cItems0)
  }
  if(length(cItems1) > 1) {
    w &lt;- recurFun(w, covMat, cItems1)
  }
  return(w)
}


out &lt;- getRecBipart(covMat, clustOrder)
out
</pre>
<p>With covMat and corMat being from the last post. In fact, this function can be further modified by encapsulating the clustering order within the getRecBipart function, but in the interest of keeping the code as similar to Marcos Lopez de Prado’s code as I could, I’ll leave this here.</p>
<p>Anyhow, the backtest will follow. One thing I will mention is that I’m using <a rel="nofollow" href="https://www.quandl.com/data/EOD-End-of-Day-US-Stock-Prices" target="_blank">Quandl’s EOD database</a>, as Yahoo has really screwed up their financial database (I.E. some sector SPDRs have broken data, dividends not adjusted, etc.). While this database is a $50/month subscription, I believe free users can access it up to 150 times in 60 days, so that should be enough to run backtests from this blog, so long as you save your downloaded time series for later use by using write.zoo.</p>
<p>This code needs the tseries library for the portfolio.optim function for the minimum variance portfolio (<a rel="nofollow" href="https://www.datacamp.com/courses/introduction-to-portfolio-analysis-in-r?tap_a=5644-dce66f&tap_s=10907-287229" target="_blank">Dr. Kris Boudt has a course on this at datacamp</a>), and the other standard packages.</p>
<p>A helper function for this backtest (and really, any other momentum rotation backtest) is the appendMissingAssets function, which simply adds on assets not selected to the final weighting and re-orders the weights by the original ordering.</p>
<pre>
require(tseries)
require(PerformanceAnalytics)
require(quantmod)
require(Quandl)

Quandl.api_key(&quot;YOUR_AUTHENTICATION_HERE&quot;) # not displaying my own api key, sorry <img alt="😦" src="https://i0.wp.com/s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f626.png?w=456&ssl=1" class="wp-smiley" data-recalc-dims="1">

# function to append missing (I.E. assets not selected) asset names and sort into original order
appendMissingAssets &lt;- function(wts, allAssetNames, wtsDate) {
  absentAssets &lt;- allAssetNames[!allAssetNames %in% names(wts)]
  absentWts &lt;- rep(0, length(absentAssets))
  names(absentWts) &lt;- absentAssets
  wts &lt;- c(wts, absentWts)
  wts &lt;- xts(t(wts), order.by=wtsDate)
  wts &lt;- wts[,allAssetNames]
  return(wts)
}

</pre>
<p>Next, we make the call to Quandl to get our data.</p>
<pre>
symbols &lt;- c(&quot;SPY&quot;, &quot;VGK&quot;,	&quot;EWJ&quot;,	&quot;EEM&quot;,	&quot;VNQ&quot;,	&quot;RWX&quot;,	&quot;IEF&quot;,	&quot;TLT&quot;,	&quot;DBC&quot;,	&quot;GLD&quot;)	

rets &lt;- list()
for(i in 1:length(symbols)) {
  
  # quandl command to download from EOD database. Free users should use write.zoo in this loop.
  
  returns &lt;- Return.calculate(Quandl(paste0(&quot;EOD/&quot;, symbols[i]), start_date=&quot;1990-12-31&quot;, type = &quot;xts&quot;)$Adj_Close)
  colnames(returns) &lt;- symbols[i]
  rets[[i]] &lt;- returns
}
rets &lt;- na.omit(do.call(cbind, rets))
</pre>
<p>While Josh Ulrich fixed quantmod to actually get Yahoo data after Yahoo broke the API, the problem is that the Yahoo data is now garbage as well, and I’m not sure how much Josh Ulrich can do about that. I really hope some other provider can step up and provide free, usable EOD data so that I don’t have to worry about readers not being able to replicate the backtest, as my policy for this blog is that readers should be able to replicate the backtests so they don’t just nod and take my word for it. If you are or know of such a provider, please leave a comment so that I can let the blog readers know all about you.</p>
<p>Next, we initialize the settings for the backtest.</p>
<pre>
invVolWts &lt;- list()
minVolWts &lt;- list()
hrpWts &lt;- list()
ep &lt;- endpoints(rets, on =  &quot;months&quot;)
nMonths = 6 # month lookback (6 as per parameters from allocateSmartly)
nVol = 20 # day lookback for volatility (20 ibid)
</pre>
<p>While the AAA backtest actually uses a 126 day lookback instead of a 6 month lookback, as it trades at the end of every month, that’s effectively a 6 month lookback, give or take a few days out of 126, but the code is less complex this way.</p>
<p>Next, we have our actual backtest.</p>
<pre>
for(i in 1:(length(ep)-nMonths)) {
  
  # get returns subset and compute absolute momentum
  retSubset &lt;- rets[c(ep[i]:ep[(i+nMonths)]),]
  retSubset &lt;- retSubset[-1,]
  moms &lt;- Return.cumulative(retSubset)
  
  # select top performing assets and subset returns for them
  highRankAssets &lt;- rank(moms) >= 6 # top 5 assets
  posReturnAssets &lt;- moms > 0 # positive momentum assets
  selectedAssets &lt;- highRankAssets &amp; posReturnAssets # intersection of the above
  selectedSubset &lt;- retSubset[,selectedAssets] # subset returns slice
  
  if(sum(selectedAssets)==0) { # if no qualifying assets, zero weight for period
    
    wts &lt;- xts(t(rep(0, ncol(retSubset))), order.by=last(index(retSubset)))
    colnames(wts) &lt;- colnames(retSubset)
    invVolWts[[i]] &lt;- minVolWts[[i]] &lt;- hrpWts[[i]] &lt;- wts
    
  } else if (sum(selectedAssets)==1) { # if one qualifying asset, invest fully into it
    
    wts &lt;- xts(t(rep(0, ncol(retSubset))), order.by=last(index(retSubset)))
    colnames(wts) &lt;- colnames(retSubset)
    wts[, which(selectedAssets==1)] &lt;- 1
    invVolWts[[i]] &lt;- minVolWts[[i]] &lt;- hrpWts[[i]] &lt;- wts
    
  } else { # otherwise, use weighting algorithms
    
    cors &lt;- cor(selectedSubset) # correlation
    volSubset &lt;- tail(selectedSubset, nVol) # 20 day volatility
    vols &lt;- StdDev(volSubset)
    covs &lt;- t(vols) %*% vols * cors
    
    # minimum volatility using portfolio.optim from tseries
    minVolRets &lt;- t(matrix(rep(1, sum(selectedAssets))))
    minVolWt &lt;- portfolio.optim(x=minVolRets, covmat = covs)$pw
    names(minVolWt) &lt;- colnames(covs)
    minVolWt &lt;- appendMissingAssets(minVolWt, colnames(retSubset), last(index(retSubset)))
    minVolWts[[i]] &lt;- minVolWt
    
    # inverse volatility weights
    invVols &lt;- 1/vols 
    invVolWt &lt;- invVols/sum(invVols) 
    invNames &lt;- colnames(invVolWt)
    invVolWt &lt;- as.numeric(invVolWt) 
    names(invVolWt) &lt;- invNames
    invVolWt &lt;- appendMissingAssets(invVolWt, colnames(retSubset), last(index(retSubset)))
    invVolWts[[i]] &lt;- invVolWt
    
    # hrp weights
    clustOrder &lt;- hclust(dist(cors), method = 'single')$order
    hrpWt &lt;- getRecBipart(covs, clustOrder)
    names(hrpWt) &lt;- colnames(covs)
    hrpWt &lt;- appendMissingAssets(hrpWt, colnames(retSubset), last(index(retSubset)))
    hrpWts[[i]] &lt;- hrpWt
  }
}
</pre>
<p>In a few sentences, this is what happens:</p>
<p>The algorithm takes a subset of the returns (the past six months at every month), and computes absolute momentum. It then ranks the ten absolute momentum calculations, and selects the intersection of the top 5, and those with a return greater than zero (so, a dual momentum calculation).</p>
<p>If no assets qualify, the algorithm invests in nothing. If there’s only one asset that qualifies, the algorithm invests in that one asset. If there are two or more qualifying assets, the algorithm computes a covariance matrix using 20 day volatility multiplied with a 126 day correlation matrix (that is, sd_20′ %*% sd_20 * (elementwise) cor_126. It then computes normalized inverse volatility weights using the volatility from the past 20 days, a minimum variance portfolio with the portfolio.optim function, and lastly, the hierarchical risk parity weights using the HRP code above from Marcos Lopez de Prado’s paper.</p>
<p>Lastly, the program puts together all of the weights, and adds a cash investment for any period without any investments.</p>
<pre>
invVolWts &lt;- round(do.call(rbind, invVolWts), 3) # round for readability
minVolWts &lt;- round(do.call(rbind, minVolWts), 3)
hrpWts &lt;- round(do.call(rbind, hrpWts), 3)

# allocate to cash if no allocation made due to all negative momentum assets
invVolWts$cash &lt;- 0; invVolWts$cash &lt;- 1-rowSums(invVolWts)
hrpWts$cash &lt;- 0; hrpWts$cash &lt;- 1-rowSums(hrpWts)
minVolWts$cash &lt;- 0; minVolWts$cash &lt;- 1-rowSums(minVolWts)

# cash value will be zero
rets$cash &lt;- 0

# compute backtest returns
invVolRets &lt;- Return.portfolio(R = rets, weights = invVolWts)
minVolRets &lt;- Return.portfolio(R = rets, weights = minVolWts)
hrpRets &lt;- Return.portfolio(R = rets, weights = hrpWts)
</pre>
<p>Here are the results:</p>
<pre>
compare &lt;- cbind(invVolRets, minVolRets, hrpRets)
colnames(compare) &lt;- c(&quot;invVol&quot;, &quot;minVol&quot;, &quot;HRP&quot;)
charts.PerformanceSummary(compare)
rbind(table.AnnualizedReturns(compare), maxDrawdown(compare), CalmarRatio(compare))  
</pre>
<pre>
                             invVol    minVol       HRP
Annualized Return         0.0872000 0.0724000 0.0792000
Annualized Std Dev        0.1208000 0.1025000 0.1136000
Annualized Sharpe (Rf=0%) 0.7221000 0.7067000 0.6968000
Worst Drawdown            0.1548801 0.1411368 0.1593287
Calmar Ratio              0.5629882 0.5131956 0.4968234
</pre>
<p><img src="https://i2.wp.com/cdn.discordapp.com/attachments/203286714720976896/317745556682440705/image.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>In short, in the context of a small, carefully-selected and allegedly diversified (I’ll let Adam Butler speak for that one) universe dominated by the process of which assets to invest in as opposed to how much, the theoretical upsides of an algorithm which simultaneously exploits a covariance structure without needing to invert a covariance matrix can be lost.</p>
<p>However, this test (albeit from 2007 onwards, thanks to ETF inception dates combined with lookback burn-in) confirms what Adam Butler himself told me, which is that HRP hasn’t impressed him, and from this backtest, I can see why. However, in the context of dual momentum rank selection, I’m not convinced that any weighting scheme will realize much better performance than any other.</p>
<p>Thanks for reading.</p>
<p>NOTE: I am always interested in networking and hearing about full-time opportunities related to my skill set. My linkedIn profile can be found <a rel="nofollow" href="https://www.linkedin.com/in/ilyakipnis/" target="_blank">here.</a></p>
<p> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/quantstrattrader.wordpress.com/920/" target="_blank"><img border="0" alt="" src="http://feeds.wordpress.com/1.0/comments/quantstrattrader.wordpress.com/920/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://quantstrattrader.wordpress.com/2017/05/26/testing-the-hierarchical-risk-parity-algorithm/"> R – QuantStrat TradeR</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/hTMM320pjlM" height="1"></a></div>