rcumsumzigzag

cumulative sum to zigzag indicator


The following code provides example data:

library(TTR)
set.seed(15)
r <- rnorm(1000, 0, .01)
P_1 <- 100
P <- P_1*cumprod(1+r)
zz <- ZigZag(P, change = 5, percent = TRUE)
set.seed(15)
volume <- round(runif(1000, 50, 550), digits = 0)
data <- as.data.frame(cbind(P, zz, volume))
plot(P, type = "l")
lines(zz, col = "red")

in the end I would like to create cumulative sum of volume in new column, where reset happens when zigzag line (zz) changes direction. I have tried to play with s <- sign(diff(data$zz, lag = 1)), which would show those turning points, but haven't been able to use cumsum with it.


Solution

  • Here is a solution that uses dplyr:

    library(dplyr)
    
    data %>%
      mutate(
        zz_up = (zz - lag(zz) > 0),
        zz_switch = zz_up != lag(zz_up),
        zz_switch = ifelse(is.na(zz_switch), FALSE, zz_switch),
        group = cumsum(zz_switch)
        ) %>%
      group_by(group) %>%
      mutate(cum_volume = cumsum(volume))