How do I code a trailing stop that resets after re-entry?

Write a trailing stop whose decision depends on the peak since entry, reset the peak at every new entry, and run the rule as a loop over the closes in date order.

After this lesson, you can code a trailing stop that remembers the highest close since entry and starts a new peak at each entry.

How does the rule remember its peak?

Once the signal is on, the rule tracks the highest close since entry, its peak, and turns off at the first close at or below 95% of that peak. A new entry starts a new peak. In the example, the signal turns off on 4 April, when the close of 104 falls below the stop of \(0.95 \times 110 = 104.50\) dollars.

\[ \text{stop}_t = s\,H_t \]

Here \(s\) is the stop fraction, 0.95, and \(H_t\) the highest close since the latest entry.

Each decision depends on the peak, and the peak depends on when the signal last turned on, so the rule runs as a loop over the closes in date order. on holds yesterday’s signal and highest the peak. When the signal is on, max updates the peak and the comparison decides whether it stays on. When it is off, an entry flag of 1 turns it on and sets the peak to that close.

The example has eight closes of one made-up stock, with an entry flag of 1 on 2, 5 and 10 April. np.zeros(..., dtype=np.int8) prepares one signal per close, and np.full(..., np.nan) one peak per close, which stays NaN while the signal is off. .to_numpy() passes the columns to the loop as arrays.

The following box runs the rule and prints the peak and stop of each day.

import numpy as np
import pandas as pd

stock = pd.DataFrame({
    "date": pd.bdate_range("2024-04-02", periods=8),
    "close": [100.0, 110.0, 104.0, 100.0, 104.0, 98.0, 99.0, 106.0],
    "entry": [1, 0, 0, 1, 0, 0, 1, 0],
})

def trailing_signal(close, entry, stop=0.95):
    signal = np.zeros(len(close), dtype=np.int8)
    peak = np.full(len(close), np.nan)
    on = False
    highest = 0.0
    for t in range(len(close)):
        if on:
            highest = max(highest, close[t])
            peak[t] = highest
            on = close[t] > stop * highest
        elif entry[t] == 1:
            on = True
            highest = close[t]
            peak[t] = highest
        signal[t] = on
    return signal, peak

stock["signal"], stock["peak"] = trailing_signal(stock["close"].to_numpy(), stock["entry"].to_numpy())
stock["stop"] = 0.95 * stock["peak"]
print(stock)
        date  close  entry  signal   peak    stop
0 2024-04-02  100.0      1       1  100.0   95.00
1 2024-04-03  110.0      0       1  110.0  104.50
2 2024-04-04  104.0      0       0  110.0  104.50
3 2024-04-05  100.0      1       1  100.0   95.00
4 2024-04-08  104.0      0       1  104.0   98.80
5 2024-04-09   98.0      0       0  104.0   98.80
6 2024-04-10   99.0      1       1   99.0   94.05
7 2024-04-11  106.0      0       1  106.0  100.70

The entry on 5 April starts a new peak at 100, so the stop falls from 104.50 to 95 dollars. With the old peak of 110, the close of 104 on 8 April would have turned the signal off.

When does the trade happen?

A signal at a close becomes a trade at the next close, as in the lesson on signals. The signal turns off at the close of 9 April, so the stock is sold at the close of 10 April, at 99 dollars.

Your turn

Run the rule with a stop at 90% of the peak and print the signals. You should see a single 0, on 9 April.

stop=0.90 lowers the stop, so the entry flag of 5 April finds the signal still on and the peak stays at 110.

stock["signal_90"], peak_90 = trailing_signal(stock["close"].to_numpy(), stock["entry"].to_numpy(), stop=0.90)
print(stock[["date", "close", "signal_90"]])
        date  close  signal_90
0 2024-04-02  100.0          1
1 2024-04-03  110.0          1
2 2024-04-04  104.0          1
3 2024-04-05  100.0          1
4 2024-04-08  104.0          1
5 2024-04-09   98.0          0
6 2024-04-10   99.0          1
7 2024-04-11  106.0          1