Skip to content

Instantly share code, notes, and snippets.

@jpicerno1
Last active May 19, 2016 16:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jpicerno1/fbc2e589023be56dde42 to your computer and use it in GitHub Desktop.
Save jpicerno1/fbc2e589023be56dde42 to your computer and use it in GitHub Desktop.
# R code re: CapitalSpecator.com post on random rebalancing with weights:
# "Using Random Portfolios To Test Asset Allocation Strategies"
# http://www.capitalspectator.com/using-random-portfolios-to-test-asset-allocation-strategies/
# 06 Oct 2015
# By James Picerno
# http://www.capitalspectator.com/
# (c) 2015 by Beta Publishing LLC
# load packages
library(quantmod)
library(tseries)
library(PerformanceAnalytics)
# 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
port.global.prices <- do.call(merge, lapply(symbols, get))
colnames(port.global.prices) <-c(symbols)
# generate daily return series for funds
port.global.returns <-na.omit(ROC(port.global.prices,1,"discrete"))
colnames(port.global.returns) <-c("spy","ijs","efa","eem","ief","lqd","vwehx","rpibx","premx","qraax","vgsix")
# asset weights for benchmark strategy
w.global.benchmark = c(0.25,0.05,0.20,0.05,0.10,0.10,0.05,0.05,0.05,0.05,0.05) # global aa
# calculate benchmark strategy data
port.global.dec31rebal.benchmark <-Return.portfolio(port.global.returns,
rebalance_on="years",
weights=w.global.benchmark,wealth.index=TRUE,verbose=TRUE)
# function to generate random strategy portfolios
rand.aa <-function(ret,min,max) {
w.global <-prop.table(runif(11,min,max)) # create random weights for assets
port.global.dec31rebal <-Return.portfolio(ret,
rebalance_on="years",
weights=w.global,
wealth.index=TRUE,verbose=TRUE)
return(as.numeric(port.global.dec31rebal$wealthindex))
}
# generate random portfolio performance indexes based on random weights, ranging from 5% to 25%
# warning: processing time could be long, depending on your
# computer's capabilities. For a quick test,
# reduce the replications to, say, 10.
rand.aa.data <-replicate(1000,rand.aa(port.global.returns,0.05,0.25))
rand.aa.data.1 <-xts(rand.aa.data,index(port.global.returns))*100 # create xts file
# benchmark portfolio performance index
port.global.dec31rebal.benchmark$wealthindex.1 <-port.global.dec31rebal.benchmark$wealthindex*100
### END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment