On Sep 30, 2013 10:02 AM, "Mark Knecht" <markknecht@gmail.com> wrote:
>
> On Fri, Sep 27, 2013 at 5:52 PM, Mark Knecht <markknecht@gmail.com> wrote:
> > On Fri, Sep 27, 2013 at 5:33 PM, Joshua Ulrich <josh.m.ulrich@gmail.com>
wrote:
> >> On Fri, Sep 27, 2013 at 7:17 PM, Mark Knecht <markknecht@gmail.com>
wrote:
> >>> Only slightly financial. Is there a function somewhere that implements
> >>> a real crossing check, as in MA1 crosses above MA2 and not just
> >>> MA1>MA2?. TTR seemed a likely candidate but I haven't found it there.
> >>>
> >> Yes, diff().
> >>
> >> library(quantmod)
> >> x <- Cl(getSymbols("SPY", auto.assign=FALSE))
> >> y <- EMA(x,10) > EMA(x,20)
> >> z <- merge(y, diff(y))
> >>
> >>> I alsa tried sos's findFn for searching, as well as stackoverflow but
> >>> it seems too general a question.
> >>>
> >>>
> >>
> >
> > Thanks Joshua. Surprising answer but it certainly works.
> >
> > Cheers,
> > Mark
>
> Hi Joshua,
>    Thanks again for the code snippet. As my xts fu is severely lacking
> I've been playing a bit with the code to try and get better. xts is
> pretty cool. Here's my slightly modified version of your code where I
> wanted to start building an xts object that gets extended as the
> modeling progresses:
>
> library(quantmod)
>
> SPY <- getSymbols("SPY", auto.assign=FALSE)
>
> SPY$EMA.10 <- EMA(Cl(SPY),10)
> SPY$EMA.20 <- EMA(Cl(SPY),20)
> SPY$y  <- with(SPY, (EMA.10 > EMA.20))
>
> SPY$y1 <- with(SPY, diff(y))
> SPY$z  <- with(SPY, merge.xts(y, y1))[,2]
> head(SPY, n=10)
>
>    There is (I think) one issue with this code. The code correctly
> identifies a 'cross above' event because (EMA.10 > EMA.20) does test
> above. However if EMA.10 has been above I think it incorrectly detects
> a 'cross below' event if (EMA.10 == EMA.20). I figure I can solve that
> using some extra data column, like a lagged EMA.10 possibly, unless
> you know of an easier, more built in way.
>
Your original question only asked about a cross above.  If you want to test
for a cross below, you need to test EMA.10 < EMA.20.

If you want both crosses in one column, you can combine them by checking
when the diffs of the logical comparisons equal 1.

(diff(EMA.10 > EMA.20)==1) - (diff(EMA.10 < EMA.20)==1)

Now the cross above will be 1 and the cross below will be -1.

>    Again, thanks for the example code. It's helpful.
>
> Cheers,
> Mark

	[[alternative HTML version deleted]]

