R (quantmod),绘制自己的指标,错误 seq.default

R (quantmod), plot own indicator, Error in seq.default

我想像这样在 quantmod 中绘制我自己的简单指标:

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)

但它给我带来了一个错误说

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

和两个额外的警告:

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

怎么了?

Joe,你必须创建一个函数来添加系列作为指标。要创建一个在您的示例中每个交易日加 1 的指标,请执行以下操作:

myInd <- function(x) {
  x <- 1:NROW(x)
  return(x)
}

创建新指标:

addMyInd <- newTA(FUN = myInd, legend = "MyInd")

检查class:

> class(addMyInd)
[1] “function”

现在让我们在价格图表下方绘制新指标:

getSymbols("AAPL", from = "2017-01-23", to = "2017-01-25")
chartSeries(AAPL,TA=NULL)
addMyInd()

问题是您的 own.ind 对象的索引与 AAPL 对象中的任何索引值都不对齐。这是因为 as.xts 默认情况下会将矩阵的行名转换为 POSIXctPOSIXct 个对象有时区,Date 个对象没有时区。

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

因此您需要将 dateFormat 参数指定给 as.xts 或直接使用 xts 构造函数和 as.Date

# 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

现在您可以使用 addTA,而不必像其他答案所说的那样创建函数。

chartSeries(AAPL, TA="addTA(own.ind)")