Created
May 24, 2012 15:17
-
-
Save timelyportfolio/2782168 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require(reshape2) | |
require(dprint) | |
require(quantmod) | |
require(PerformanceAnalytics) | |
#get manager data set for some date to play with | |
data(managers) | |
#get xts in df form so that we can melt with the reshape package | |
#will use just manager 1, sp500, and 10y treasury | |
managers <- managers[,c(1,8,9)] | |
#add 0 at beginning so cumulative returns start at 1 | |
#also cumulative will match up datewise with returns | |
managers <- as.xts(rbind(rep(0,NCOL(managers)),coredata(managers)), | |
order.by=c(as.Date(format(index(managers)[1],"%Y-%m-01"))-1,index(managers))) | |
managers.df <- as.data.frame(cbind(index(managers),coredata(managers)),stringsAsFactors=FALSE) | |
#melt data which puts in a form that lattice and ggplot enjoy | |
managers.melt <- melt(managers.df,id.vars=1) | |
colnames(managers.melt) <- c("date","account","return") | |
managers.melt[,1] <- as.Date(managers.melt[,1]) | |
#get cumulative returns starting at 1 | |
managers.cumul <- as.xts( | |
apply(managers+1,MARGIN=2,FUN=cumprod), | |
#add end of first month to accommodate the 1 that we add | |
order.by=index(managers)) | |
#get returns by quarter | |
managers.qtr <- na.omit(ROC(managers.cumul[endpoints(managers.cumul,"quarters")],n=1,type="discrete")) | |
#get a column for year and a column for the quarter | |
percent <- function(x, digits = 2, format = "f", ...) | |
{ | |
paste(formatC(100 * x, format = format, digits = digits, ...), "%", sep = "") | |
} | |
managers.qtr.table <- as.data.frame(cbind(format(index(managers.qtr),"%Y"), | |
paste("Quarter ",as.numeric(format(index(managers.qtr),"%m"))/3,sep=""), | |
apply(round(coredata(managers.qtr),4),MARGIN=2,percent)),stringsAsFactors=FALSE) | |
colnames(managers.qtr.table)[1:2] <- c("year","quarter") | |
#print pretty table | |
dev.off() | |
dprint(year+quarter~., data=managers.qtr.table, | |
pg.dim=c(8,10),fit=TRUE,margins=c(0,1,0,1),main="Quarterly Returns") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment