r-我需要你帮助创建指标函数



谢谢你帮我。我想创建指标的函数。它适用于TTR:SMA,但不适用于TRR::或TTR::Donchian Channel

这是工作的例子。(SMA(

# Create SMA function
n = 10
sma <- function(x, return_format = "tibble", n = n) {
# Convert tibble to xts
if (!is.xts(x)) {
x <- xts(x[,-1], order.by = x$Date)
}
# Get SMA 
sma_xts <- SMA(x = x$Adjusted, n = n) # I want sma on Adjusted Price
# Rename
names(sma_xts) <- "SMA"
# Return in xts format if tibble is not specified
if (return_format == "tibble") {
sma <- fortify.zoo(sma_xts, names = "Date")
} else {
sma <- sma_xts
}
sma
}

然而,当我想将此应用于或DonchianChannel时,它显示为NA。

# Create DonchianChannel
n = 10
dc <- function(x, return_format = "tibble", n = n) {
# Convert tibble to xts
if (!is.xts(x)) {
x <- xts(x[,-1], order.by = x$Date)
}
# Get DonchianChannel
dc_xts <- DonchianChannel(x = c(x$High,x$Low), n = n) # <<< I think here is the problem
# Rename
names(dc_xts) <- "DC"
# Return in xts format if tibble is not specified
if (return_format == "tibble") {

dc <- fortify.zoo(dc_xts, names = "Date")

} else {
dc <- dc_xts
}
dc
}

我的最佳猜测是函数的输入是错误的。因为SMA需要x,但DonchianChannel需要HL。所以我尝试了很多格式,但仍然没有得到

SMA(x, n = 10, ...)
ATR(HLC, n = 14, maType, ...)
DonchianChannel(HL, n = 10, include.lag = FALSE)

谢谢你们启发我:(我正在努力变得更好。

您遇到了一些问题。第一个是在函数外定义n。n的承诺将在DonchianChannel调用内部引发问题。第二个是DonchianChannel函数不期望有一个对象x,而是一个对象HL。第三个问题是函数返回3列,而不是1列,因此重命名将失败。

我创建了一个工作示例,没有重命名任何内容。

library(quantmod)
aapl <- getSymbols("AAPL", from = Sys.Date() - 366, to = Sys.Date(), auto.assign = FALSE)
# set default values in the function definition, like n = 10
dc <- function(x, return_format = "tibble", n = 10) {
# Convert tibble to xts
if (!is.xts(x)) {
x <- xts(x[,-1], order.by = x$Date)
}
# Get DonchianChannel, note that donchian needs HL, not x
dc_xts <- TTR::DonchianChannel(HL = cbind(x$High, x$Low), n = n) 
# Return in xts format if tibble is not specified
if (return_format == "tibble") {
dc <- fortify.zoo(dc_xts, names = "Date")
} else {
dc <- dc_xts
}
dc
}
head(dc(aapl), 15)
Date   high     mid    low
1  2021-09-20     NA      NA     NA
2  2021-09-21     NA      NA     NA
3  2021-09-22     NA      NA     NA
4  2021-09-23     NA      NA     NA
5  2021-09-24     NA      NA     NA
6  2021-09-27     NA      NA     NA
7  2021-09-28     NA      NA     NA
8  2021-09-29     NA      NA     NA
9  2021-09-30     NA      NA     NA
10 2021-10-01 147.47 143.290 139.11
11 2021-10-04 147.47 142.870 138.27
12 2021-10-05 147.47 142.870 138.27
13 2021-10-06 147.47 142.870 138.27
14 2021-10-07 147.47 142.870 138.27
15 2021-10-08 145.96 142.115 138.27

ATR函数需要一个HLC对象,并且按照这个顺序。如果您制作了一个函数,请使用此函数,确保任何cbind的顺序正确。始终检查函数的返回,因为许多财务函数返回的列不止一列。

最新更新