Trailing Stop For Exiting On Momentum Strategy

Was reading in the docs there are 3 ways to exit a position QuantRocket:

Exit by rebalancing
Attach exit orders
Close positions with the blotter

If we wanted to exit a position using an 5% trailing stop, what would be the best way to do this? My hunch would be that the trailing stop logic would need to be part of the prices_to_signals logic in which a position returns 0 as a signal for rebalancing if the latest closing price divided by the newest 52-week high is less than 0.95?

Yes, that sounds like a reasonable strategy.

Hey @JohnAntonusMaximus, how far did you get with this?

I'm new to QuantRocket but I'm trying to model trailing stops now.

What @Brian suggests does not sound like enough: The newest 52-week high might be before your trading signal. For example if you're doing mean reversion with a trailing stop, you won't enter long positions if the security is down more than 5% because it will "hit" your trailing stop.

If you take your entry signal and prices.where(other_signal, 0) first you can ignore highs when you were not in a position.

Another problem with just looking at price / 52 week high, your strategy will re-enter positions after your stop was triggered but not change the stop. When the price recovers your stop signal will flip off and you'll reenter the position but the 52 week high is the same...

If you're rebalancing monthly, maybe you could do something like signal.groupby(by=[signal.index.month, signal.index.year]).cummin(). When you exit a position during the month, cummin will "stick" to that exit.

If you need trailing stops, my advice is to use Zipline instead of Moonshot. Even if modeling trailing stops is possible with Pandas/Moonshot (and I'm not sure if it is), it is certainly more natural to use them in an event-driven backtester like Zipline. (Zipline live trading will be available in the upcoming release).