Search code examples
rtime-seriesfinancezooquantitative-finance

plot.zoo - Plot one graph with different colors


I want to plot a graph of a time series return on an asset with different colors for more volatile periods. I want the volatility clusters to be marked in red with the rest of the more calm periods marked in blue. I've attached an image of what I want to achieve.

My code:

plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "blue")

Daily return series (2 typical volatility clusters marked in red)


Solution

  • If cond is a logical vector with your condition for more volatile periods (for example cond <- abs(Returns > 0.05)), you can use something like:

    plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "blue")
    points(index(djr)[cond], djr[cond], type = "l", col = "red")
    

    For multiple periods in red, lines may appear that go from one to the other. In the following example I solve this problem:

    # Reproducible example:
    library(zoo)
    djr <- as.zoo(EuStockMarkets[, "DAX"])
    djr <- (djr - mean(djr))/sd(djr)
    
    cond <- abs(as.numeric(djr)) > 0.75
    rlec <- rle(cond)
    
    plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "white")
    ind <- 1
    for(i in 1:length(rlec$values)) {
      points(index(djr)[ind:(ind + rlec$lengths[i] - 1)], 
             djr[ind:(ind + rlec$lengths[i] - 1)], 
             type = "l", col = c("blue", "red")[rlec$values[i] + 1])
      ind <- ind + rlec$lengths[i]
    }
    

    enter image description here