Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Created August 15, 2012 18:50
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 timelyportfolio/3362522 to your computer and use it in GitHub Desktop.
Save timelyportfolio/3362522 to your computer and use it in GitHub Desktop.
plot.xts horizon plot example
#plot.xts with horizons
require(PerformanceAnalytics)
horizon.panel <- function(index,x,...) {
#get some decent colors from RColorBrewer
#we will use colors on the edges so 2:4 for red and 7:9 for blue
require(RColorBrewer)
col.brew <- brewer.pal(name="RdBu",n=10)
#ease this reference later
n=NROW(x)
#clean up NA
x[which(is.na(x),arr.ind=TRUE)[,1],
unique(which(is.na(x),arr.ind=TRUE)[,2])] <- 0
#get number of bands for the loop
#limit to 4
nbands = min(4,ceiling(max(abs(coredata(x)))/horizonscale))
#plot(index(x), abs(coredata(x)), type="n", bty="n", las=1, yaxt="n", xaxt="n", xlab=NA, ylab=NA, ylim=c(0,horizonscale))
#thanks to helpful reader A. Zolot
#par(usr=c(index(x)[1],index(x)[n],0,horizonscale),mar=c(2,1,1,1)) # 0-margines
for (i in 1:nbands) {
#draw positive
polygon(
c(index[1], index, index[n]),
c(origin, coredata(x) - (i-1) * horizonscale,origin),
col=col.brew[length(col.brew)-nbands+i-1],
border=NA
)
#draw negative
polygon(
c(index[1], index, index[n]),
c(origin, -coredata(x) - (i-1) * horizonscale,origin),
col=col.brew[nbands-i+1],
border=NA
)
}
#delete trash drawn below origin that we keep so no overlap between positive and negative
polygon(
c(index[1], index, index[n]),
c(origin, -ifelse(coredata(x)==origin,horizonscale*5,abs(coredata(x))),origin),
col=par("bg"),
border=NA
)
#draw a line at the origin
abline(h=origin,col="black")
#labelling just for example purposes
#do label at top left and top right
text(x=index[1], y=horizonscale, colnames(x), adj=c(0,1))
text(x=index[n], y=horizonscale, colnames(x), adj=c(1,1))
#do label at center right for ease of reference
#text(x=index[n], y=horizonscale/2, colnames(x), pos=2)
#do label at bottom center
#text(x=index[n/2], y=origin, colnames(x), pos=3)
#do not need this anymore since plot.xts handles
#axis.Date(side=1,x=index(x),pos=0)
}
data(edhec)
#set these up for global access since I do not see how to pass into panel function
origin = 0
horizonscale = 0.1
#get 12 month rolling return of edhec indexes
roc <- as.xts(apply(cumprod(edhec+1),MARGIN=2,ROC,n=12,type="discrete"),order.by=index(edhec))
plot.xts(roc,layout.screens = 1:NCOL(roc),
ylim=c(origin,horizonscale),
panel=horizon.panel,bty="n",
auto.grid=FALSE,
yax.loc="none",
yaxt="n", #, xaxt="n")
main="Horizon Plot of EDHEC Indexes 12-month Rolling Return")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment