1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import pandas as pd import talib import matplotlib.pyplot as plt # import yfinance as yf
# 安装必要库(若未安装) # !pip install TA-Lib yfinance matplotlib
# 加载示例数据(以苹果公司2024年数据为例) # df = yf.download("AAPL", start="2024-01-01", end="2025-06-23") # df = df[['Close']].rename(columns={'Close': 'close'})
# 计算14日RSI(默认参数) rsi_period = 14 df['rsi'] = talib.RSI(df['收盘'], timeperiod=rsi_period)
# 过滤初始无效数据(前14天无法计算RSI) valid_data = df.dropna() plt.figure(figsize=(16, 10)) gs = plt.GridSpec(2, 1, height_ratios=[3, 1])
# 主图:价格与RSI信号线 ax1 = plt.subplot(gs[0]) ax1.plot(valid_data['收盘'], label='Close Price', color='#1f77b4', linewidth=1.5) ax1.set_title(f'AAPL Price & RSI ({rsi_period}-day)', fontsize=14) ax1.legend(loc='upper left') ax1.grid(True, alpha=0.3)
# RSI副图 ax2 = plt.subplot(gs[1], sharex=ax1) ax2.plot(valid_data['rsi'], label='RSI', color='purple', linewidth=1.2)
# 超买超卖区域填充 ax2.fill_between(valid_data.index, 70, valid_data['rsi'], where=(valid_data['rsi'] >=70), facecolor='red', alpha=0.2, interpolate=True) ax2.fill_between(valid_data.index, 30, valid_data['rsi'], where=(valid_data['rsi'] <=30), facecolor='green', alpha=0.2, interpolate=True)
# 水平参考线 ax2.axhline(70, color='darkred', linestyle='--', alpha=0.7) ax2.axhline(30, color='darkgreen', linestyle='--', alpha=0.7)
# 坐标轴优化 ax2.set_ylim(0, 100) ax2.set_yticks([30, 50, 70]) ax2.grid(True, alpha=0.3) ax2.set_ylabel('RSI', fontsize=10)
plt.tight_layout() plt.show()
|