代码之家  ›  专栏  ›  技术社区  ›  MichaelE

如何使用带(n-1)标准差的bbands函数?

  •  1
  • MichaelE  · 技术社区  · 7 年前

    给定来自ttr包的bbands函数的fowling数据和结果:

    d1= 1:20
    d1
     [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
    
    BBands(t1)[20,]
            dn       mavg         up       pctB 
    -1.0325626 10.5000000 22.0325626  0.9118772 
    

    现在是使用sd功能的手动波段。

    > c(mean(t1)-sd(t1)*2,mean(t1)+sd(t1)*2)
    [1] -1.33216 22.33216
    

    区别在于标准差采用(n-1)法,而BBands采用N法。

    问题是如何让bbands函数使用(n-1)方法。 文件 here 不列出此类选项。

    如果不可能是bbands,有人能帮我做一个克隆bbands的函数,但是用(n-1)作为标准差。

    1 回复  |  直到 7 年前
        1
  •  0
  •   mischva11 Jochen Ritzel    7 年前

    函数

    只要编写函数,就可以得到简单的函数代码 BBands (不带括号):

    function (HLC, n = 20, maType, sd = 2, ...) 
    {
        HLC <- try.xts(HLC, error = as.matrix)
        if (NCOL(HLC) == 3) {
            if (is.xts(HLC)) {
                xa <- xcoredata(HLC)
                HLC <- xts(apply(HLC, 1, mean), index(HLC))
                xcoredata(HLC) <- xa
            }
            else {
                HLC <- apply(HLC, 1, mean)
            }
        }
        else if (NCOL(HLC) != 1) {
            stop("Price series must be either High-Low-Close, or Close/univariate.")
        }
        maArgs <- list(n = n, ...)
        if (missing(maType)) {
            maType <- "SMA"
        }
        mavg <- do.call(maType, c(list(HLC), maArgs))
        sdev <- runSD(HLC, n, sample = FALSE)
        up <- mavg + sd * sdev
        dn <- mavg - sd * sdev
        pctB <- (HLC - dn)/(up - dn)
        res <- cbind(dn, mavg, up, pctB)
        colnames(res) <- c("dn", "mavg", "up", "pctB")
        reclass(res, HLC)
    }
    

    让我们改变函数

    有个变量 sdev 有了这个功能 runSD() ,我将其改为函数sdev<-as.vector(rollappyr(hlc,n,sd))`,这样我们得到一个向量输出。让我们调用新函数bbands:

    BBands_2 <- function (HLC, n = 20, maType, sd = 2, ...)
    
    {
      HLC <- try.xts(HLC, error = as.matrix)
      if (NCOL(HLC) == 3) {
        if (is.xts(HLC)) {
          xa <- xcoredata(HLC)
          HLC <- xts(apply(HLC, 1, mean), index(HLC))
          xcoredata(HLC) <- xa
        }
        else {
          HLC <- apply(HLC, 1, mean)
        }
      }
      else if (NCOL(HLC) != 1) {
        stop("Price series must be either High-Low-Close, or Close/univariate.")
      }
      maArgs <- list(n = n, ...)
      if (missing(maType)) {
        maType <- "SMA"
      }
      mavg <- do.call(maType, c(list(HLC), maArgs))
      sdev <- as.vector(rollapplyr(HLC, n, sd))
      up <- mavg + sd * sdev
      dn <- mavg - sd * sdev
      pctB <- (HLC - dn)/(up - dn)
      res <- cbind(dn, mavg, up, pctB)
      colnames(res) <- c("dn", "mavg", "up", "pctB")
      reclass(res, HLC)
    }
    

    现在可以在代码中复制该函数了。您还需要激活 library(xts) 当然还有 library(TTR)

    结果

    BBands_2的结果:

    df <- 1:20
    
    BBands_2(df)[20,]
            dn       mavg         up       pctB 
    -1.3321596 10.5000000 22.3321596  0.9014483