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 53 54 55 56
| import pandas as pd import talib import matplotlib.pyplot as plt import mplfinance as mpf
# 假设df是包含日期索引和收盘价的DataFrame # 示例数据加载(若需要真实数据可替换为yfinance获取) # df = pd.read_csv('stock_data.csv', index_col='Date', parse_dates=True) close = df['收盘']
# 使用TA-Lib计算布林带 period = 20 std_dev = 2 upper, middle, lower = talib.BBANDS( close.values, timeperiod=period, nbdevup=std_dev, nbdevdn=std_dev, matype=0 # 0=SMA,1=EMA等 )
# 将结果存入DataFrame df['Upper'] = upper df['Middle'] = middle df['Lower'] = lower
# 过滤无效数据 valid_data = df.dropna() plt.figure(figsize=(14, 7)) plt.title(f'{df.columns[0]} Price with Bollinger Bands ({period} days, {std_dev}σ)', fontsize=14)
# 绘制收盘价曲线 plt.plot(valid_data.index, valid_data['收盘'], label='Close Price', color='#1f77b4', linewidth=1.2)
# 绘制布林带 plt.plot(valid_data.index, valid_data['Upper'], label='Upper Band', color='red', linestyle='--', linewidth=1) plt.plot(valid_data.index, valid_data['Middle'], label='Middle Band', color='orange', linewidth=1.5) plt.plot(valid_data.index, valid_data['Lower'], label='Lower Band', color='green', linestyle='--', linewidth=1)
# 填充布林带区域增强可视化 plt.fill_between(valid_data.index, valid_data['Upper'], valid_data['Lower'], color='gray', alpha=0.1)
# 添加辅助元素 plt.xlabel('Date', fontsize=12) plt.ylabel('Price', fontsize=12) plt.grid(True, alpha=0.3) plt.legend(loc='upper left', fontsize=10) plt.tight_layout() plt.show()
|