[R-SIG-Finance] Writing sell rules with quantstrat

Brian G. Peterson brian at braverock.com
Wed Feb 15 12:11:50 CET 2012


On Tue, 2012-02-14 at 22:14 -0800, Sergey Pisarenko wrote:
> Hi,
> 
> I have been working with quantstrat and for the most part have been
> able to re-write my existing code to fit within the framework. I see
> that "buy" signals work and "enter" rules are triggered.
> 
> I currently do not grasp how to implement sell rules. I would like to
> create 2 sell rules:
>  1. when profit for a specific position reaches 15%
>  2. when a position is kept for a year
> 
> >From what I have read from the examples the correct method to use is
> "add.rule". Here's something I have already:
> 
> seller <- function(data, timestamp, portfolio, symbol) {
>   posn <- getPosQty(portfolio, symbol, timestamp)
>   if (posn != 0) {
>   }
> }
<...>
> It is clear that the code must go in the "seller" function. I also
> understand that sell order is created by using "addOrder" function. I
> am not sure how to check current profit inside of the function,
> though.
> 
> What would be the correct approach to check the current profit for a
> position inside of the rule function?

In your *entry* rule, you enter at market, so you're guaranteed a
fill.  

Your 'exit' rule for the profit taker order is then clear.  Enter it at
the same time as a stoplimit for 15% more than your entry signal price.
This won't be precisely 15% more than the close price on the next bar,
but is likely fine for a backtest (you could also look ahead, but I
don't recommend adding these kinds of biases).  It is certainly easier
than running all the calculation to check net profit on every bar after
entering a position.

A timed rule could certainly be done in your 'seller' function, but for
efficiency I would probably add an indicator function that would check
my entry indicator, and place a new 'signal' one year later.  Then you
put an entry rule to exit then if you have a position.

If you haven't already done so, find Guy Yollin's lecture slides on
quantstrat from UW.  He demonstrates some interesting custom order
sizing functions that could also give you ideas.

Regards,

   - Brian  

 


-- 
Brian G. Peterson
http://braverock.com/brian/
Ph: 773-459-4973
IM: bgpbraverock



More information about the R-SIG-Finance mailing list