源码 · COMBO-02

MACD + RSI 过滤:Python 与 Pine 脚本源码

MACD + RSI 过滤 的当前 Python 实现,附使用默认参数的示例运行器,另附 TradingView Pine 脚本版本。

这段代码做了什么

RSI未超买时的MACD多头交叉,或MACD已处于多头且RSI超卖,都可入场;空头交叉退出不受RSI超卖限制。

参数

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

指标

  • MACD为递归EMA12−EMA26,信号线EMA9;RSI对涨跌额使用span14的EMA,分母加1e-10。

入场

  • 40行后:多头交叉且RSI<70,或MACD已高于信号线且RSI<30。

离场

  • 空头交叉、RSI>80,或MACD不高于信号线且RSI>70时退出。

Python

共 187 行。运行方式: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 脚本(v5)

此 Pine 版本暂无适用于当前脚本的 TradingView 编译记录。本站回测规则以 Python 为准。

//@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()

打开 TradingView 运行这个脚本推广链接:我们可能获得佣金,你不会多花钱。

自己跑一遍

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

本示例使用当前行情和默认参数,不复现网站的滚动前推结果。策略证据下载包含归档源码,可回放已发布回测中记录的运算。重新计算策略决策需要精确的原始输入,这些输入可能不公开。组合默认使用声明的资产池(未声明时使用网站配置的市场);自定义代码和 CSV 保留资产顺序,仅使用各资产都有数据的日期,不填补缺失价格。请提供足够覆盖策略回看期和预热期的历史数据。

可自由使用和修改。按现状提供,仅供研究和学习。历史回测不代表未来收益,不构成投资建议。

更多策略源码

全部策略源码 →

订阅每周 Arena 周报

每周一封邮件:排名变化、新信号和新研究。不发垃圾邮件,随时可以退订。