使用Matplotlib绘制RSI相对强弱指标详解与实战案例分享

引言:什么是RSI相对强弱指标?
RSI(Relative Strength Index,相对强弱指标)是技术分析中最受欢迎的动量振荡器之一,由J. Welles Wilder在1978年提出。它衡量价格变动的速度和变化幅度,帮助交易者识别超买和超卖条件,以及潜在的趋势反转点。
RSI的核心价值在于:
动量测量
:显示价格变动的强度,当价格上涨但动量减弱时,可能预示趋势即将反转
超买/超卖识别
:通常70以上为超买区域,30以下为超卖区域
背离检测
:价格与指标之间的背离是重要的反转信号
支撑/阻力
:RSI在趋势中常在50附近形成支撑或阻力
本文将详细讲解如何使用Python的Matplotlib库绘制RSI指标,并通过完整的实战案例展示如何在实际交易分析中应用它。
RSI的计算原理
RSI计算公式详解
RSI的计算基于以下步骤:
计算价格变化
:比较连续两天的收盘价
分离涨跌
:将正变化和负变化分别归入”平均涨幅”和”平均跌幅”
计算相对强度(RS)
:RS = 平均涨幅 / 平均跌幅
计算RSI
:RSI = 100 – (100 / (1 + RS))
标准周期通常为14天,但可根据交易策略调整。
Python实现RSI计算
以下是使用pandas实现RSI计算的完整代码:
import pandas as pd
import numpy as np

def calculate_rsi(data, period=14):
“””
计算RSI指标

参数:
data: 包含’close’列的DataFrame
period: RSI计算周期

返回:
带有’rsi’列的DataFrame
“””
# 计算价格变化
delta = data[‘close’].diff()

# 分离涨跌
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0) # 计算平均涨幅和平均跌幅(使用Wilder平滑) avg_gain = gain.ewm(alpha=1/period, adjust=False).mean() avg_loss = loss.ewm(alpha=1/period, adjust=False).mean() # 计算相对强度(RS) rs = avg_gain / avg_loss # 计算RSI data['rsi'] = 100 - (100 / (1 + rs)) return data 使用Matplotlib绘制RSI指标 基础RSI图表绘制 首先,我们需要创建一个基础的RSI图表,包括RSI线、超买/超卖水平线和价格图表。 import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.dates import DateFormatter import yfinance as yf import pandas as pd import numpy as np def plot_rsi(data, title="RSI指标分析", figsize=(14, 8)): """ 使用Matplotlib绘制RSI指标图表 参数: data: 包含'close'和'rsi'列的DataFrame title: 图表标题 figsize: 图表大小 """ # 设置中文字体(如果系统支持) plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False # 创建图表和子图 fig, (ax1, ax2) = plt.subplots(2, 1, figsize=figsize, gridspec_kw={'height_ratios': [2, 1]}, sharex=True) # 绘制价格图表(主图) ax1.plot(data.index, data['close'], label='收盘价', linewidth=1.5, color='#1f77b4') ax1.set_ylabel('价格', fontsize=12) ax1.set_title(title, fontsize=14, fontweight='bold') ax1.grid(True, alpha=0.3) ax1.legend(loc='upper left') # 绘制RSI图表 ax2.plot(data.index, data['rsi'], label='RSI', linewidth=1.5, color='#ff7f0e') # 添加超买/超卖水平线 ax2.axhline(70, color='red', linestyle='--', alpha=0.7, label='超买线(70)') ax2.axhline(30, color='green', linestyle='--', alpha=0.7, label='超卖线(30)') ax2.axhline(50, color='gray', linestyle=':', alpha=0.5, label='中线(50)') # 填充超买/超卖区域 ax2.axhspan(70, 100, alpha=0.1, color='red') ax2.axhspan(0, 30, alpha=0.1, color='green') # 设置RSI轴范围和标签 ax2.set_ylabel('RSI值', fontsize=12) ax2.set_ylim(0, 100) ax2.set_xlabel('日期', fontsize=12) # 添加图例 ax2.legend(loc='upper left', ncol=2) # 优化日期显示 date_format = DateFormatter('%Y-%m-%d') ax2.xaxis.set_major_formatter(date_format) plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45, ha='right') # 调整布局 plt.tight_layout() return fig, (ax1, ax2) # 示例:使用yfinance获取数据并绘制 def demo_basic_rsi(): """基础RSI绘图示例""" # 获取苹果公司股票数据 data = yf.download('AAPL', start='2023-01-01', end='2023-12-31') data = data[['Close']].rename(columns={'Close': 'close'}) # 计算RSI data = calculate_rsi(data) # 绘制图表 plot_rsi(data, title="AAPL 2023年RSI指标分析") plt.show() # 运行示例 # demo_basic_rsi() 高级RSI图表功能 在实际交易分析中,我们经常需要添加更多功能,如交易信号标记、移动平均线等。以下是增强版的RSI绘图函数: def plot_rsi_advanced(data, signals=None, title="高级RSI分析", figsize=(16, 10)): """ 高级RSI绘图函数,支持信号标记 参数: data: 包含'close'和'rsi'列的DataFrame signals: 信号DataFrame,包含'buy'和'sell'列 title: 图表标题 figsize: 图表大小 """ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=figsize, gridspec_kw={'height_ratios': [2, 1]}, sharex=True) # 主图:价格和交易信号 ax1.plot(data.index, data['close'], label='收盘价', linewidth=1.5, color='#1f77b4') # 如果有信号数据,标记买卖点 if signals is not None: buy_signals = signals[signals['buy'] == True] sell_signals = signals[signals['sell'] == True] ax1.scatter(buy_signals.index, data.loc[buy_signals.index, 'close'], color='green', marker='^', s=100, label='买入信号', zorder=5) ax1.scatter(sell_signals.index, data.loc[sell_signals.index, 'close'], color='red', marker='v', s=100, label='卖出信号', zorder=5) ax1.set_ylabel('价格', fontsize=12) ax1.set_title(title, fontsize=14, fontweight='bold') ax1.grid(True, alpha=0.3) ax1.legend(loc='upper left') # RSI图 ax2.plot(data.index, data['rsi'], label='RSI', linewidth=1.5, color='#ff7f0e') # 超买/超卖区域 ax2.axhline(70, color='red', linestyle='--', alpha=0.7, label='超买线(70)') ax2.axhline(30, color='green', linestyle='--', alpha=0.7, label='超卖线(30)') ax2.axhline(50, color='gray', linestyle=':', alpha=0.5, label='中线(50)') # 填充区域 ax2.axhspan(70, 100, alpha=0.1, color='red') ax2.axhspan(0, 30, alpha=0.1, color='green') # 如果有信号,也在RSI上标记 if signals is not None: buy_rsi = data.loc[buy_signals.index, 'rsi'] sell_rsi = data.loc[sell_signals.index, 'rsi'] ax2.scatter(buy_signals.index, buy_rsi, color='green', marker='^', s=80, zorder=5) ax2.scatter(sell_signals.index, sell_rsi, color='red', marker='v', s=80, zorder=5) ax2.set_ylabel('RSI值', fontsize=12) ax2.set_ylim(0, 100) ax2.set_xlabel('日期', fontsize=12) ax2.legend(loc='upper left', ncol=2) # 日期格式化 date_format = DateFormatter('%Y-%m-%d') ax2.xaxis.set_major_formatter(date_format) plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45, ha='right') plt.tight_layout() return fig, (ax1, ax2) 实战案例:基于RSI的交易策略 案例1:超买超卖反转策略 这是一个经典的RSI策略:当RSI进入超卖区域(<30)后返回30以上时买入,当RSI进入超买区域(>70)后返回70以下时卖出。
def rsi_reversal_strategy(data, rsi_period=14, overbought=70, oversold=30):
“””
RSI超买超卖反转策略

策略逻辑:
– 买入信号: RSI从低于oversold上升到高于oversold
– 卖出信号: RSI从高于overbought下降到低于overbought
“””
# 确保已计算RSI
if ‘rsi’ not in data.columns:
data = calculate_rsi(data, period=rsi_period)

# 初始化信号列
data[‘buy’] = False
data[‘sell’] = False

# 生成信号
for i in range(1, len(data)):
# 买入信号:RSI从超卖区域回升
if (data[‘rsi’].iloc[i-1] < oversold) and (data['rsi'].iloc[i] >= oversold):
data.loc[data.index[i], ‘buy’] = True

# 卖出信号:RSI从超买区域回落
if (data[‘rsi’].iloc[i-1] > overbought) and (data[‘rsi’].iloc[i] <= overbought): data.loc[data.index[i], 'sell'] = True return data # 完整实战示例 def demo_reversal_strategy(): """超买超卖反转策略实战""" # 获取数据 data = yf.download('TSLA', start='2023-01-01', end='2023-12-31') data = data[['Close']].rename(columns={'Close': 'close'}) # 计算RSI并生成信号 data = rsi_reversal_strategy(data) # 绘制图表 plot_rsi_advanced(data, signals=data[['buy', 'sell']], title="TSLA 2023年RSI超买超卖反转策略") plt.show() # 打印信号统计 print(f"买入信号数量: {data['buy'].sum()}") print(f"卖出信号数量: {data['sell'].sum()}") return data # 运行策略示例 # demo_reversal_strategy() 案例2:RSI背离检测策略 RSI背离是重要的反转信号。当价格创新高但RSI未创新高(看跌背离),或价格创新低但RSI未创新低(看涨背离)时,可能预示趋势反转。 def detect_rsi_divergence(data, window=5, min_price_change=0.02): """ 检测RSI背离 参数: data: 包含'close'和'rsi'列的DataFrame window: 用于识别局部极值的窗口大小 min_price_change: 最小价格变化百分比 返回: 带有背离信号的DataFrame """ # 初始化背离列 data['bullish_divergence'] = False # 看涨背离(价格新低,RSI未新低) data['bearish_divergence'] = False # 看跌背离(价格新高,RSI未新高) # 找到局部极值点 price = data['close'].values rsi = data['rsi'].values # 使用滚动窗口找局部极值 for i in range(window, len(data) - window): # 检查是否为局部低点 if (price[i] == min(price[i-window:i+window+1]) and rsi[i] != min(rsi[i-window:i+window+1])): # 检查是否有更低的价格但更高的RSI lower_prices = price[i-window:i+window+1] < price[i] higher_rsi = rsi[i-window:i+window+1] > rsi[i]

if any(lower_prices & higher_rsi):
data.loc[data.index[i], ‘bullish_divergence’] = True

# 检查是否为局部高点
if (price[i] == max(price[i-window:i+window+1]) and
rsi[i] != max(rsi[i-window:i+window+1])):
# 检查是否有更高的价格但更低的RSI
higher_prices = price[i-window:i+window+1] > price[i]
lower_rsi = rsi[i-window:i+window+1] < rsi[i] if any(higher_prices & lower_rsi): data.loc[data.index[i], 'bearish_divergence'] = True return data def plot_rsi_with_divergence(data, title="RSI背离分析"): """ 绘制带背离标记的RSI图表 """ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10), gridspec_kw={'height_ratios': [2, 1]}, sharex=True) # 价格图 ax1.plot(data.index, data['close'], label='收盘价', linewidth=1.5, color='#1f77b4') # 标记看涨背离(绿色向上箭头) bullish = data[data['bullish_divergence'] == True] if not bullish.empty: ax1.scatter(bullish.index, bullish['close'], color='green', marker='^', s=150, label='看涨背离', zorder=5, edgecolors='black') # 标记看跌背离(红色向下箭头) bearish = data[data['bearish_divergence'] == True] if not bearish.empty: ax1.scatter(bearish.index, bearish['close'], color='red', marker='v', s=150, label='看跌背离', zorder=5, edgecolors='black') ax1.set_ylabel('价格', fontsize=12) ax1.set_title(title, fontsize=14, fontweight='bold') ax1.grid(True, alpha=0.3) ax1.legend(loc='upper left') # RSI图 ax2.plot(data.index, data['rsi'], label='RSI', linewidth=1.5, color='#ff7f0e') # 超买超卖线 ax2.axhline(70, color='red', linestyle='--', alpha=0.7) ax2.axhline(30, color='green', linestyle='--', alpha=0.7) ax2.axhline(50, color='gray', linestyle=':', alpha=0.5) # 标记背离点 if not bullish.empty: ax2.scatter(bullish.index, bullish['rsi'], color='green', marker='^', s=100, zorder=5, edgecolors='black') if not bearish.empty: ax2.scatter(bearish.index, bearish['rsi'], color='red', marker='v', s=100, zorder=5, edgecolors='black') ax2.set_ylabel('RSI值', fontsize=12) ax2.set_ylim(0, 100) ax2.set_xlabel('日期', fontsize=12) ax2.legend(loc='upper left') # 日期格式化 date_format = DateFormatter('%Y-%m-%d') ax2.xaxis.set_major_formatter(date_format) plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45, ha='right') plt.tight_layout() return fig, (ax1, ax2) # 背离策略实战 def demo_divergence_strategy(): """RSI背离策略实战""" # 获取比特币数据 data = yf.download('BTC-USD', start='2023-01-01', end='2023-12-31') data = data[['Close']].rename(columns={'Close': 'close'}) # 计算RSI data = calculate_rsi(data) # 检测背离 data = detect_rsi_divergence(data) # 绘制图表 plot_rsi_with_divergence(data, title="BTC 2023年RSI背离分析") plt.show() # 统计背离次数 print(f"看涨背离次数: {data['bullish_divergence'].sum()}") print(f"看跌背离次数: {data['bearish_divergence'].sum()}") return data # 运行背离策略示例 # demo_divergence_strategy() 案例3:RSI与移动平均线结合策略 将RSI与移动平均线结合可以过滤假信号,提高策略的可靠性。 def rsi_ma_strategy(data, rsi_period=14, ma_period=50, rsi_threshold=50): """ RSI与移动平均线结合策略 策略逻辑: - 只在价格高于MA50时考虑RSI超卖买入 - 只在价格低于MA50时考虑RSI超买卖出 """ # 计算RSI data = calculate_rsi(data, period=rsi_period) # 计算移动平均线 data['ma50'] = data['close'].rolling(window=ma_period).mean() # 初始化信号 data['buy'] = False data['sell'] = False # 生成信号 for i in range(1, len(data)): # 买入条件:价格在MA50上方,且RSI从超卖回升 if (data['close'].iloc[i] > data[‘ma50’].iloc[i] and
data[‘rsi’].iloc[i-1] < 30 and data['rsi'].iloc[i] >= 30):
data.loc[data.index[i], ‘buy’] = True

# 卖出条件:价格在MA50下方,且RSI从超买回落
if (data[‘close’].iloc[i] < data['ma50'].iloc[i] and data['rsi'].iloc[i-1] > 70 and data[‘rsi’].iloc[i] <= 70): data.loc[data.index[i], 'sell'] = True return data def plot_rsi_ma_strategy(data, title="RSI+MA50复合策略"): """ 绘制RSI+MA复合策略图表 """ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10), gridspec_kw={'height_ratios': [2, 1]}, sharex=True) # 价格图 ax1.plot(data.index, data['close'], label='收盘价', linewidth=1.5, color='#1f77b4') ax1.plot(data.index, data['ma50'], label='MA50', linewidth=1.5, color='orange', alpha=0.8) # 标记买卖信号 buy_signals = data[data['buy'] == True] sell_signals = data[data['sell'] == True] ax1.scatter(buy_signals.index, buy_signals['close'], color='green', marker='^', s=120, label='买入', zorder=5, edgecolors='black') ax1.scatter(sell_signals.index, sell_signals['close'], color='red', marker='v', s=120, label='卖出', zorder=5, edgecolors='black') ax1.set_ylabel('价格', fontsize=12) ax1.set_title(title, fontsize=14, fontweight='bold') ax1.grid(True, alpha=0.3) ax1.legend(loc='upper left') # RSI图 ax2.plot(data.index, data['rsi'], label='RSI', linewidth=1.5, color='#ff7f0e') ax2.axhline(70, color='red', linestyle='--', alpha=0.7, label='超买线') ax2.axhline(30, color='green', linestyle='--', alpha=0.7, label='超卖线') ax2.axhline(50, color='gray', linestyle=':', alpha=0.5, label='中线') # 标记RSI信号点 ax2.scatter(buy_signals.index, buy_signals['rsi'], color='green', marker='^', s=80, zorder=5, edgecolors='black') ax2.scatter(sell_signals.index, sell_signals['rsi'], color='red', marker='v', s=80, zorder=5, edgecolors='black') ax2.set_ylabel('RSI值', fontsize=12) ax2.set_ylim(0, 100) ax2.set_xlabel('日期', fontsize=12) ax2.legend(loc='upper left', ncol=2) # 日期格式化 date_format = DateFormatter('%Y-%m-%d') ax2.xaxis.set_major_formatter(date_format) plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45, ha='right') plt.tight_layout() return fig, (ax1, ax2) # 复合策略实战 def demo_rsi_ma_strategy(): """RSI+MA复合策略实战""" # 获取SP500 ETF数据 data = yf.download('SPY', start='2023-01-01', end='2023-12-31') data = data[['Close']].rename(columns={'Close': 'close'}) # 应用策略 data = rsi_ma_strategy(data) # 绘制图表 plot_rsi_ma_strategy(data, title="SPY 2023年RSI+MA50复合策略") plt.show() # 信号统计 print(f"买入信号: {data['buy'].sum()}") print(f"卖出信号: {data['sell'].sum()}") return data # 运行复合策略示例 # demo_rsi_ma_strategy() RSI指标的高级应用技巧 1. RSI的形态分析 RSI图表本身也会形成类似价格的形态,如头肩顶/底、三角形等,这些形态可以提供额外的交易信号。 def detect_rsi_patterns(data): """ 检测RSI中的简单形态(双顶/双底) """ data['rsi_double_top'] = False data['rsi_double_bottom'] = false rsi = data['rsi'].values for i in range(2, len(data)-2): # 双顶形态:两个相近的高点,中间有回调 if (rsi[i-1] > 75 and rsi[i] < rsi[i-1] and rsi[i+1] > rsi[i] and
abs(rsi[i+1] – rsi[i-1]) < 3 and rsi[i+2] < rsi[i+1]): data.loc[data.index[i+1], 'rsi_double_top'] = True # 双底形态:两个相近的低点,中间有反弹 if (rsi[i-1] < 25 and rsi[i] > rsi[i-1] and rsi[i+1] < rsi[i] and abs(rsi[i+1] - rsi[i-1]) < 3 and rsi[i+2] > rsi[i+1]):
data.loc[data.index[i+1], ‘rsi_double_bottom’] = True

return data
2. RSI的周期调整
不同市场和时间框架需要不同的RSI周期:
def adaptive_rsi_strategy(data, base_period=14):
“””
自适应RSI策略:根据波动率调整RSI周期
“””
# 计算波动率(标准差)
data[‘volatility’] = data[‘close’].rolling(window=20).std()

# 根据波动率调整RSI周期
data[‘adjusted_period’] = base_period
data.loc[data[‘volatility’] > data[‘volatility’].quantile(0.75), ‘adjusted_period’] = base_period + 5
data.loc[data[‘volatility’] < data['volatility'].quantile(0.25), 'adjusted_period'] = base_period - 5 # 计算自适应RSI data['rsi_adaptive'] = np.nan for i in range(len(data)): if not pd.isna(data['adjusted_period'].iloc[i]): period = int(data['adjusted_period'].iloc[i]) if i >= period:
# 计算该点的RSI
subset = data.iloc[i-period:i+1]
data.loc[data.index[i], ‘rsi_adaptive’] = calculate_rsi(subset, period)[‘rsi’].iloc[-1]

return data
3. RSI与其他指标的组合
def multi_indicator_strategy(data):
“””
多指标组合:RSI + MACD + Bollinger Bands
“””
# RSI
data = calculate_rsi(data)

# MACD(简化版)
data[’ema12′] = data[‘close’].ewm(span=12).mean()
data[’ema26′] = data[‘close’].ewm(span=26).mean()
data[‘macd’] = data[’ema12′] – data[’ema26′]
data[‘macd_signal’] = data[‘macd’].ewm(span=9).mean()

# 布林带
data[‘ma20’] = data[‘close’].rolling(window=20).mean()
data[‘std20’] = data[‘close’].rolling(window=20).std()
data[‘upper_band’] = data[‘ma20’] + 2 * data[‘std20’]
data[‘lower_band’] = data[‘ma20’] – 2 * data[‘std20’]

# 复合信号
data[‘buy’] = False
data[‘sell’] = False

# 买入:RSI超卖 + MACD金叉 + 价格触及下轨
data.loc[(data[‘rsi’] < 30) & (data['macd'] > data[‘macd_signal’]) &
(data[‘close’] <= data['lower_band']), 'buy'] = True # 卖出:RSI超买 + MACD死叉 + 价格触及上轨 data.loc[(data['rsi'] > 70) &
(data[‘macd’] < data['macd_signal']) & (data['close'] >= data[‘upper_band’]), ‘sell’] = True

return data
RSI指标的局限性与注意事项
1. 强趋势中的失效问题
在强趋势中,RSI可能长期停留在超买或超卖区域,导致过早离场或错过机会。
解决方案
:
结合趋势指标(如MA)使用
调整超买/超卖阈值(如80/20)
使用RSI的斜率而非绝对值
def rsi_trend_filter(data, trend_period=50):
“””
使用趋势过滤器优化RSI信号
“””
data[‘trend’] = data[‘close’].rolling(trend_period).mean()
data[‘rsi_slope’] = data[‘rsi’].diff(5) # 5日斜率

# 只在上升趋势中做多,下降趋势中做空
data[‘buy’] = False
data[‘sell’] = False

# 上升趋势:价格在MA上方
uptrend = data[‘close’] > data[‘trend’]
downtrend = data[‘close’] < data['trend'] # 买入信号:上升趋势 + RSI超卖 + RSI斜率向上 data.loc[uptrend & (data['rsi'] < 30) & (data['rsi_slope'] > 0), ‘buy’] = True

# 卖出信号:下降趋势 + RSI超买 + RSI斜率向下
data.loc[downtrend & (data[‘rsi’] > 70) & (data[‘rsi_slope’] < 0), 'sell'] = True return data 2. 假突破问题 RSI信号可能在价格小幅波动时频繁触发,导致过度交易。 解决方案 : 增加信号确认条件 使用RSI的”区域”而非单点 结合成交量分析 def rsi_with_volume_filter(data, volume_threshold=1.2): """ RSI + 成交量过滤 """ # 计算平均成交量 data['avg_volume'] = data['volume'].rolling(20).mean() # RSI信号 data = calculate_rsi(data) data['buy'] = False data['sell'] = False # 信号需要成交量确认 for i in range(1, len(data)): # 买入:RSI超卖 + 成交量放大 if (data['rsi'].iloc[i-1] < 30 and data['rsi'].iloc[i] >= 30 and
data[‘volume’].iloc[i] > data[‘avg_volume’].iloc[i] * volume_threshold):
data.loc[data.index[i], ‘buy’] = True

# 卖出:RSI超买 + 成交量放大
if (data[‘rsi’].iloc[i-1] > 70 and data[‘rsi’].iloc[i] <= 70 and data['volume'].iloc[i] > data[‘avg_volume’].iloc[i] * volume_threshold):
data.loc[data.index[i], ‘sell’] = True

return data
3. 参数优化与回测
在实际应用前,必须进行参数优化和回测:
def backtest_rsi_strategy(data, initial_capital=10000, commission=0.001):
“””
RSI策略回测框架

参数:
data: 带有buy/sell信号的DataFrame
initial_capital: 初始资金
commission: 交易手续费率
“””
capital = initial_capital
position = 0 # 持仓数量
trades = []

for i in range(len(data)):
current_price = data[‘close’].iloc[i]

# 买入信号
if data[‘buy’].iloc[i] and capital > 0:
shares = capital // current_price
if shares > 0:
cost = shares * current_price * (1 + commission)
if cost <= capital: position = shares capital -= cost trades.append({ 'date': data.index[i], 'action': 'BUY', 'price': current_price, 'shares': shares, 'capital': capital, 'position': position }) # 卖出信号 elif data['sell'].iloc[i] and position > 0:
revenue = position * current_price * (1 – commission)
capital = revenue
trades.append({
‘date’: data.index[i],
‘action’: ‘SELL’,
‘price’: current_price,
‘shares’: position,
‘capital’: capital,
‘position’: 0
})
position = 0

# 计算最终收益
final_value = capital + (position * data[‘close’].iloc[-1] if position > 0 else 0)
total_return = (final_value – initial_capital) / initial_capital * 100

print(f”初始资金: ${initial_capital:,.2f}”)
print(f”最终价值: ${final_value:,.2f}”)
print(f”总收益率: {total_return:.2f}%”)
print(f”交易次数: {len(trades)}”)

return trades, final_value

# 回测示例
def demo_backtest():
“””回测示例”””
data = yf.download(‘AAPL’, start=’2022-01-01′, end=’2023-12-31′)
data = data[[‘Close’, ‘Volume’]].rename(columns={‘Close’: ‘close’, ‘Volume’: ‘volume’})

# 应用策略
data = rsi_reversal_strategy(data)

# 回测
trades, final_value = backtest_rsi_strategy(data)

# 绘制权益曲线
capital_series = [initial_capital]
for trade in trades:
capital_series.append(trade[‘capital’])

plt.figure(figsize=(12, 6))
plt.plot(range(len(capital_series)), capital_series, linewidth=2, color=’#1f77b4′)
plt.title(‘策略权益曲线’, fontsize=14, fontweight=’bold’)
plt.xlabel(‘交易次数’, fontsize=12)
plt.ylabel(‘资金 ($)’, fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

# 运行回测
# demo_backtest()
总结
RSI相对强弱指标是一个强大而灵活的技术分析工具,但其有效性取决于正确使用和适当组合。通过Matplotlib绘制RSI图表,我们可以直观地分析市场状态,识别交易机会。
关键要点
:
基础计算
:理解RSI的计算原理是正确应用的前提
可视化
:使用Matplotlib创建清晰的RSI图表,包含超买超卖线、信号标记等
策略开发
:从简单的超买超卖反转到复杂的多指标组合,RSI可以适应多种交易风格
风险控制
:始终结合趋势过滤、成交量确认等机制,避免假信号
回测验证
:任何策略都必须经过严格回测,确保其在历史数据上的有效性
最佳实践
:
不要单独依赖RSI,至少结合一个趋势指标
根据市场波动率调整RSI周期和阈值
在强趋势市场中,优先考虑RSI的斜率而非绝对值
始终设置止损,控制单笔交易风险
通过本文提供的完整代码和实战案例,你应该能够独立实现RSI指标的计算、可视化和策略开发。记住,技术分析是艺术与科学的结合,持续学习和实践是提高的关键。