Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
dynamic stop loss implementation

Hi community,

I am new in both Quantopian and python, so bear with me and my horrible programming skills. I am trying to implement a simple Dynamic Stop loss in few random securities. So far, I am using a small percentage of the entry price i.e. 1-2% to set up the width of the STOP LOSS.

However, after analyzing results and transactions I appreciate there is a problem buying/selling. I switched on a counter to monitor the amount of times I buy or sell shares of a security.

QUESTIONS:
1-When I plot SMA on record()...which of the securities is being displayed? Presumably each security has its own SMA value...
2-If I rebalance everyday, I should only buy shares of a security ONCE every day. Looking into the transaction details I see I buy multiple times the same security.
3-How can I implement a cleaner code to control the dynamic stop loss and the transactions?

Many thanks,

Juan

2 responses

Hey, here some answers:

  1. Since the SMAs are recorded after looping through the SMA-calculation for all securities, you will record the last security. You could use record in the for loop (see appended backtest) to record the SMA10 for all securities.
  2. The rebalance-function is only called once a day at market open. After placing your order, it must be filled. But this can take some time depending on the security.
  3. In Python, you don't have to initialize variables. Adjust your comments, when changing code. Try to set your algos parameters at the begin, then you are able to change them more easily. Use if ... else .... and stack them, when possible. Don't catch an error in an finished algrithm, unless the Exception is a feature.

Hi Sebastian,

Many thanks for your example algo and your good tips. I had a go to modify your example and clearly now I have more control of what the code does. (attached backtest only buying SPY for debugging)

Now, the only thing that still is not under control is when the price goes over the trailing width. It seems it does not update the stop loss.

I have recorded the value of the the stop loss to monitor when the trailing is switching on...I am sure it must be a simple thing I am not seeing right now.