Algorithmic Trading & Indicators Intermediate

ATR Trailing Stop-Loss Line & Supertrend Exit Engine in Python

Calculate volatility-based ATR Trailing Stop lines in Python Pandas that ratchet upward during bull trends and downward during bear trends.

#pandas#numpy

Problem Statement

Fixed stop-losses give back profits during parabolic trends. An ATR trailing stop ratchets behind price action, locking in gains automatically.

Formula / Core Logic

Trail_Stop_Long = Max(Trail_Stop__{t-1}, Close_t - Multiplier * ATR)

Installation

pip install pandas numpy
atr-trailing-stop-supertrend-confluence-python.py
import pandas as pd
import numpy as np
\.def atr_trailing_stop(df, period=14, mult=3.0):
    df = df.copy()
    tr = pd.concat([df['High'] - df['Low'], (df['High'] - df['Close'].shift(1)).abs(), (df['Low'] - df['Close'].shift(1)).abs()], axis=1).max(axis=1)
    atr = tr.ewm(alpha=1/period, adjust=False).mean()
    
    close = df['Close'].values
    stop = close - (mult * atr.values)
    trail_stop = np.zeros_like(close)
    
    for i in range(1, len(close)):
        if close[i] > trail_stop[i-1] and close[i-1] > trail_stop[i-1]:
            trail_stop[i] = max(trail_stop[i-1], close[i] - (mult * atr.iloc[i]))
        else:
            trail_stop[i] = close[i] - (mult * atr.iloc[i])
    df['ATR_Trail_Stop'] = trail_stop
    return df

Get the Complete 100+ Python Quant & Automation Bundle

Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).

Buy Full Bundle on Gumroad ($19) →

Frequently Asked Questions

Q: How does trailing stop differ from Supertrend?

ATR trailing stops ratchet continuously based on price distance, whereas Supertrend flips its band level only upon trend state transitions.