Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# R code re: CapitalSpecator.com post on random rebalancing dates:
# "Skewed By Randomness"
# www.capitalspectator.com/skewed-by-randomness-testing-arbitrary-rebalancing-dates/#more-6039
# 08 Sep 2015
# By James Picerno
# http://www.capitalspectator.com/
# (c) 2015 by Beta Publishing LLC
# load packages
library(quantmod)
library(tseries)
library(PerformanceAnalytics)
# download prices
symbols <-c("SPY","IJS","EFA","EEM","IEF","LQD","VWEHX","RPIBX","PREMX","QRACX","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 dataset
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")
# calculate weighted total returns for portfolios
# asset weights
w.global = 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
# buy and hold portfolio/no rebalancing
port.global.bh <-Return.portfolio(port.global.returns,
weights=w.global,wealth.index=TRUE,verbose=TRUE)
# year-end rebalanced portfolios
port.global.dec31rebal <-Return.portfolio(port.global.returns,
rebalance_on="years",
weights=w.global,wealth.index=TRUE,verbose=TRUE)
# randomly rebalanced portfolios
# function to generate data for 13 randomly selected rebalancing dates for 1.1.2003-9.4.2015
rand.sample <-function(x) { # x=port.global.returns
dates <-index(x)
dates.sample.1 <-sample(dates,11)
dates.sample.2 <-dates.sample.1[ order(dates.sample.1 )]
dates.sample.2
initial.w <- xts(matrix(c(w.global), nrow=1, ncol=11,byrow=TRUE),index(first(port.global.prices)))
w.global.sample.a <- xts(matrix(c(w.global),nrow=11, ncol=11,byrow=TRUE),dates.sample.2)
w.global.sample <-rbind(initial.w,w.global.sample.a)
a <-Return.portfolio(x,
rebalance_on="daily",
weights=w.global.sample,wealth.index=TRUE,verbose=FALSE)
b <-as.numeric(a)
b
}
# generate multiple return series of random rebalancing dates
rand.sample.data <-replicate(1000,rand.sample(port.global.returns)) # note: this will take several minutes for 1000 portfolios
rand.sample.data.1 <-xts(rand.sample.data,index(port.global.returns)) # add dates
# merge portfolio returns into one dataset for charting, analytics:
# buy & hold, year-end rebalancing, and random rebalancing dates
port.all <-merge(port.global.bh$wealthindex,
port.global.dec31rebal$wealthindex,
rand.sample.data.1)
### END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment