R 肯特纳频道

R Keltner Channels

R 是否有任何已经实现了 Keltner 通道的软件包,我想知道的是每日收盘价位于哪个通道中(-3、-2、-1、1、2、3 )

我在TTR中找到了ATR功能,但我不确定是否有办法使用它,我想得到的是类似于link描述的东西,我只需要值,而不是图表,以便我可以比较每日收盘价与渠道

Keltner Channels : StockCharts.com

Keltner Channels

感谢任何为我指明正确方向的帮助

这种模板代码将帮助您获得您特别想要的东西。选择您自己的 n 值等

library(quantmod)
getSymbols("AAPL")

get_Keltner_channels <- function(ohlc, n_EMA = 10, n_ATR = 14, multiplier = 2) {
    mid <- EMA(Cl(ohlc), n_EMA)    
    hi <- mid + multiplier * ATR(HLC = HLC(ohlc), n = n_ATR)$atr
    lo <- mid - multiplier * ATR(HLC = HLC(ohlc), n = n_ATR)$atr
    keltner <- cbind(lo, mid, hi)
    colnames(keltner) <- c("Kelt_lo", "Kelt_mid", "Kelt_hi")
    keltner
}

out <- get_Keltner_channels(AAPL)

# > tail(out)
# Kelt_lo Kelt_mid   Kelt_hi
# 2016-07-15 94.26621 97.09092  99.91563
# 2016-07-18 94.74742 97.58893 100.43045
# 2016-07-19 95.27084 98.00367 100.73651
# 2016-07-20 95.71888 98.35937 100.99986
# 2016-07-21 95.83500 98.55403 101.27306
# 2016-07-22 95.88848 98.57330 101.25811
KC <- function(x, n.ema = 20, n.atr = 10, multiplier = 2, maType='EMA') {
    x <- try.xts(x, error = as.matrix)
    ma <- do.call(what = maType, args = list(Cl(x), n.ema))
    atr <- ATR(HLC(x), n = n.atr, maType = maType)$atr
    upper <- ma + multiplier * atr
    lower <- ma - multiplier * atr
    r <- cbind(lower, ma, upper)
    colnames(r) <- c("KC.lower", "KC.mid", "KC.upper")
    return(reclass(r,x))
}

addKC <- newTA(FUN = KC, on = -1, col = rep('cornflowerblue', 3), lty = rep('dotted', 3))

如果您喜欢 dplyr,这可能会对您有所帮助。调味。

keltnerEmaPeriods = 20
keltnerAtrPeriods = 20
keltnerAtrMultiplier = 1.5
      
tidyquant::tq_mutate( mutate_fun=EMA, select=close, n=keltnerEmaPeriods) %>%
dplyr::rename( "Keltner_average"="EMA" ) %>%
tidyquant::tq_mutate( mutate_fun=ATR, n=keltnerAtrPeriods ) %>%
dplyr::select( -c("tr", "ATR", "ATR..1") ) %>%
dplyr::mutate( "Keltner_lower" = Keltner_average - keltnerAtrMultiplier * atr) %>%
dplyr::mutate( "Keltner_upper" = Keltner_average + keltnerAtrMultiplier * atr) %>%