[R-SIG-Finance] logical AND of all columns in a xts object

Joshua Ulrich josh.m.ulrich at gmail.com
Wed Jan 4 18:29:17 CET 2012


Use apply() and convert the result to xts:

> as.xts(apply(tail(LAGLWCB,10),1,all))
            [,1]
2011-12-19 FALSE
2011-12-20 FALSE
2011-12-21 FALSE
2011-12-22 FALSE
2011-12-23 FALSE
2011-12-27 FALSE
2011-12-28 FALSE
2011-12-29 FALSE
2011-12-30 FALSE
2012-01-03  TRUE

Best,
--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com



On Wed, Jan 4, 2012 at 11:07 AM, Andreas Voellenklee <wotuzu17 at gmail.com> wrote:
> 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---
>
> _______________________________________________
> R-SIG-Finance at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions should go.



More information about the R-SIG-Finance mailing list