【问题标题】:cumulative sum to zigzag indicator之字形指标的累积总和
【发布时间】:2016-02-17 14:03:44
【问题描述】:

以下代码提供了示例数据:

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")

最后我想在新列中创建体积的累积总和,当锯齿线 (zz) 改变方向时会发生重置。我尝试过使用s &lt;- sign(diff(data$zz, lag = 1)),它会显示那些转折点,但无法使用 cumsum。

【问题讨论】:

  • 为糟糕的英语道歉,不是我的母语。感谢编辑。

标签: r cumsum zigzag


【解决方案1】:

这是一个使用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)) 

【讨论】:

    【解决方案2】:

    尝试RcppRoll:

    代码

    Vectorize(require)(package = c("magrittr", "dplyr", "RcppRoll"),
                                   char = TRUE)
    
    data %<>%
      # Create difference for ZigZag
      mutate(diffZZ = c(0,diff(zz))) %>% 
      # Use it as a group
      group_by(diffZZ) %>% 
      # Use RcppRoll to compute that sum
      mutate(sumVolByDiff = roll_sum(x = volume, n = 2, fill = NA)) %>% 
      # Clean / not important
      ungroup()
    

    预览

    > head(data)
    Source: local data frame [6 x 5]
    
             P       zz volume   diffZZ sumVolByDiff
         (dbl)    (dbl)  (dbl)    (dbl)        (dbl)
    1 100.2588 100.2588    351 0.000000           NA
    2 102.0947 100.5596    148 0.300785          523
    3 101.7480 100.8604    533 0.300785         1077
    4 102.6608 101.1612    375 0.300785          609
    5 103.1618 101.4620    234 0.300785          692
    6 101.8668 101.7627    544 0.300785          938
    

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 2021-01-18
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 2015-09-11
      • 2018-07-02
      • 1970-01-01
      相关资源
      最近更新 更多