[R-SIG-Finance] Crosses above, crosses below

Mark Knecht markknecht at gmail.com
Mon Sep 30 17:02:39 CEST 2013


On Fri, Sep 27, 2013 at 5:52 PM, Mark Knecht <markknecht at gmail.com> wrote:
> On Fri, Sep 27, 2013 at 5:33 PM, Joshua Ulrich <josh.m.ulrich at gmail.com> wrote:
>> On Fri, Sep 27, 2013 at 7:17 PM, Mark Knecht <markknecht at 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,
>>> Mark
>>>
>>
>> --
>> Joshua Ulrich  |  about.me/joshuaulrich
>> FOSS Trading  |  www.fosstrading.com
>
> 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.

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

Cheers,
Mark



More information about the R-SIG-Finance mailing list