Skip to content

Instantly share code, notes, and snippets.

@theHausdorffMetric
Created March 4, 2012 19:57
Show Gist options
  • Save theHausdorffMetric/1974563 to your computer and use it in GitHub Desktop.
Save theHausdorffMetric/1974563 to your computer and use it in GitHub Desktop.
An R Example to create a boxplot of returns of a financial series depending on weekdays
require(quantmod)
require(ggplot2)
require(reshape2)
# The standard definitions of boxplots are non-obvious to interpret for non-statisticians.
# A "the box is fifty percent, the line 95% and there you have 5% outlier points" is
# typically more easily swallowed by practitioners.
# I therefore define two functions which will change the boxplot appearance below.
myBoxPlotSummary <- function(x) {
r <- quantile(x, probs = c(0.025, 0.25, 0.5, 0.75, 0.975),na.rm=TRUE)
names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
r
}
myBoxPlotOutliers <- function(x) {
tmp<-quantile(x,probs=c(.025,.975),na.rm=TRUE)
subset(x, x < tmp[1] | tmp[2] < x)
}
# Download some Data, e.g. the CBOE VIX
getSymbols("^VIX",src="yahoo")
# Make a factor depending on the day of week. We will use this to segement data according to days of the week.
wd<-factor(.indexwday(VIX),levels=1:5,labels=c("Mon","Tue","Wed","Thu","Fri"),ordered=TRUE)
# Note here that I do not use the weekdays function, because this will be locale dependent and lead
# to an unwanted sorting of the days in the boxplot
wd<-factor(.indexwday(VIX),levels=1:5,labels=c("Mon","Tue","Wed","Thu","Fri"),ordered=TRUE)
# wd<-factor(.indexwday(VIX),levels=1:7,labels=c("Mon","Tue","Wed","Thu","Fri","Sat","Sun"),ordered=TRUE)
# a dataframe with the factor and the daily returns from close to close
tail(mydf<-data.frame(wd=wd,ROC(Cl(VIX))))
mdat<- melt(mydf)
# plot the boxplots with own summary functions and outliers
ggplot(mdat,aes(wd,value)) +
opts(title = "Daily returns of the VIX") + xlab("") + ylab("% per day") +
stat_summary(fun.data=myBoxPlotSummary, geom="boxplot") +
stat_summary(fun.y = myBoxPlotOutliers, geom="point")
#kruskal.test(x=mydf[,2],g=mydf[,1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment