[R-SIG-Finance] logical AND of all columns in a xts object
Andreas Voellenklee
wotuzu17 at gmail.com
Wed Jan 4 18:07:08 CET 2012
I am working on a function to filter a OHLC timeseries for n
consecutive long white/black candles in a row.
In the example below the xts- object "LAGLWCB" looks like this:
> tail(LAGLWCB,n=10)
Lag.0 Lag.1 Lag.2
2011-12-19 TRUE FALSE FALSE
2011-12-20 FALSE TRUE FALSE
2011-12-21 FALSE FALSE TRUE
2011-12-22 FALSE FALSE FALSE
2011-12-23 FALSE FALSE FALSE
2011-12-27 FALSE FALSE FALSE
2011-12-28 FALSE FALSE FALSE
2011-12-29 TRUE FALSE FALSE
2011-12-30 TRUE TRUE FALSE
2012-01-03 TRUE TRUE TRUE
The condition "Three consecutive long white candle bodies" is true
when the logical- AND of all columns equals true:
eval(LAGLWCB[,1] & LAGLWCB[,2] & LAGLWCB[,3])
is there a way to perform logical operations on all columns of a xts
object, without having to explicitly code all columns like in the
command above?
Thanks,
Andreas
# ---example---
require("quantmod")
getSymbols("GLBS", adjust=TRUE)
CSPLongCandleBody <- function(TS, n=20, threshold=1.5) {
CBL <- 2*(abs(Op(TS)-Cl(TS))) / (Op(TS)+Cl(TS))
CBLMedian <- runMedian(CBL, n=n)
LongWhiteCandleBody <- eval (CBL >= CBLMedian*threshold & Cl(TS) > Op(TS))
LongBlackCandleBody <- eval (CBL >= CBLMedian*threshold & Op(TS) > Cl(TS))
result <- cbind(LongWhiteCandleBody, LongBlackCandleBody)
colnames(result) <- c("LongWhiteCandleBody", "LongBlackCandleBody")
return(result)
}
# LongWhiteCandleBody
LWCB <- CSPLongCandleBody(GLBS)[,1]
tail(LWCB,n=10)
# Lag LongWhiteCandleBody 0 to 2 periods
LAGLWCB <- Lag(LWCB, k=0:2)
tail(LAGLWCB,n=10)
# Three consecutive Long White Candle Bodies
ThreeLWCB <- eval(LAGLWCB[,1] & LAGLWCB[,2] & LAGLWCB[,3])
tail(ThreeLWCB,n=10)
# ---end of example---
More information about the R-SIG-Finance
mailing list