How to create a technical indicator in quantmod package

后端 未结 1 1399
清酒与你
清酒与你 2021-02-09 17:43

I\'m a newbie to R and I am facing some problems with the creation of a technical indicator. More specifically, I want to create an indicator, Fibonacci, which will

1条回答
  •  不思量自难忘°
    2021-02-09 18:10

    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!

    enter image description here

    0 讨论(0)
提交回复
热议问题