鉴于来自TTR包的BBands函数的残骸数据和结果:
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
不同之处在于,sd使用(n-1)方法作为标准差,BBands使用N方法。
问题是如何让BBands函数使用(n-1)方法。 文档here未列出此类选项。
如果BBands不可能,有人可以帮我制作一个克隆BBands的函数,但标准偏差为(n-1)。
答案 0 :(得分:0)
功能
当你编写函数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&lt; - as.vector(rollapplyr(HLC,n,sd))`,所以我们得到一个矢量输出。让我们称之为新功能BBands_2:
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