Source code · COMBO-02

MACD + RSI Filter: Python and Pine Script Code

The current Python implementation of MACD + RSI Filter, with an illustrative default-parameter runner, plus a TradingView Pine Script version.

What the code does

A bullish crossover below the RSI overbought level or an already-bullish MACD with oversold RSI can enter. A bearish crossover exits without an oversold veto.

Inputs

  • macd_fast=12, macd_slow=26, macd_signal=9, rsi_period=14, rsi_overbought=70, rsi_oversold=30, rsi_extreme=80.

Indicators

  • MACD uses recursive EMA12−EMA26 and EMA9 signal. RSI uses EMA span14 of gains/losses with denominator offset1e-10.

Entry

  • After 40 rows: bullish crossover AND RSI<70, OR MACD already above signal AND RSI<30.

Exit

  • Bearish crossover, RSI>80, or MACD not above signal while RSI>70.

Python

187 lines. Run it with: python COMBO-02.py SPY

import pandas as pd
import numpy as np

STRATEGY = {'id': 'COMBO-02',
 'name': 'MACD + RSI Filter',
 'mode': 'single',
 'tags': ['Technical', 'Combo', 'Momentum'],
 'summary': 'Combine MACD crossings or bullish pullbacks with EMA-based RSI.',
 'description': 'A bullish crossover below the RSI overbought level or an already-bullish '
                'MACD with oversold RSI can enter. A bearish crossover exits without an '
                'oversold veto.',
 'bestOn': 'Trending markets with pullbacks',
 'frequency': 'Daily',
 'assetClasses': ['Index', 'Commodity', 'FX'],
 'holdingPeriod': 'Days to weeks',
 'instruments': ['SPY', 'GLD', 'USO', 'EURUSD=X'],
 'pseudocode': {'Entry': ['After 40 rows: bullish crossover AND RSI<70, OR MACD already above '
                          'signal AND RSI<30.'],
                'Exit': ['Bearish crossover, RSI>80, or MACD not above signal while RSI>70.'],
                'Indicators': ['MACD uses recursive EMA12−EMA26 and EMA9 signal. RSI uses EMA '
                               'span14 of gains/losses with denominator offset1e-10.'],
                'Inputs': ['macd_fast=12, macd_slow=26, macd_signal=9, rsi_period=14, '
                           'rsi_overbought=70, rsi_oversold=30, rsi_extreme=80.'],
                'Position sizing': ['100% long or cash.']},
 'notes': ['EMA-span RSI differs from Wilder RSI. There is no time stop or proven guarantee '
           'of fewer false signals.'],
 'updated': '2026-01-12',
 'recommendedCompare': ['SPY', 'GLD']}


def calculate_macd(prices, fast=12, slow=26, signal=9):
    """Calculate MACD indicator."""
    ema_fast = prices.ewm(span=fast, adjust=False).mean()
    ema_slow = prices.ewm(span=slow, adjust=False).mean()
    macd_line = ema_fast - ema_slow
    signal_line = macd_line.ewm(span=signal, adjust=False).mean()
    histogram = macd_line - signal_line
    return macd_line, signal_line, histogram


def calculate_rsi(prices, period=14):
    """Calculate RSI indicator."""
    delta = prices.diff()
    gain = delta.where(delta > 0, 0)
    loss = (-delta).where(delta < 0, 0)
    avg_gain = gain.ewm(span=period, adjust=False).mean()
    avg_loss = loss.ewm(span=period, adjust=False).mean()
    rs = avg_gain / (avg_loss + 1e-10)
    return 100 - (100 / (1 + rs))


def generate_signals(prices, config=None):
    config = config or {}

    macd_fast = int(config.get("macd_fast", 12))
    macd_slow = int(config.get("macd_slow", 26))
    macd_signal = int(config.get("macd_signal", 9))
    rsi_period = int(config.get("rsi_period", 14))
    rsi_overbought = float(config.get("rsi_overbought", 70))
    rsi_oversold = float(config.get("rsi_oversold", 30))
    rsi_extreme = float(config.get("rsi_extreme", 80))

    close = prices.copy()
    n = len(close)

    # Calculate indicators
    macd_line, signal_line, histogram = calculate_macd(close, macd_fast, macd_slow, macd_signal)
    rsi = calculate_rsi(close, rsi_period)

    # MACD crossover signals
    macd_cross_up = (macd_line > signal_line) & (macd_line.shift(1) <= signal_line.shift(1))
    macd_cross_down = (macd_line < signal_line) & (macd_line.shift(1) >= signal_line.shift(1))
    macd_bullish = macd_line > signal_line

    signal = pd.Series(0.0, index=close.index)

    warmup = max(macd_slow, rsi_period) + macd_signal + 5

    for i in range(warmup, n):
        prev_signal = signal.iloc[i - 1]
        curr_rsi = rsi.iloc[i]
        curr_macd_bullish = macd_bullish.iloc[i]
        curr_cross_up = macd_cross_up.iloc[i]
        curr_cross_down = macd_cross_down.iloc[i]

        if pd.isna(curr_rsi) or pd.isna(curr_macd_bullish):
            signal.iloc[i] = prev_signal
            continue

        if prev_signal == 0:
            # Not in position - look for entry
            # Entry: MACD bullish crossover AND RSI not overbought
            if curr_cross_up and curr_rsi < rsi_overbought:
                signal.iloc[i] = 1.0
            elif curr_macd_bullish and curr_rsi < rsi_oversold:
                # Alternative entry: MACD already bullish + RSI oversold
                signal.iloc[i] = 1.0
            else:
                signal.iloc[i] = 0.0
        else:
            # In position - look for exit
            # Exit: MACD bearish crossover OR extreme RSI
            if curr_cross_down:
                signal.iloc[i] = 0.0
            elif curr_rsi > rsi_extreme:
                signal.iloc[i] = 0.0
            elif not curr_macd_bullish and curr_rsi > rsi_overbought:
                # MACD bearish + overbought
                signal.iloc[i] = 0.0
            else:
                signal.iloc[i] = 1.0

    return signal.fillna(0.0)


# ---------------------------------------------------------------------------
# Runner added by Quant Arena (https://quantarenas.com/code/) so this file works on its own.
#
#   pip install pandas numpy yfinance
#   python COMBO-02.py SPY              # downloads daily prices with yfinance
#   python COMBO-02.py prices.csv       # daily Date and Close; include Open, High, Low for OHLC rules
#
# This default-parameter example does not replay the site's walk-forward fits
# or archived data. Evidence downloads replay the published run's recorded
# arithmetic and include archived source. Recomputing strategy decisions needs
# the exact original inputs, which may not be public.
# Convention, same as the site: the position decided at the close of day t earns
# the return of day t+1. Results are before trading costs. Not investment advice.
# ---------------------------------------------------------------------------
def _load_prices(source):
    import numpy as np

    if source.lower().endswith(".csv"):
        frame = pd.read_csv(source, index_col=0, parse_dates=True)
    else:
        import yfinance as yf
        try:
            frame = yf.download(source, start="2010-01-01", auto_adjust=True, progress=False)
        except Exception as error:
            raise ValueError("Could not download daily prices: " + str(error)) from error
        if not isinstance(frame, pd.DataFrame):
            raise ValueError("Expected a table of daily prices for one ticker.")
        if isinstance(frame.columns, pd.MultiIndex):
            levels = [level for level in range(frame.columns.nlevels)
                      if "Close" in frame.columns.get_level_values(level)]
            if len(levels) != 1:
                raise ValueError("Expected daily prices for one ticker.")
            frame.columns = frame.columns.get_level_values(levels[0])
    required = ["Open", "High", "Low", "Close"] if STRATEGY.get("input") == "ohlc" else ["Close"]
    if frame.columns.has_duplicates:
        raise ValueError("Expected one column per price field for one ticker.")
    missing = [name for name in required if name not in frame.columns]
    if missing:
        raise ValueError("Missing price columns: " + ", ".join(missing))
    if not isinstance(frame.index, pd.DatetimeIndex) or frame.index.hasnans or frame.index.normalize().has_duplicates:
        raise ValueError("Prices need one row per valid calendar date.")
    frame = frame.copy()
    frame[required] = frame[required].apply(pd.to_numeric, errors="raise")
    frame = frame.sort_index().dropna(subset=required)
    prices = frame[required].to_numpy(dtype=float)
    if len(frame) < 2:
        raise ValueError("Need at least two complete daily observations.")
    if not np.isfinite(prices).all() or (prices <= 0).any():
        raise ValueError("Prices must be finite and positive.")
    return frame


if __name__ == "__main__":
    import sys

    try:
        prices = _load_prices(sys.argv[1] if len(sys.argv) > 1 else "SPY")
    except (OSError, TypeError, ValueError) as error:
        raise SystemExit("Input error: " + str(error)) from error
    close = prices["Close"]
    signal_input = prices if STRATEGY.get("input") == "ohlc" else close
    position = generate_signals(signal_input).reindex(close.index).ffill().fillna(0.0)
    daily = close.pct_change().fillna(0.0) * position.shift(1).fillna(0.0)
    equity = (1 + daily).cumprod()
    years = (close.index[-1].date() - close.index[0].date()).days / 365.25
    print(STRATEGY["id"], STRATEGY["name"], "|", close.index[0].date(), "to", close.index[-1].date())
    print("Total return   {:+.1%}".format(equity.iloc[-1] - 1))
    print("CAGR           {:+.1%}".format(equity.iloc[-1] ** (1 / years) - 1))
    print("Sharpe         {:.2f}".format(daily.mean() / daily.std() * 252 ** 0.5 if daily.std() else 0.0))
    print("Max drawdown   {:.1%}".format((equity / equity.cummax() - 1).min()))
    print("Days in market {:.0%}".format((position != 0).mean()))
    print("Buy and hold   {:+.1%}".format(close.iloc[-1] / close.iloc[0] - 1))

TradingView Pine Script (v5)

This Pine version has no current TradingView compilation check recorded. Use Python for the site's backtest rules.

//@version=5
// COMBO-02 MACD + RSI Filter — Quant Arena (https://quantarenas.com/code/)
// Converted from the Python implementation used on the site. Daily timeframe. Not investment advice.
// Converted by hand from Python and not compiled in TradingView by us: please report problems.
// Note: RSI here uses an EMA with span=period (pandas ewm(span)), NOT Wilder smoothing, so it differs
// slightly from the built-in ta.rsi.
strategy("COMBO-02 MACD + RSI Filter", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0, process_orders_on_close=true)

macdFast   = input.int(12, "MACD fast", minval=1)
macdSlow   = input.int(26, "MACD slow", minval=1)
macdSignal = input.int(9, "MACD signal", minval=1)
rsiPeriod  = input.int(14, "RSI period", minval=1)
rsiOB      = input.float(70, "RSI overbought")
rsiOS      = input.float(30, "RSI oversold")
rsiExtreme = input.float(80, "RSI extreme")

macdLine = ta.ema(close, macdFast) - ta.ema(close, macdSlow)
sigLine = ta.ema(macdLine, macdSignal)

delta = ta.change(close)
gain = delta > 0 ? delta : 0.0
loss = delta < 0 ? -delta : 0.0
avgGain = ta.ema(gain, rsiPeriod)
avgLoss = ta.ema(loss, rsiPeriod)
rs = avgGain / (avgLoss + 1e-10)
rsiV = 100 - (100 / (1 + rs))

crossUp = macdLine > sigLine and macdLine[1] <= sigLine[1]
crossDown = macdLine < sigLine and macdLine[1] >= sigLine[1]
macdBullish = macdLine > sigLine

warmup = math.max(macdSlow, rsiPeriod) + macdSignal + 5

var float pos = 0.0

if bar_index >= warmup
    if na(rsiV) or na(macdLine) or na(sigLine)
        pos := pos
    else if pos == 0
        if crossUp and rsiV < rsiOB
            pos := 1.0
        else if macdBullish and rsiV < rsiOS
            pos := 1.0
        else
            pos := 0.0
    else
        if crossDown
            pos := 0.0
        else if rsiV > rsiExtreme
            pos := 0.0
        else if not macdBullish and rsiV > rsiOB
            pos := 0.0
        else
            pos := 1.0
else
    pos := 0.0

plot(rsiV, "RSI (EMA span)", color=color.purple)
hline(rsiOB, "Overbought", color=color.red)
hline(rsiOS, "Oversold", color=color.green)
hline(rsiExtreme, "Extreme", color=color.maroon)

if pos > 0
    strategy.entry("Long", strategy.long)
else
    strategy.close_all()

Open TradingView to run this scriptAffiliate link: we may earn a commission, at no cost to you.

Run it yourself

pip install pandas numpy yfinance
python COMBO-02.py SPY
python COMBO-02.py my_prices.csv

This example uses current prices and default parameters; it does not reproduce the site's walk-forward results. Evidence downloads include archived source and replay the published run's recorded arithmetic. Recomputing strategy decisions requires the exact original inputs, which may not be public. Baskets use the declared universe (or the site's configured markets); custom symbols and CSV columns keep their order. Only common observations are used, without filling missing prices. Provide enough history for the strategy's lookback and warmup.

Free to use and modify. Provided as is, for research and education. Historical backtests do not predict future returns. Not investment advice.

More strategy code

All strategy code →

Get the weekly Arena report

One email a week: ranking changes, new signals and new research. No spam; unsubscribe any time.