Reputation: 1768
I want to plot my own simple indicator in quantmod like so:
own.ind <- as.matrix(c(1,2,3), ncol=1, nrow=3)
rownames(own.ind) <- c("2017-01-23", "2017-01-24", "2017-01-25")
own.ind <- as.xts(own.ind)
getSymbols("AAPL", from = as.Date("2017-01-23"), to = as.Date("2017-01-25"))
chartSeries(AAPL)
addTA(own.ind)
But it earned me an error saying
Error in seq.default(min(tav * 0.975, na.rm = TRUE), max(tav * 1.05, na.rm = TRUE), :
'from' cannot be NA, NaN or infinite
and two additional warnings:
1: In min(tav * 0.975, na.rm = TRUE) : no non-missing arguments to min; returning Inf
2: In max(tav * 1.05, na.rm = TRUE) : no non-missing arguments to max; returning -Inf
What's wrong?
Upvotes: 1
Views: 130
Reputation: 176648
The problem is that the index for your own.ind
object does not align with any of the index values in the AAPL
object. This is because as.xts
converts the rownames of your matrix to POSIXct
by default. POSIXct
objects have a timezone, and Date
objects don't have a timezone.
R> merge(Cl(AAPL), own.ind)
AAPL.Close own.ind
2017-01-23 120.08 NA
2017-01-23 NA 1
2017-01-24 119.97 NA
2017-01-24 NA 2
2017-01-25 121.88 NA
2017-01-25 NA 3
So you either need to specify the dateFormat
argument to as.xts
or use the xts
constructor and as.Date
directly.
# use dateFormat
own.ind <- as.matrix(c(1,2,3), ncol=1, nrow=3)
rownames(own.ind) <- c("2017-01-23", "2017-01-24", "2017-01-25")
own.ind <- as.xts(own.ind, dateFormat = "Date")
merge(Cl(AAPL), own.ind)
# AAPL.Close own.ind
# 2017-01-23 120.08 1
# 2017-01-24 119.97 2
# 2017-01-25 121.88 3
# use xts constructor and as.Date
own.ind <- xts(1:3, as.Date(c("2017-01-23", "2017-01-24", "2017-01-25")))
merge(Cl(AAPL), own.ind)
# AAPL.Close own.ind
# 2017-01-23 120.08 1
# 2017-01-24 119.97 2
# 2017-01-25 121.88 3
Now you can use addTA
without having to create a function as the other answer says you must.
chartSeries(AAPL, TA="addTA(own.ind)")
Upvotes: 1
Reputation: 2986
Joe, you have to create a function to add the series as indicator. To create an indicator which adds 1 per trading day as in your example do the following:
myInd <- function(x) {
x <- 1:NROW(x)
return(x)
}
create the new indicator:
addMyInd <- newTA(FUN = myInd, legend = "MyInd")
to check class
:
> class(addMyInd)
[1] “function”
Now let’s chart the new indicator below the price chart:
getSymbols("AAPL", from = "2017-01-23", to = "2017-01-25")
chartSeries(AAPL,TA=NULL)
addMyInd()
Upvotes: 0