How to create a technical indicator in quantmod package

僤鯓⒐⒋嵵緔 提交于 2019-12-03 07:44:20

Rather than writing the add* function from scratch, you could just use newTA:

> library(quantmod)
> getSymbols("AAPL")
[1] "AAPL"
> addFibonacci <- newTA(Fibonacci,on=1)
> chartSeries(AAPL, TA="addFibonacci()")
Error in addFibonacci() : could not find function "get.current.chob"

Hmm, apparently get.current.chob isn't exported... that's okay, we can just change the function ourselves. After calling addFibonacci <- newTA(Fibonacci,on=1), addFibonacci is defined as:

addFibonacci <- function (..., on = 1, legend = "auto") 
{
    #lchob <- get.current.chob()
    lchob <- quantmod:::get.current.chob()
    x <- as.matrix(lchob@xdata)
    x <- Fibonacci(x = x)
    yrange <- NULL
    chobTA <- new("chobTA")
    if (NCOL(x) == 1) {
        chobTA@TA.values <- x[lchob@xsubset]
    }
    else chobTA@TA.values <- x[lchob@xsubset, ]
    chobTA@name <- "chartTA"
    if (any(is.na(on))) {
        chobTA@new <- TRUE
    }
    else {
        chobTA@new <- FALSE
        chobTA@on <- on
    }
    chobTA@call <- match.call()
    legend.name <- gsub("^add", "", deparse(match.call()))
    gpars <- c(list(...), list())[unique(names(c(list(), list(...))))]
    chobTA@params <- list(xrange = lchob@xrange, yrange = yrange, 
        colors = lchob@colors, color.vol = lchob@color.vol, multi.col = lchob@multi.col, 
        spacing = lchob@spacing, width = lchob@width, bp = lchob@bp, 
        x.labels = lchob@x.labels, time.scale = lchob@time.scale, 
        isLogical = is.logical(x), legend = legend, legend.name = legend.name, 
        pars = list(gpars))
    if (is.null(sys.call(-1))) {
        TA <- lchob@passed.args$TA
        lchob@passed.args$TA <- c(TA, chobTA)
        lchob@windows <- lchob@windows + ifelse(chobTA@new, 1, 
            0)
        chartSeries.chob <- chartSeries.chob
        do.call("chartSeries.chob", list(lchob))
        invisible(chobTA)
    }
    else {
        return(chobTA)
    }
}

And you can see where I replaced the call to get.current.chob() with quantmod:::get.current.chob(). Now it should work.

chartSeries(AAPL, TA="addFibonacci()")

Success!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!