この関数は、調整済み価格が移動平均線を超えてからの日数を返します (交差した日のゼロ)。現在の価格が MA を下回っている場合、日数は負の数になり、現在の価格が MA を上回っている場合は正の数になります。
x
Adjusted
列を持つ xts オブジェクトでn
ありn
、SMA
DaysSinceMACross <- function(x, n) {
prem <- Ad(x) - SMA(Ad(x), n)
prem[seq_len(n)] <- 0
x$grp <- cumsum(c(0, diff(prem > 0, na.pad=FALSE)) != 0)
x$sign <- sign(prem)
x$days <- ave(prem, x$grp, FUN=function(xx) 0:(NROW(xx) - 1))
x$days * x$sign
}
x <-getSymbols(ticker, src='yahoo', to='2012-10-22', auto.assign = FALSE)
R> tail(DaysSinceMACross(x, 10))
# days
#2012-10-15 -5
#2012-10-16 0
#2012-10-17 1
#2012-10-18 0
#2012-10-19 -1
#2012-10-22 -2