函数
只要编写函数,就可以得到简单的函数代码
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