Skip to content

Instantly share code, notes, and snippets.

@jpicerno1
Last active January 12, 2016 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpicerno1/269da1b1f34679f0e433 to your computer and use it in GitHub Desktop.
Save jpicerno1/269da1b1f34679f0e433 to your computer and use it in GitHub Desktop.
# R code re: CapitalSpecator.com post on risk-contribution analysis:
# "Portfolio Analysis in R: Part VI | Risk-Contribution Analysis"
# http://www.capitalspectator.com/portfolio-analysis-in-r-part-vi-risk-contribution-analysis/
# 12 Jan 2016
# By James Picerno
# http://www.capitalspectator.com/
# (c) 2016 by Beta Publishing LLC
library(quantmod)
library(tseries)
library(PerformanceAnalytics)
library(xts)
library(timeSeries)
library(TTR)
# 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]
assign(symbol,x)
}
# merge price histories into one data set
prices <- do.call(merge, 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
port.sd <-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