Skip to content

Commit

Permalink
Use try.xts/reclass and call ema() C function
Browse files Browse the repository at this point in the history
Call ema() C function to avoid 2 calls to the EMA() R function. This
requires adding the try.xts() and reclass() calls to DEMA(), since
they were being done by EMA().

Also add other checks for the value of 'n' and the number of columns
of the input that were done in EMA().

Set 'n' to NULL if it's missing and 'ratio' is not. The C code will
calculate the value of 'n' for the given 'ratio'.

Fixes joshuaulrich#69.
  • Loading branch information
joshuaulrich committed Jun 23, 2018
1 parent 70bf685 commit 25aaf31
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions R/MovingAverages.R
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,25 @@ function(x, n=10, v=1, wilder=FALSE, ratio=NULL) {
# Double Exponential Moving Average
# Thanks to John Gavin for the v-factor generalization

x <- try.xts(x, error=as.matrix)
if( n < 1 || n > NROW(x) )
stop(sprintf("n = %d is outside valid range: [1, %d]", n, NROW(x)))
if(NCOL(x) > 1) {
stop("ncol(x) > 1. DEMA only supports univariate 'x'")
}
if(v < 0 || v > 1) {
stop("Please ensure 0 <= v <= 1")
}

dema <- (1 + v) * EMA(x,n,wilder,ratio) -
EMA(EMA(x,n,wilder,ratio),n,wilder,ratio) * v
if(missing(n) && !missing(ratio))
n <- NULL

# Call C routine
ma1 <- .Call("ema", x, n, ratio, isTRUE(wilder), PACKAGE = "TTR")
d <- .Call("ema", ma1, n, ratio, isTRUE(wilder), PACKAGE = "TTR")

dema <- (1 + v) * ma1 - d * v
dema <- reclass(dema, x)

if(!is.null(dim(dema))) {
colnames(dema) <- "DEMA"
Expand Down

0 comments on commit 25aaf31

Please sign in to comment.