Displaying german stock performance with R using ggplot2

I cannot follow stock market developments daily, so I was looking for a quick overview of what had happened in the last week. What would be of interest for me is  “How did German stocks perform over the last 5 days, compared to the last 20 trading days and the last 250 trading days”.

R in combination with the right packages delivers a quick answer.

The result is a picture like this:

Performance Plot

Plot of German stock performance

Values in the “upper right” quadrant stand for shares, that did show positive performance during the last 5 and 20 trading days. The color displays the performance over the last 250 trading days.

We can see that the last week was rather positive, all of the shares except one have positive performance.  Also the last 20 days were profitable for most shares.

However, it can be seen that a lot of stocks did suffer during the last year (i.e. 250 trading days), which van bee seen from the colors – most of them are red. Most notably CBK.DE (Commerzbank) did nearly loose all of its value…

You can find the R code here:


#get list of Symbols for DAX-values
getSymbols(l, from="2010-09-01")
l[1] <- "GDAXI"

# Function to extract "adjusted prices" and build dataframe: Thanks to Zach Mayer of moderntoolmaking.blogspot.com
symbolFrame <- function(symbolList) {
Data <- data.frame(NULL)
for (S in symbolList) {
Data <- cbind(Data,Ad(get(S)))
colnames(Data) <- symbolList


Data <- symbolFrame(l[-1]) # build a dataframe without DAX istelf
Data <- cbind(Ad(GDAXI), Data) # add DAX
colnames(Data)[1] <- "DAX"
tail(Data,2) #just to check - often Yahoo is not up to date and there are NAs in the last row
#Data <- window(Data, start=start(Data), end=end(Data)-1) # code to delete last row...

Return.calculate(Data, method="simple") -> Data.r #calculates the returns (simple)
Data.r[is.na(Data.r)] <- 0 

#builds frames for the respective perfromances on short, mid and long term
mid.perf <- as.data.frame(coredata(tail(cumsum(tail(Data.r,20)),1)))
short.perf <- as.data.frame(coredata(tail(cumsum(tail(Data.r,5)),1)))
long.perf <- as.data.frame(coredata(tail(cumsum(tail(Data.r,250)),1)))

per.df <- data.frame(cbind(t(short.perf), t(mid.perf), t(long.perf)))

colnames(per.df) <- c("short", "mid", "long")
row.names(per.df)[1] <- "DAX"
chart_title <- paste("Performance Comparison DAX values\n(latest data close of ",end(Data),")")
ggplot(data=per.df, aes(short, mid, label=rownames(per.df))) + geom_point(aes(color=long), size=4) +
  geom_text(hjust=0, vjust=0,size=4) + geom_vline(xintercept=0) + geom_hline(yintercept=0) +
  scale_colour_gradient2(low="red", high="green", "250days\nPerformance") +
  scale_y_continuous("Mid Performance: 20days", formatter="percent") +
  scale_x_continuous("Short Performance: 5days", formatter="percent") +
  opts(title = chart_title)

Created by Pretty R at inside-R.org