How to put stoploss in backtesting

dear sir,



in this strategy ther is only buy and for exit it is double selling what to code for exit or stoploss for backtesting

 df['Signal'] = np.nan

    df.loc[(df['SAR']< df['Adj Close']) & (df['fastd']>df['slowd']) & (df['fastk']>df['slowk']),'Signal'] =1

    df.loc[(df['SAR']> df['Adj Close']) & (df['fastd']<df['slowd']) & (df['fastk']<df['slowk']),'Signal'] =-1

    df['Signal'] = df['Signal'].fillna(method='ffill')

how to put 0 for exit. please suggest with if conditon i have tried but error occurs

Hello Promod,



You can incorporate stop-loss into your signal labels by perhaps adding more conditions which check for prices. If the adjusted close is lower than a threshold at any given point in the series you can make the signal as -1. 



df.loc[threshold> df['Adj Close']  ,'Signal'] =-1



You can do the same thing using returns as well. Set a percentage threshold and then check if returns are lower than this threshold. 



df.loc[threshold_ret> df['returns']  ,'Signal'] =-1




Similarly, you can put conditions for when you don't want to take a position using something like:



df.loc[condition  ,'Signal'] = 0



Do get back if further clarification is needed. 








 

thank you sir for your responce i have tried this but still getting error in code, the code is as follows, please suggest me where i am wrong what chages to be made.

 df['Signal'] = np.nan

    df.loc[(df['SAR']< df['Adj Close']) & (df['fastd']>df['slowd']) & (df['fastk']>df['slowk']),'Signal'] =1

    df.loc[(df['SAR']> df['Adj Close']) & (df['fastd']<df['slowd']) & (df['fastk']<df['slowk']),'Signal'] =-1

    df['Signal'] = df['Signal'].fillna(method='ffill')    

        if df.loc[(df['Signal'] == 1:

            df.loc[(df['Adj Close'] < (df['Adj Close']-(df['ATR']*2))), 'Signal'] = 0

        elif df.loc[(df['Signal'] == -1:

            df.loc[(df['Adj Close'] > (df['Adj Close']+(df['ATR']*2)), 'Signal'] = 0

    df['Signal'] = df['Signal'].fillna(method='ffill')

 

Hello Promod,



There are syntactical errors in this code. I would recommend that you try out Quantra's free offerings on pandas and NumPy. 



Your thought process is however right. You can do the first one as follows:



df.loc[(df['Signal'] == 1) & (df['Adj Close'] < (df['Adj Close']-(df['ATR']*2))), 'Signal'] = 0



No need for the if and elif.