2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
股票K线图查看器
|
|
|
|
|
|
从MySQL数据库读取股票K线数据并绘制专业K线图
|
|
|
|
|
|
|
|
|
|
|
|
主要功能:
|
|
|
|
|
|
1. 连接MySQL数据库
|
|
|
|
|
|
2. 读取股票OHLCV数据
|
|
|
|
|
|
3. 绘制专业K线图
|
|
|
|
|
|
4. 支持多时间周期查看
|
|
|
|
|
|
|
|
|
|
|
|
数据库配置来源: database_config.py
|
|
|
|
|
|
数据模型来源: stock_models.py
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import pandas as pd
|
|
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
from matplotlib.patches import Rectangle
|
|
|
|
|
|
from matplotlib.ticker import FuncFormatter
|
|
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
|
import logging
|
|
|
|
|
|
import os
|
2025-07-23 10:48:32 +08:00
|
|
|
|
import numpy as np
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
# 导入数据库相关模块
|
|
|
|
|
|
from database_config import init_database, close_database, get_database
|
|
|
|
|
|
|
|
|
|
|
|
# 配置日志
|
|
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 设置matplotlib为交互式模式,支持放大缩小和移动
|
|
|
|
|
|
plt.ion() # 开启交互模式
|
2025-07-22 20:19:06 +08:00
|
|
|
|
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 中文字体
|
|
|
|
|
|
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class StockKlineViewer:
|
|
|
|
|
|
"""
|
|
|
|
|
|
股票K线图查看器类
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
"""
|
|
|
|
|
|
初始化K线图查看器
|
|
|
|
|
|
"""
|
|
|
|
|
|
self.db = None
|
|
|
|
|
|
self.is_connected = False
|
|
|
|
|
|
|
|
|
|
|
|
def connect_database(self):
|
|
|
|
|
|
"""
|
|
|
|
|
|
连接数据库
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
bool: 连接成功返回True,失败返回False
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
logger.info("🔗 正在连接数据库...")
|
|
|
|
|
|
success = init_database()
|
|
|
|
|
|
if success:
|
|
|
|
|
|
self.db = get_database()
|
|
|
|
|
|
self.is_connected = True
|
|
|
|
|
|
logger.info("✅ 数据库连接成功")
|
|
|
|
|
|
return True
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.error("❌ 数据库连接失败")
|
|
|
|
|
|
return False
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 数据库连接异常: {e}")
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def disconnect_database(self):
|
|
|
|
|
|
"""
|
|
|
|
|
|
断开数据库连接
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
if self.is_connected:
|
|
|
|
|
|
close_database()
|
|
|
|
|
|
self.is_connected = False
|
|
|
|
|
|
logger.info("🔒 数据库连接已关闭")
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 关闭数据库连接异常: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
def read_stock_data(self, stock_code, period, start_date, end_date):
|
|
|
|
|
|
"""
|
|
|
|
|
|
从数据库读取股票K线数据
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 股票代码,如 "601658.SH"
|
|
|
|
|
|
period (str): 数据周期,如 "1m", "5m", "1d"
|
|
|
|
|
|
start_date (str): 开始日期,格式 "YYYYMMDD"
|
|
|
|
|
|
end_date (str): 结束日期,格式 "YYYYMMDD"
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
pd.DataFrame: 包含OHLCV数据的DataFrame,按时间排序
|
|
|
|
|
|
列包括:time, open, high, low, close, volume, amount
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not self.is_connected:
|
|
|
|
|
|
logger.error("❌ 数据库未连接")
|
|
|
|
|
|
return pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
logger.info(f"📊 正在从数据库读取 {stock_code} 的 {period} 数据...")
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
# 生成表名(不创建表,只是获取表名)
|
|
|
|
|
|
clean_code = stock_code.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
|
|
|
|
|
clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower()
|
|
|
|
|
|
table_name = f"kline_{clean_code}_{clean_period}"
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
# 转换日期格式用于查询
|
|
|
|
|
|
start_datetime = datetime.strptime(start_date, "%Y%m%d")
|
|
|
|
|
|
end_datetime = datetime.strptime(end_date, "%Y%m%d") + timedelta(days=1) # 包含结束日期
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
# 直接使用SQL查询,避免创建表
|
|
|
|
|
|
sql = f"""
|
|
|
|
|
|
SELECT timestamp, open_price, high_price, low_price, close_price, volume, amount
|
|
|
|
|
|
FROM {table_name}
|
|
|
|
|
|
WHERE timestamp >= %s AND timestamp < %s
|
|
|
|
|
|
ORDER BY timestamp
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
cursor = self.db.execute_sql(sql, (start_datetime, end_datetime))
|
|
|
|
|
|
results = cursor.fetchall()
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
# 转换为DataFrame
|
|
|
|
|
|
data_list = []
|
2025-07-23 10:48:32 +08:00
|
|
|
|
for record in results:
|
2025-07-22 20:19:06 +08:00
|
|
|
|
data_list.append({
|
2025-07-23 10:48:32 +08:00
|
|
|
|
'time': record[0], # timestamp
|
|
|
|
|
|
'open': float(record[1]), # open_price
|
|
|
|
|
|
'high': float(record[2]), # high_price
|
|
|
|
|
|
'low': float(record[3]), # low_price
|
|
|
|
|
|
'close': float(record[4]), # close_price
|
|
|
|
|
|
'volume': int(record[5]), # volume
|
|
|
|
|
|
'amount': float(record[6]) # amount
|
2025-07-22 20:19:06 +08:00
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
df = pd.DataFrame(data_list)
|
|
|
|
|
|
|
|
|
|
|
|
if not df.empty:
|
|
|
|
|
|
df.set_index('time', inplace=True)
|
2025-07-22 22:42:43 +08:00
|
|
|
|
|
|
|
|
|
|
# 去除重复数据 - 保留第一条记录
|
|
|
|
|
|
original_len = len(df)
|
|
|
|
|
|
df = df[~df.index.duplicated(keep='first')]
|
|
|
|
|
|
|
|
|
|
|
|
if len(df) < original_len:
|
|
|
|
|
|
logger.info(f"🧹 检测到重复数据,已去重: {original_len} -> {len(df)} 条")
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
logger.info(f"✅ 成功读取 {len(df)} 条 {stock_code} 数据")
|
|
|
|
|
|
logger.info(f"📅 数据时间范围: {df.index.min()} ~ {df.index.max()}")
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.warning(f"⚠️ 未找到 {stock_code} 在指定时间范围内的数据")
|
2025-07-23 10:48:32 +08:00
|
|
|
|
logger.warning(f"💡 请确保表 {table_name} 存在且包含数据")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
return df
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 读取数据失败: {e}")
|
2025-07-23 10:48:32 +08:00
|
|
|
|
logger.error(f"💡 可能的原因: 表 {table_name} 不存在,请先运行 main.py 下载数据")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
import traceback
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
return pd.DataFrame()
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
def plot_kline_chart(self, df, stock_code, period, show_volume=True, show_macd=True, macd_params=None):
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
2025-07-22 22:42:43 +08:00
|
|
|
|
绘制可交互的K线图
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
df (pd.DataFrame): 包含OHLCV数据的DataFrame
|
|
|
|
|
|
stock_code (str): 股票代码
|
|
|
|
|
|
period (str): 数据周期
|
|
|
|
|
|
show_volume (bool): 是否显示成交量,默认True
|
2025-07-23 10:48:32 +08:00
|
|
|
|
show_macd (bool): 是否显示MACD指标,默认True
|
|
|
|
|
|
macd_params (dict): MACD参数设置,格式如下:
|
|
|
|
|
|
{
|
|
|
|
|
|
'fast_period': 12, # 快速EMA周期
|
|
|
|
|
|
'slow_period': 26, # 慢速EMA周期
|
|
|
|
|
|
'signal_period': 9 # 信号线周期
|
|
|
|
|
|
}
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
bool: 绘制成功返回True,失败返回False
|
|
|
|
|
|
"""
|
|
|
|
|
|
if df.empty:
|
|
|
|
|
|
logger.error("❌ 数据为空,无法绘制K线图")
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
# 设置默认MACD参数
|
|
|
|
|
|
if macd_params is None:
|
|
|
|
|
|
macd_params = {
|
|
|
|
|
|
'fast_period': 12,
|
|
|
|
|
|
'slow_period': 26,
|
|
|
|
|
|
'signal_period': 9
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
try:
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 创建新的figure窗口
|
2025-07-23 10:48:32 +08:00
|
|
|
|
plt.figure(figsize=(16, 12))
|
2025-07-22 22:42:43 +08:00
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
# 创建图表布局
|
2025-07-23 10:48:32 +08:00
|
|
|
|
if show_volume and show_macd:
|
|
|
|
|
|
ax1 = plt.subplot(3, 1, 1) # K线图占上面50%
|
|
|
|
|
|
ax2 = plt.subplot(3, 1, 2) # 成交量图占中间25%
|
|
|
|
|
|
ax3 = plt.subplot(3, 1, 3) # MACD图占下面25%
|
|
|
|
|
|
plt.subplots_adjust(hspace=0.4) # 调整子图间距
|
|
|
|
|
|
elif show_volume:
|
2025-07-22 22:42:43 +08:00
|
|
|
|
ax1 = plt.subplot(2, 1, 1) # K线图占上面3/4
|
|
|
|
|
|
ax2 = plt.subplot(2, 1, 2) # 成交量图占下面1/4
|
2025-07-23 10:48:32 +08:00
|
|
|
|
plt.subplots_adjust(hspace=0.3)
|
|
|
|
|
|
elif show_macd:
|
|
|
|
|
|
ax1 = plt.subplot(2, 1, 1) # K线图占上面3/4
|
|
|
|
|
|
ax3 = plt.subplot(2, 1, 2) # MACD图占下面1/4
|
|
|
|
|
|
plt.subplots_adjust(hspace=0.3)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
else:
|
2025-07-22 22:42:43 +08:00
|
|
|
|
ax1 = plt.subplot(1, 1, 1)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
# 绘制K线图
|
|
|
|
|
|
self._plot_candlestick(ax1, df)
|
|
|
|
|
|
|
|
|
|
|
|
# 设置K线图标题和标签
|
2025-07-23 10:48:32 +08:00
|
|
|
|
title = f'{stock_code} K线图 ({period}周期) - 数据总数: {len(df)}条'
|
|
|
|
|
|
if show_macd:
|
|
|
|
|
|
title += f' | MACD({macd_params["fast_period"]},{macd_params["slow_period"]},{macd_params["signal_period"]})'
|
|
|
|
|
|
ax1.set_title(title, fontsize=16, fontweight='bold')
|
2025-07-22 20:19:06 +08:00
|
|
|
|
ax1.set_ylabel('价格 (元)', fontsize=12)
|
|
|
|
|
|
ax1.grid(True, alpha=0.3)
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制成交量柱状图
|
|
|
|
|
|
if show_volume:
|
|
|
|
|
|
self._plot_volume(ax2, df)
|
|
|
|
|
|
ax2.set_ylabel('成交量', fontsize=12)
|
|
|
|
|
|
ax2.grid(True, alpha=0.3)
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
# 绘制MACD指标
|
|
|
|
|
|
if show_macd:
|
|
|
|
|
|
if show_volume and show_macd:
|
|
|
|
|
|
self._plot_macd(ax3, df, macd_params)
|
|
|
|
|
|
elif show_macd and not show_volume:
|
|
|
|
|
|
self._plot_macd(ax3, df, macd_params)
|
|
|
|
|
|
ax3.set_ylabel('MACD', fontsize=12)
|
|
|
|
|
|
ax3.grid(True, alpha=0.3)
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
# 设置x轴时间格式
|
2025-07-23 10:48:32 +08:00
|
|
|
|
if show_volume and show_macd:
|
|
|
|
|
|
self._setup_time_axis(ax3, df.index) # 最下面的图设置时间轴
|
|
|
|
|
|
elif show_volume:
|
|
|
|
|
|
self._setup_time_axis(ax2, df.index)
|
|
|
|
|
|
elif show_macd:
|
|
|
|
|
|
self._setup_time_axis(ax3, df.index)
|
|
|
|
|
|
else:
|
|
|
|
|
|
self._setup_time_axis(ax1, df.index)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 启用工具栏和交互功能
|
2025-07-22 20:19:06 +08:00
|
|
|
|
plt.tight_layout()
|
|
|
|
|
|
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 显示交互式图表
|
|
|
|
|
|
logger.info("📈 K线图已显示,可以使用工具栏进行放大、缩小、移动等操作")
|
|
|
|
|
|
logger.info("💡 使用提示:")
|
|
|
|
|
|
logger.info(" - 🔍 放大镜工具:框选区域进行放大")
|
|
|
|
|
|
logger.info(" - ↔️ 移动工具:拖拽图表进行移动")
|
|
|
|
|
|
logger.info(" - 🏠 主页按钮:恢复到原始视图")
|
|
|
|
|
|
logger.info(" - ⬅️ 后退按钮:返回上一个视图")
|
2025-07-23 10:48:32 +08:00
|
|
|
|
if show_macd:
|
|
|
|
|
|
logger.info(f"📊 MACD参数: 快速EMA={macd_params['fast_period']}, 慢速EMA={macd_params['slow_period']}, 信号线={macd_params['signal_period']}")
|
2025-07-22 22:42:43 +08:00
|
|
|
|
|
|
|
|
|
|
plt.show(block=False) # 非阻塞显示,允许继续执行程序
|
|
|
|
|
|
|
|
|
|
|
|
# 等待用户交互
|
|
|
|
|
|
input("\n按回车键关闭图表窗口...")
|
|
|
|
|
|
plt.close()
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
logger.info("✅ K线图绘制完成")
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 绘制K线图失败: {e}")
|
|
|
|
|
|
import traceback
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def _plot_candlestick(self, ax, df):
|
|
|
|
|
|
"""
|
|
|
|
|
|
绘制蜡烛图(K线)
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
ax: matplotlib轴对象
|
|
|
|
|
|
df: 包含OHLC数据的DataFrame
|
|
|
|
|
|
"""
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 重置DataFrame索引,确保能正确遍历
|
|
|
|
|
|
df_reset = df.reset_index()
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 绘制每根K线
|
|
|
|
|
|
for i, row in df_reset.iterrows():
|
|
|
|
|
|
# 确定K线颜色 (红涨绿跌)
|
|
|
|
|
|
if row['close'] >= row['open']:
|
|
|
|
|
|
# 上涨K线 (红色)
|
|
|
|
|
|
color = 'red'
|
|
|
|
|
|
# K线实体
|
|
|
|
|
|
height = row['close'] - row['open']
|
|
|
|
|
|
body_bottom = row['open']
|
|
|
|
|
|
else:
|
|
|
|
|
|
# 下跌K线 (绿色)
|
|
|
|
|
|
color = 'green'
|
|
|
|
|
|
# K线实体
|
|
|
|
|
|
height = row['open'] - row['close']
|
|
|
|
|
|
body_bottom = row['close']
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制K线实体
|
|
|
|
|
|
if height > 0: # 有实体
|
|
|
|
|
|
ax.add_patch(Rectangle((i-0.3, body_bottom), 0.6, height,
|
|
|
|
|
|
facecolor=color, edgecolor=color, alpha=0.8))
|
|
|
|
|
|
else: # 十字星,实体高度为0
|
|
|
|
|
|
ax.plot([i-0.3, i+0.3], [row['open'], row['open']], color=color, linewidth=2)
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制上影线
|
|
|
|
|
|
if row['high'] > max(row['open'], row['close']):
|
|
|
|
|
|
ax.plot([i, i], [max(row['open'], row['close']), row['high']], color=color, linewidth=1)
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制下影线
|
|
|
|
|
|
if row['low'] < min(row['open'], row['close']):
|
|
|
|
|
|
ax.plot([i, i], [row['low'], min(row['open'], row['close'])], color=color, linewidth=1)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 设置坐标轴范围
|
|
|
|
|
|
ax.set_xlim(-0.5, len(df_reset)-0.5)
|
|
|
|
|
|
price_min = df['low'].min()
|
|
|
|
|
|
price_max = df['high'].max()
|
|
|
|
|
|
price_range = price_max - price_min
|
|
|
|
|
|
ax.set_ylim(price_min - price_range * 0.05, price_max + price_range * 0.05)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
def _plot_volume(self, ax, df):
|
|
|
|
|
|
"""
|
|
|
|
|
|
绘制成交量柱状图
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
ax: matplotlib轴对象
|
|
|
|
|
|
df: 包含成交量数据的DataFrame
|
|
|
|
|
|
"""
|
|
|
|
|
|
# 成交量颜色与K线一致
|
|
|
|
|
|
colors = ['red' if close >= open_price else 'green'
|
|
|
|
|
|
for close, open_price in zip(df['close'], df['open'])]
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制成交量柱状图
|
|
|
|
|
|
ax.bar(range(len(df)), df['volume'], color=colors, alpha=0.6)
|
|
|
|
|
|
|
|
|
|
|
|
# 格式化成交量显示
|
|
|
|
|
|
ax.yaxis.set_major_formatter(FuncFormatter(self._format_volume))
|
|
|
|
|
|
ax.set_xlim(-1, len(df))
|
|
|
|
|
|
|
|
|
|
|
|
def _format_volume(self, x, pos):
|
|
|
|
|
|
"""
|
|
|
|
|
|
格式化成交量显示(万、亿等)
|
|
|
|
|
|
"""
|
|
|
|
|
|
if x >= 100000000: # 亿
|
|
|
|
|
|
return f'{x/100000000:.1f}亿'
|
|
|
|
|
|
elif x >= 10000: # 万
|
|
|
|
|
|
return f'{x/10000:.1f}万'
|
|
|
|
|
|
else:
|
|
|
|
|
|
return f'{int(x)}'
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
def _calculate_macd(self, df, fast_period=12, slow_period=26, signal_period=9):
|
|
|
|
|
|
"""
|
|
|
|
|
|
计算MACD指标
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
df (pd.DataFrame): 包含收盘价的DataFrame
|
|
|
|
|
|
fast_period (int): 快速EMA周期,默认12
|
|
|
|
|
|
slow_period (int): 慢速EMA周期,默认26
|
|
|
|
|
|
signal_period (int): 信号线EMA周期,默认9
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
tuple: (macd_line, signal_line, histogram)
|
|
|
|
|
|
"""
|
|
|
|
|
|
# 计算快速和慢速EMA
|
|
|
|
|
|
close_prices = df['close']
|
|
|
|
|
|
|
|
|
|
|
|
# 计算EMA
|
|
|
|
|
|
fast_ema = close_prices.ewm(span=fast_period).mean()
|
|
|
|
|
|
slow_ema = close_prices.ewm(span=slow_period).mean()
|
|
|
|
|
|
|
|
|
|
|
|
# 计算MACD线
|
|
|
|
|
|
macd_line = fast_ema - slow_ema
|
|
|
|
|
|
|
|
|
|
|
|
# 计算信号线
|
|
|
|
|
|
signal_line = macd_line.ewm(span=signal_period).mean()
|
|
|
|
|
|
|
|
|
|
|
|
# 计算柱状图
|
|
|
|
|
|
histogram = macd_line - signal_line
|
|
|
|
|
|
|
|
|
|
|
|
return macd_line, signal_line, histogram
|
|
|
|
|
|
|
|
|
|
|
|
def _plot_macd(self, ax, df, macd_params=None):
|
|
|
|
|
|
"""
|
|
|
|
|
|
绘制MACD指标图
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
ax: matplotlib轴对象
|
|
|
|
|
|
df: 包含价格数据的DataFrame
|
|
|
|
|
|
macd_params (dict): MACD参数设置,如果为None则使用默认参数
|
|
|
|
|
|
"""
|
|
|
|
|
|
# 设置默认参数
|
|
|
|
|
|
if macd_params is None:
|
|
|
|
|
|
macd_params = {
|
|
|
|
|
|
'fast_period': 12,
|
|
|
|
|
|
'slow_period': 26,
|
|
|
|
|
|
'signal_period': 9
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 计算MACD指标
|
|
|
|
|
|
macd_line, signal_line, histogram = self._calculate_macd(
|
|
|
|
|
|
df,
|
|
|
|
|
|
macd_params['fast_period'],
|
|
|
|
|
|
macd_params['slow_period'],
|
|
|
|
|
|
macd_params['signal_period']
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 重置索引以便绘制
|
|
|
|
|
|
x_range = range(len(df))
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制MACD线
|
|
|
|
|
|
ax.plot(x_range, macd_line, label='MACD', color='blue', linewidth=1.5)
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制信号线
|
|
|
|
|
|
ax.plot(x_range, signal_line, label='Signal', color='red', linewidth=1.5)
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制MACD柱状图
|
|
|
|
|
|
colors = ['red' if h >= 0 else 'green' for h in histogram]
|
|
|
|
|
|
ax.bar(x_range, histogram, color=colors, alpha=0.6, width=0.8, label='Histogram')
|
|
|
|
|
|
|
|
|
|
|
|
# 添加零轴线
|
|
|
|
|
|
ax.axhline(y=0, color='black', linestyle='-', alpha=0.3)
|
|
|
|
|
|
|
|
|
|
|
|
# 设置图例 - 包含参数信息
|
|
|
|
|
|
legend_label = f"MACD({macd_params['fast_period']},{macd_params['slow_period']},{macd_params['signal_period']})"
|
|
|
|
|
|
ax.legend([legend_label, 'Signal', 'Histogram'], loc='upper left', fontsize=10)
|
|
|
|
|
|
|
|
|
|
|
|
# 设置坐标轴范围
|
|
|
|
|
|
ax.set_xlim(-0.5, len(df)-0.5)
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
def _setup_time_axis(self, ax, time_index):
|
|
|
|
|
|
"""
|
|
|
|
|
|
设置时间轴格式
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
ax: matplotlib轴对象
|
|
|
|
|
|
time_index: 时间索引
|
|
|
|
|
|
"""
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 设置x轴标签为时间,适合日线显示
|
|
|
|
|
|
step = max(1, len(time_index) // 8) # 最多显示8个时间标签,避免过密
|
|
|
|
|
|
time_labels = []
|
|
|
|
|
|
tick_positions = []
|
|
|
|
|
|
|
|
|
|
|
|
for i in range(0, len(time_index), step):
|
|
|
|
|
|
if i < len(time_index):
|
|
|
|
|
|
time_val = time_index[i]
|
|
|
|
|
|
if hasattr(time_val, 'strftime'):
|
|
|
|
|
|
# 日线显示格式:月-日
|
|
|
|
|
|
time_labels.append(time_val.strftime('%m-%d'))
|
|
|
|
|
|
else:
|
|
|
|
|
|
time_labels.append(str(time_val))
|
|
|
|
|
|
tick_positions.append(i)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
ax.set_xticks(tick_positions)
|
|
|
|
|
|
ax.set_xticklabels(time_labels, rotation=45, ha='right')
|
|
|
|
|
|
ax.set_xlabel('时间', fontsize=12)
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
def view_stock_kline(self, stock_code, period, start_date, end_date, macd_params=None):
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
查看股票K线图的完整流程
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 股票代码
|
|
|
|
|
|
period (str): 数据周期
|
|
|
|
|
|
start_date (str): 开始日期
|
|
|
|
|
|
end_date (str): 结束日期
|
2025-07-23 10:48:32 +08:00
|
|
|
|
macd_params (dict): MACD参数设置,格式如下:
|
|
|
|
|
|
{
|
|
|
|
|
|
'fast_period': 12, # 快速EMA周期
|
|
|
|
|
|
'slow_period': 26, # 慢速EMA周期
|
|
|
|
|
|
'signal_period': 9 # 信号线周期
|
|
|
|
|
|
}
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
bool: 成功返回True,失败返回False
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
logger.info(f"🎯 正在为 {stock_code} 绘制 {period} 周期K线图...")
|
|
|
|
|
|
logger.info(f"📅 时间范围: {start_date} ~ {end_date}")
|
|
|
|
|
|
|
|
|
|
|
|
# 1. 连接数据库
|
|
|
|
|
|
if not self.is_connected:
|
|
|
|
|
|
if not self.connect_database():
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
# 2. 读取数据
|
|
|
|
|
|
df = self.read_stock_data(stock_code, period, start_date, end_date)
|
|
|
|
|
|
|
|
|
|
|
|
if df.empty:
|
|
|
|
|
|
logger.error(f"❌ {stock_code} 在指定时间范围内没有数据")
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 3. 绘制交互式K线图
|
2025-07-23 10:48:32 +08:00
|
|
|
|
success = self.plot_kline_chart(df, stock_code, period, macd_params=macd_params)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
if success:
|
|
|
|
|
|
logger.info("🎉 K线图查看完成!")
|
|
|
|
|
|
return True
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.error("❌ K线图绘制失败")
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 查看K线图异常: {e}")
|
|
|
|
|
|
import traceback
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
return False
|
|
|
|
|
|
finally:
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 4. 清理资源
|
2025-07-22 20:19:06 +08:00
|
|
|
|
self.disconnect_database()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
|
"""
|
2025-07-22 22:42:43 +08:00
|
|
|
|
主函数 - 测试K线图查看器(专注于日线数据)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
# 创建K线图查看器
|
|
|
|
|
|
viewer = StockKlineViewer()
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
# 测试参数 - 包含不同的MACD参数设置
|
2025-07-22 20:19:06 +08:00
|
|
|
|
test_cases = [
|
|
|
|
|
|
{
|
2025-07-22 22:42:43 +08:00
|
|
|
|
"stock_code": "601658.SH", # 邮储银行
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"period": "1d",
|
2025-07-22 22:42:43 +08:00
|
|
|
|
"start_date": "20250501",
|
2025-07-23 10:48:32 +08:00
|
|
|
|
"end_date": "20250721",
|
|
|
|
|
|
"macd_params": None, # 使用默认参数 (12,26,9)
|
|
|
|
|
|
"description": "默认MACD参数"
|
|
|
|
|
|
},
|
|
|
|
|
|
# 可以添加更多测试用例来演示不同参数
|
|
|
|
|
|
# {
|
|
|
|
|
|
# "stock_code": "601658.SH",
|
|
|
|
|
|
# "period": "1d",
|
|
|
|
|
|
# "start_date": "20250501",
|
|
|
|
|
|
# "end_date": "20250721",
|
|
|
|
|
|
# "macd_params": {
|
|
|
|
|
|
# "fast_period": 10, # 更敏感的快线
|
|
|
|
|
|
# "slow_period": 22, # 更敏感的慢线
|
|
|
|
|
|
# "signal_period": 7 # 更敏感的信号线
|
|
|
|
|
|
# },
|
|
|
|
|
|
# "description": "快速MACD参数 (10,22,7)"
|
|
|
|
|
|
# }
|
2025-07-22 20:19:06 +08:00
|
|
|
|
]
|
|
|
|
|
|
|
2025-07-22 22:42:43 +08:00
|
|
|
|
print("🚀 股票K线图查看器测试 - 日线数据")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
print("=" * 50)
|
2025-07-23 10:48:32 +08:00
|
|
|
|
print("📊 MACD参数说明:")
|
|
|
|
|
|
print(" fast_period: 快速EMA周期 (默认12, 范围5-15)")
|
|
|
|
|
|
print(" slow_period: 慢速EMA周期 (默认26, 范围20-30)")
|
|
|
|
|
|
print(" signal_period: 信号线周期 (默认9, 范围5-15)")
|
|
|
|
|
|
print("=" * 50)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
for i, test_case in enumerate(test_cases, 1):
|
2025-07-23 10:48:32 +08:00
|
|
|
|
print(f"\n📈 测试用例 {i}: {test_case['description']}")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
print(f" 股票代码: {test_case['stock_code']}")
|
|
|
|
|
|
print(f" 数据周期: {test_case['period']}")
|
|
|
|
|
|
print(f" 时间范围: {test_case['start_date']} ~ {test_case['end_date']}")
|
|
|
|
|
|
|
2025-07-23 10:48:32 +08:00
|
|
|
|
if test_case['macd_params']:
|
|
|
|
|
|
params = test_case['macd_params']
|
|
|
|
|
|
print(f" MACD参数: ({params['fast_period']},{params['slow_period']},{params['signal_period']})")
|
|
|
|
|
|
else:
|
|
|
|
|
|
print(f" MACD参数: (12,26,9) - 默认参数")
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
success = viewer.view_stock_kline(
|
|
|
|
|
|
stock_code=test_case['stock_code'],
|
|
|
|
|
|
period=test_case['period'],
|
|
|
|
|
|
start_date=test_case['start_date'],
|
2025-07-23 10:48:32 +08:00
|
|
|
|
end_date=test_case['end_date'],
|
|
|
|
|
|
macd_params=test_case['macd_params']
|
2025-07-22 20:19:06 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if success:
|
|
|
|
|
|
print(f"✅ 测试用例 {i} 成功")
|
|
|
|
|
|
else:
|
|
|
|
|
|
print(f"❌ 测试用例 {i} 失败")
|
|
|
|
|
|
|
|
|
|
|
|
print("\n🎉 测试完成!")
|
2025-07-23 10:48:32 +08:00
|
|
|
|
print("\n<EFBFBD> MACD参数调整建议:")
|
|
|
|
|
|
print(" 🔸 短线交易: 使用(10,22,7)更敏感")
|
|
|
|
|
|
print(" 🔸 中长线: 使用(12,26,9)标准参数")
|
|
|
|
|
|
print(" 🔸 稳健策略: 使用(14,28,10)更平滑")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 程序执行出错: {e}")
|
|
|
|
|
|
import traceback
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
main()
|