[R-SIG-Finance] quantstrat help

Joshua Ulrich josh.m.ulrich at gmail.com
Fri Oct 17 15:05:39 CEST 2014


On Fri, Oct 17, 2014 at 7:31 AM, Raghuraman Ramachandran
<optionsraghu at gmail.com> wrote:
> Thx Josh.
>
> Here is the code:
>
> require(quantmod)
> require(TTR)
> getSymbols('^GSPC')
> colnames(GSPC)=c("Open","High","Low","Close","Volume","AdjPrice")
> for (i in 1: nrow(GSPC))
> {
>   GSPC$signal[i]=ifelse((GSPC$Close[i]>1.02*GSPC$Open[i]), 1
> ,ifelse(GSPC$Close[i]<= 0.98*GSPC$Open[i], -1, 0))
> }
>
It is very bad practice to call a vectorized function (ifelse) inside
a loop.  The loop is unnecessary:
GSPC$signal <- with(GSPC,
  ifelse(Close > 1.02*Open, 1, ifelse(Close <= 0.98*Open, -1, 0)))

> So there will be consecutive days of longs or shorts but how to ignore
> the subsequent signals and take the first occurrences inside
> quantstrat pls?
>
If you truly want to ignore those signals, simply remove them before
sending them to applyRules.
GSPC$firstSignal <- with(GSPC, ifelse(signal == lag(signal), 0, signal))

> Rgds
> Raghu
>
> On Fri, Oct 17, 2014 at 12:50 PM, Joshua Ulrich <josh.m.ulrich at gmail.com> wrote:
>> On Fri, Oct 17, 2014 at 4:37 AM, Raghuraman Ramachandran
>> <optionsraghu at gmail.com> wrote:
>>> Dear guRus
>>>
>>> I am trying to understand the quantstrat package. My signal is very
>>> simple. I want to buy if daily close > 2% of open and vice versa. But
>>> my signals produce consecutive 1s (when market is going higher) and
>>> -1s (when market is going lower) so I want to avoid buying (or
>>> selling) more if already bought or sold.
>>>
>> Then only take the first signal.  If you want more specific
>> instructions about how to do that, then provide more specific details
>> about your problem (e.g. your actual code).
>>
>>> My question is:
>>> Is it possible to tell quantstrat a) Please do not buy if already
>>> bought and if a new buy signal appears and b) Please buy even though
>>> if already bought and a new signal appears.
>>
>> a) Yes.
>> b) Yes.
>>
>>> Also, when a leave a trailing stop which takes precedence? A trailing
>>> stop or a new signal on the opposite side and is it possible to change
>>> this precedence please?
>>>
>> Rules are processed in the order described in the Details section of
>> ?add.rule.  You can change the order, but it is strongly discouraged
>> because it's very easy to create unrealistic behavior if you modify
>> the order incorrectly.
>>
>>> Sincere thanks for the guidance,
>>> Raghu
>>>
>>
>> --
>> Joshua Ulrich  |  about.me/joshuaulrich
>> FOSS Trading  |  www.fosstrading.com



More information about the R-SIG-Finance mailing list