Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Find cummax() in range for trend following strategy

posted this question here, but I haven't received an answer.

I have the following df2:

df2 = pd.DataFrame({"price":[200,205,210,208,206, 199, 192, 185, 165, 160, 161, 165, 168, 171, 169, 163, 161], "signal": [1,0,0,0,-1,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,1,0,0,0,-1,np.nan]})  
# for signal, 1 means you opened a position, 0 means you're in the position, and -1 means you closed the position, NaN means you don't currently have a position  

So I have open positions at df2[0:5] and df2[11:16]. For these two separate ranges (df2[0:5] and df2[11:16]), I want the separate cummax() of the price column.

Here's what I tried:

 df2['trailing high'] = np.where(df2['signal'] != np.nan, df2['price'].cummax(), np.nan)  

But the above just gives me the cummax() of the entire price column instead of giving me the cummax() of df2[0:5] and df2[11:16]. As you might have guessed, once I have the trailing cummax() of the price column, I'd use that to set a trailing stop loss where the trailing stop would continue to move higher as price moves higher, but would not move lower (hence the cummax()) as price moves lower.

The final df should look like this:

finaldf = pd.DataFrame({"price":[200,205,210,208,206, 199, 192, 185, 165, 160, 161, 165, 168, 171, 169, 163, 161], "signal": [1,0,0,0,-1,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,1,0,0,0,-1,np.nan], "trailing_high": [200, 205, 210, 210, 210, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 165, 168, 171, 171, 171, np.nan]})

3 responses

Hello,

This should work:

def myfunc(df):  
    trailing_high = []  
    max_val = 0.  
    for i in range(len(df)):  
        if np.isnan(df['signal'].loc[i]):  
            trailing_high.append(np.nan)  
            max_val = 0.  
            print('reset')  
        else:  
            if df['price'].loc[i] > max_val:  
                max_val = df['price'].loc[i]  
            trailing_high.append(max_val)  
    return pd.Series(trailing_high, index=df.index)


df2['trailing high'] = myfunc(df2)  

You are on the right track by looking at the cummax method. However, if applied to the entire dataframe it won't reset for each 'holding period' but rather keep registering the max for the entire dataframe. Not what is wanted (as was noted).

So, maybe don't apply this method to the entire dataframe but only to each 'holding period' group instead? The cummax method not only works over entire dataframes, but also over any user defined groups. By defining a group to be each range where the stock is held, one can effectively get just the cummax for that group.

Here's one way to get the trailing highs as expected. Start with df2 as defined above.

# Start with our original df2 dataframe  
# First add a group column which is simply the increment of the open signal  
df2['group'] = df2.signal.replace(-1, 0).cumsum()

# Next apply the cummax method to each group to get our trailing high  
df2['trailing_high'] = df2.groupby('group').price.cummax()

# Maybe clean up df2 by dropping the group column  
df2 = df2.drop(['group'], axis=1)

That should do it. Two or three lines. The dataframe 'df2' will look like the desired 'finaldf' .

The attached notebook goes into more detail why this works and shows the interim results. Hope that helps.

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.

Thank you for the help! Both work! What if you have your entry signals (1), but your exit signal (-1) is based off the price relative to your trailing high? For example, if price ever falls below the trailing high (e.g. when 208 < 210), that would generate your exit signal (-1), and thus you'd be "out." Which then in turn would mean you would not be generating trailing highs until you get another entry signal (1) and you're back in the trade. I'm stuck because the exit signal is based off the trailing high, which is based off the exit signal.