Back to Community
Use a trailing stop loss

So, I modified the sample algorithm that we all are able to start with... made the numbers a bit more friendly to a small investor and plugged an S&P Index spyder for the security to invest with...

Now I'm trying to (without any success) to place a trailing stop along with each order. I'd like to limit losses on any trade to no more than 5% and have that margin move with the price.

A bit more advanced a possibility--I'd like to figure out how to widen the margin to 10% or 15% once such a margin would result in no loss of original capital.

Help for a newb?

Clone Algorithm
65
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 51f464d9c32e3206de1ac9b9
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
4 responses

Hi Clestian,

I think you can do that with max(). You might need to use min() for short positions.

# initial set trailing stop for long position  
context.longstop = data[stock].price * (1 - .05) # 5% stop-loss price

# update: increase (never decrease) stop-loss  
context.longstop = max( context.longstop, data[stock].price * (1 - .05) ) # 5% target

# test stop-loss  
if data[stock].price < context.longstop:  
   # sell everything  

That didn't work for me... putting both context statements in my initial data (not sure where to put the update statement) seemed to cause an error with the def handle_data section of the script. However, I think I'm getting the desired result with the backtest below... slightly different buy/sell criteria... and the short stop is basically useless at this point;

next thing to do is implement shorting...

Clone Algorithm
122
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 51f556d24abae506c8f0cb86
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

So, the initial goal was to follow the price/share and have a trailing stop loss follow the price... What I'm doing here is using the opening price multiplied by my trailing stop loss value (.99 long, 1.01 short) to establish a stop loss. If the price goes below (long) or above (short) the stop loss, the position sells. Trading SPY vs. the benchmark... not too bad a margin (70.5% vs 46.5%) for trading the same index against each other...

any suggestions for improving my buy/sell criteria?

I'm going to attempt allowing the screen to run on multiple companies and see what happens... I'll probably be posting it to another discussion.

Clone Algorithm
122
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 51f55d884abae506c8f15d81
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

You could try a breakout signal. For example, if it's a 30-day high, use that as a buy/long signal, and if it's a 30-day low, use that as a sell/short signal. You can do this by storing the last 30 highs and lows and checking if the current price exceeds the high or falls below the low.

So this example doesn't work great, it's not representative of the strategy, just something you can play around with. I just slightly modified your example, you can see a few new lines added and some adjusted if statements.

Also, you could try using stop or limit orders instead of checking every day to see if your price goes out of certain bounds. Although, you will probably have to update the stop or limit orders, but just something to think about. See here: https://www.quantopian.com/help#ide-ordering

Clone Algorithm
144
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 51f68b017afd0b06d02a480f
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.