Stop Loss in Mean Reversion Strategy (section 11, unit 2)

I do not understand the logic behind the code for the stop loss in mean reversion strategy:

 

if sl_flag:
        # Add a stop loss x standard deviation away from lower band.
        # For example, refer to the above markdown cell
        df['long_sl'] = df.prices < (
            df.lower_band - sl_std_dev*df.moving_std_dev)

        # Whenever the long_sl is True, set the positions_long_sl to 0
        df.loc[df.long_sl, 'positions_long_sl'] = 0

        # Whenever the price reverts to the mean, set the positions_long_sl to 1
        df.loc[df.long_exit, 'positions_long_sl'] = 1

Why do we have to set positions_long_sl to 1 when the price reverts to the mean if our position has already a value of '0'?



Many thanks!



Luca

Hey Luca!



"positions_long_sl" is a counter variable. It tracks whether the long position has been cut by stop-loss or not. Whenever a position is exited due to hitting of SL, the "positions_long_sl" is set from 1 to 0 which will consequently make the "positions" column 0.



Hope that clarifies your doubt.

Dear Rishabh, 



thanks for your explanation. I understand that when the SL is triggered, the "positions_long_sl" is set to zero, so it can be multiplied with the current "positions_long" equal to 1, giving a zero position.



My question was why do we set "positions_long_sl" at 1 when it triggers the mean, if the "positions_long" is already at zero? Thanks!

df.loc[df.long_exit, 'positions_long_sl'] = 1

Hey Luca,



We set the "positions_long_sl" at 1 when it triggers the mean to reset it to the original state. So whenever a new long position is taken, and a consequent SL is hit, the change from 1 to 0 can be made for the "positions_long_sl" and consequently "positions_long".



If you don't reset "positions_long_sl" to 1 at the mean, i.e., the long exit, any new positions taken after that will be set to 0 even if the SL is not hit due to the following line of code: 

df.positions_long = df.positions_long * df.positions_long_sl

In the above code, any new position if taken will result in:

# 1 (df.positions_long) x 0 (df.positions_long_sl) = 0

To avoid this, we reset "positions_long_sl" to 1.



Hope that clarifies the issue.

Yes Rishabh, now it's clear. Many thanks for your precious help!



Luca