Skip to content

Instantly share code, notes, and snippets.

Last active January 12, 2016 15:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jpicerno1/269da1b1f34679f0e433 to your computer and use it in GitHub Desktop.
# R code re: post on risk-contribution analysis:
# "Portfolio Analysis in R: Part VI | Risk-Contribution Analysis"
# 12 Jan 2016
# By James Picerno
# (c) 2016 by Beta Publishing LLC
# download fund prices
symbols <-c("SPY","IJS","EFA","EEM","IEF","LQD","VWEHX","RPIBX","PREMX","QRAAX","VGSIX")
getSymbols(symbols, src='yahoo', from='2003-12-31')
for(symbol in symbols) {
x <- get(symbol)
indexFormat(x) <- '%Y-%m-%d'
colnames(x) <- gsub("x",symbol,colnames(x))
x <- x[,6]
# merge price histories into one data set
prices <-, lapply(symbols, get))
colnames(prices) <-c(symbols)
# generate daily return series for funds
returns <-na.omit(ROC(prices,1,"discrete"))
colnames(prices) <-c("spy","ijs","efa","eem","ief","lqd","vwehx","rpibx","premx","qraax","vgsix")
# set asset allocation weights
w = c(0.25,0.05,0.20,0.05,0.10,0.10,0.05,0.05,0.05,0.05,0.05)
# calculate risk contribution to portfolio with function from PortfolioAnalytics package <-StdDev(returns, weights = w, portfolio_method = "component")
### END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment