2013-07-30

(This article was originally published at Systematic Investor » R, and syndicated at StatsBlogs.)

Today I want to share and present an example of the flexible Stop Loss functionality that I added to the Systematic Investor Toolbox.

Let’s examine a simple Moving Average Crossover strategy:

Buy is triggered once fast moving average crosses above the slow moving average

Sell is triggered once fast moving average crosses below the slow moving average

Here is an example using 20 and 50 day moving averages on SPY.

Next, I created the custom.stop.fn() function in bt.stop.r at github to handle user defined stop functions. Let’s have a look at 3 different flavors of stops below:

Each user defined stop function have 4 required inputs:

weight – signal or weight indicating position

price – price for asset

tstart – index(time) when trade was open

tend – index(time) when trade is closed

Additionally, you can provide any other required information.

For example, the fixed.stop function above, will exit the trade once price falls below given % (pstop) from entry price or trade is closed. The trailing.stop.profit.target function will exit the trade once either:

trailing stop is reached. i.e. price falls below given % (pstop) from max price since start of trade OR

profit target is reached. i.e. price rises above given % (pprofit) from entry price

Following is an example of integrating these stop losses into the back-tests. Please note that I only use the Buy rule from the original strategy to open the trades and to close the trades I use the stop loss logic.



Nothing exciting to report. The fixed stop loss is not triggered often and resembles the Buy and Hold. The trailing stops reduce the time strategy is in the market and also reduce returns. The trailing stop with profit target is doing a bit better.

We can see functionality of the stops more clearly in the picture below:



The shaded green area indicates the times when strategy is invested. In the top chart, the strategy is long once fast moving average (red line) is above the slow moving average (blue line).

The next chart (Fixed Stop) is fully invested because market has taken off since we entered the trade and stop, which is % relative to the trade entry price, is never triggered.

The last 2 charts show the trailing stop logic. Strategy is less often invested once we enforce the aggressive profit target.

Have fun with creating your own customized stop loss functions and let me know if you run into problems.

To view the complete source code for this example, please have a look at the bt.stop.ma.cross.test() function in bt.stop.test.r at github.



Please comment on the article here: Systematic Investor » R

The post Stop Loss appeared first on All About Statistics.

Show more