plot.zoo-用不同的颜色绘制一张图

时间:2018-07-31 08:52:48

标签: r time-series finance zoo quantitative-finance

我想绘制一个具有不同颜色的资产在更不稳定的时期内的时间序列收益图。我希望将波动性集群标记为红色,将其余的较平静时期标记为蓝色。我已附上我想要实现的图像。

我的代码:

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

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

2 个答案:

答案 0 :(得分:1)

如果cond是一个逻辑向量,且您的情况在更不稳定的时期内发生(例如cond <- abs(Returns > 0.05)),则可以使用以下方式:

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

对于多个红色周期,可能会出现从一个到另一个的行。在下面的示例中,我解决了这个问题:

# 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

答案 1 :(得分:0)

胡安的答案有效。这是我发现也可以使用的另一种方法

ling_segs <-ifelse(djr <= -0.02 | djr >= 0.02, cbind(djr), NA)

line_segs <- na.omit(ling_segs)

plot.zoo(cbind(djr, line_segs),
     plot.type = "single", 
     xlab = "Date", ylab = "Returns",
     col = c("blue", "red"))
相关问题