DEV Community

ayushman4you-ctrl
ayushman4you-ctrl

Posted on

Supertrend + 200 EMA Trend Filter in Python (No TA-Lib)

Most retail algorithmic trading bots fail not because the entry indicator is wrong, but because they keep firing signals during sideways consolidation.

If you run a standalone Supertrend (10, 3) on index intraday or swing charts, choppy sessions will trigger back-to-back false breakouts. Pairing Supertrend with a 200-period Exponential Moving Average (EMA) acts as a structural regime filter:

  • Longs allowed only when: Close > 200 EMA AND Supertrend == Bullish
  • Shorts allowed only when: Close < 200 EMA AND Supertrend == Bearish
  • Otherwise: Stay flat (CHOPPY_NO_TRADE)

Pure Python & Pandas Implementation (Zero External TA Binaries)

Installing TA-Lib on cloud containers or lightweight environments often breaks due to C-compiler dependencies. Here is the clean, vectorized ATR + Supertrend + 200 EMA filter using only numpy and pandas:


python
import numpy as np
import pandas as pd

def add_supertrend_ema_filter(df: pd.DataFrame, atr_period: int = 10, multiplier: float = 3.0) -> pd.DataFrame:
    df = df.copy()

    # 1. Macro Regime Filter (200 EMA)
    df["EMA_200"] = df["Close"].ewm(span=200, adjust=False).mean()

    # 2. True Range & Wilder's ATR
    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 / atr_period, adjust=False).mean()

    # 3. Basic Upper & Lower Bands
    hl2 = (df["High"] + df["Low"]) / 2
    upper_band = hl2 + (multiplier * atr)
    lower_band = hl2 - (multiplier * atr)

    supertrend = np.zeros(len(df))
    direction = np.ones(len(df))

    for i in range(1, len(df)):
        if df["Close"].iloc[i] > upper_band.iloc[i - 1]:
            direction[i] = 1
        elif df["Close"].iloc[i] < lower_band.iloc[i - 1]:
            direction[i] = -1
        else:
            direction[i] = direction[i - 1]
            if direction[i] == 1 and lower_band.iloc[i] < lower_band.iloc[i - 1]:
                lower_band.iloc[i] = lower_band.iloc[i - 1]
            if direction[i] == -1 and upper_band.iloc[i] > upper_band.iloc[i - 1]:
                upper_band.iloc[i] = upper_band.iloc[i - 1]

        supertrend[i] = lower_band.iloc[i] if direction[i] == 1 else upper_band.iloc[i]

    df["Supertrend"] = supertrend
    df["Trend_Dir"] = np.where(direction == 1, "BULLISH", "BEARISH")

    # 4. Confluence Execution Gate
    df["Trade_Regime"] = np.where(
        (df["Close"] > df["EMA_200"]) & (df["Trend_Dir"] == "BULLISH"),
        "LONG_ALLOWED",
        np.where(
            (df["Close"] < df["EMA_200"]) & (df["Trend_Dir"] == "BEARISH"),
            "SHORT_ALLOWED",
            "CHOPPY_NO_TRADE",
        ),
    )
    return df
Enter fullscreen mode Exit fullscreen mode

Top comments (0)