2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
股票K线图查看器 - 分离数据和显示功能
|
|
|
|
|
|
支持从数据库加载股票数据并绘制交互式K线图,包含MACD指标
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import pandas as pd
|
|
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
from matplotlib.patches import Rectangle
|
|
|
|
|
|
from matplotlib.ticker import FuncFormatter
|
2025-07-24 11:28:41 +08:00
|
|
|
|
import sys
|
2025-07-22 20:19:06 +08:00
|
|
|
|
import os
|
2025-07-24 11:28:41 +08:00
|
|
|
|
from datetime import datetime, date
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 添加路径以导入日志模块
|
|
|
|
|
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
|
project_root = os.path.dirname(os.path.dirname(current_dir))
|
|
|
|
|
|
sys.path.append(project_root)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 导入模块
|
|
|
|
|
|
try:
|
|
|
|
|
|
from src.log.logger import logger
|
|
|
|
|
|
except ImportError:
|
|
|
|
|
|
import logging
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
try:
|
|
|
|
|
|
from database_config import init_database, get_database
|
|
|
|
|
|
from stock_models import create_stock_kline_model
|
|
|
|
|
|
except ImportError as e:
|
|
|
|
|
|
logger.error(f"❌ 无法导入数据库配置模块: {e}")
|
|
|
|
|
|
init_database = None
|
|
|
|
|
|
get_database = None
|
|
|
|
|
|
create_stock_kline_model = None
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
class StockDataManager:
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
股票数据管理器 - 使用Peewee ORM
|
|
|
|
|
|
专门负责数据的读取、处理和管理
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
初始化数据管理器
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
self.database = None
|
2025-07-22 20:19:06 +08:00
|
|
|
|
self.is_connected = False
|
2025-07-24 11:28:41 +08:00
|
|
|
|
self.model_cache = {} # 缓存已创建的模型
|
|
|
|
|
|
logger.info("📊 StockDataManager (Peewee) 初始化完成")
|
|
|
|
|
|
|
|
|
|
|
|
def _normalize_stock_code(self, stock_code):
|
|
|
|
|
|
"""
|
|
|
|
|
|
标准化股票代码格式
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 股票代码,支持多种格式
|
|
|
|
|
|
- "601658" -> "601658.SH"
|
|
|
|
|
|
- "601658.SH" -> "601658.SH"
|
|
|
|
|
|
- "000001" -> "000001.SZ"
|
|
|
|
|
|
- "000001.SZ" -> "000001.SZ"
|
|
|
|
|
|
- "510310" -> "510310.SH"
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
str: 标准化后的股票代码
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not stock_code:
|
|
|
|
|
|
return stock_code
|
|
|
|
|
|
|
|
|
|
|
|
# 如果已经包含市场后缀,直接返回
|
|
|
|
|
|
if '.' in stock_code:
|
|
|
|
|
|
return stock_code.upper()
|
|
|
|
|
|
|
|
|
|
|
|
# 根据股票代码判断市场
|
|
|
|
|
|
if stock_code.startswith('00') or stock_code.startswith('30'):
|
|
|
|
|
|
# 深圳市场:000xxx, 002xxx, 300xxx
|
|
|
|
|
|
return f"{stock_code}.SZ"
|
|
|
|
|
|
elif stock_code.startswith('60') or stock_code.startswith('51') or stock_code.startswith('50'):
|
|
|
|
|
|
# 上海市场:600xxx, 601xxx, 603xxx, 510xxx, 500xxx
|
|
|
|
|
|
return f"{stock_code}.SH"
|
|
|
|
|
|
else:
|
|
|
|
|
|
# 默认为上海市场
|
|
|
|
|
|
logger.warning(f"⚠️ 无法识别股票代码市场: {stock_code},默认使用上海市场(.SH)")
|
|
|
|
|
|
return f"{stock_code}.SH"
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
def connect_database(self):
|
|
|
|
|
|
"""
|
|
|
|
|
|
连接数据库
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
bool: 连接成功返回True,失败返回False
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
if not self.is_connected:
|
|
|
|
|
|
# 初始化数据库
|
|
|
|
|
|
if init_database():
|
|
|
|
|
|
self.database = get_database()
|
|
|
|
|
|
self.is_connected = True
|
|
|
|
|
|
logger.info("✅ 数据库连接成功 (Peewee ORM)")
|
|
|
|
|
|
return True
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.error("❌ 数据库初始化失败")
|
|
|
|
|
|
return False
|
|
|
|
|
|
return True
|
2025-07-22 20:19:06 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 数据库连接异常: {e}")
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def disconnect_database(self):
|
|
|
|
|
|
"""
|
|
|
|
|
|
断开数据库连接
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
if self.database and self.is_connected:
|
|
|
|
|
|
self.database.close()
|
2025-07-22 20:19:06 +08:00
|
|
|
|
self.is_connected = False
|
2025-07-24 11:28:41 +08:00
|
|
|
|
logger.info("✅ 数据库连接已关闭 (Peewee)")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
except Exception as e:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
logger.error(f"❌ 关闭数据库连接时出错: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
def _get_model_class(self, stock_code, period):
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取或创建股票K线模型类
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 股票代码(支持短格式如'601658'或完整格式如'601658.SH')
|
|
|
|
|
|
period (str): 数据周期
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
Model: Peewee模型类
|
|
|
|
|
|
"""
|
|
|
|
|
|
# 标准化股票代码
|
|
|
|
|
|
normalized_code = self._normalize_stock_code(stock_code)
|
|
|
|
|
|
model_key = f"{normalized_code}_{period}"
|
|
|
|
|
|
|
|
|
|
|
|
if model_key not in self.model_cache:
|
|
|
|
|
|
try:
|
|
|
|
|
|
# 创建模型类,使用标准化的股票代码
|
|
|
|
|
|
model_class = create_stock_kline_model(normalized_code, period)
|
|
|
|
|
|
self.model_cache[model_key] = model_class
|
|
|
|
|
|
logger.info(f"📊 创建模型缓存: {model_key}")
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"❌ 创建模型失败: {model_key} - {e}")
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
return self.model_cache[model_key]
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
def read_stock_data(self, stock_code, period='1d', start_date=None, end_date=None):
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
从数据库读取股票K线数据 - 使用Peewee ORM
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
stock_code (str): 股票代码,支持多种格式:
|
|
|
|
|
|
- 短格式:'601658', '000001', '510310'
|
|
|
|
|
|
- 完整格式:'601658.SH', '000001.SZ', '510310.SH'
|
|
|
|
|
|
period (str): 数据周期,支持 1m, 5m, 15m, 30m, 60m, 1d
|
|
|
|
|
|
start_date (str): 开始日期,格式 'YYYY-MM-DD',为None时获取最近数据
|
|
|
|
|
|
end_date (str): 结束日期,格式 'YYYY-MM-DD',为None时获取到最新数据
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
Returns:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
pd.DataFrame: 包含OHLCV数据的DataFrame,索引为时间
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
if not self.is_connected:
|
|
|
|
|
|
logger.error("❌ 数据库未连接")
|
|
|
|
|
|
return pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 获取模型类
|
|
|
|
|
|
model_class = self._get_model_class(stock_code, period)
|
|
|
|
|
|
if not model_class:
|
|
|
|
|
|
logger.error(f"❌ 无法获取模型类: {stock_code} ({period})")
|
|
|
|
|
|
return pd.DataFrame()
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
logger.info(f"📊 使用Peewee查询: {stock_code} ({period})")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 构建查询
|
|
|
|
|
|
query = model_class.select()
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 添加日期条件
|
|
|
|
|
|
if start_date:
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
|
|
|
|
|
|
query = query.where(model_class.timestamp >= start_datetime)
|
2025-07-23 10:48:32 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
if end_date:
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
end_datetime = datetime.strptime(end_date, '%Y-%m-%d')
|
|
|
|
|
|
query = query.where(model_class.timestamp <= end_datetime)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 按时间排序
|
|
|
|
|
|
query = query.order_by(model_class.timestamp.asc())
|
|
|
|
|
|
|
|
|
|
|
|
# 如果没有指定日期范围,限制获取最近500条数据
|
|
|
|
|
|
if not start_date and not end_date:
|
|
|
|
|
|
query = query.limit(500)
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(f"<EFBFBD> 执行Peewee查询: {stock_code} ({period})")
|
|
|
|
|
|
|
|
|
|
|
|
# 执行查询并转换为DataFrame
|
|
|
|
|
|
results = []
|
|
|
|
|
|
for record in query:
|
|
|
|
|
|
results.append({
|
|
|
|
|
|
'timestamp': record.timestamp,
|
|
|
|
|
|
'open': float(record.open_price),
|
|
|
|
|
|
'high': float(record.high_price),
|
|
|
|
|
|
'low': float(record.low_price),
|
|
|
|
|
|
'close': float(record.close_price),
|
|
|
|
|
|
'volume': int(record.volume)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
})
|
|
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
if not results:
|
|
|
|
|
|
logger.warning(f"⚠️ 未找到数据: {stock_code} ({period})")
|
|
|
|
|
|
return pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
# 转换为DataFrame
|
|
|
|
|
|
df = pd.DataFrame(results)
|
|
|
|
|
|
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
|
|
|
|
|
df.set_index('timestamp', inplace=True)
|
|
|
|
|
|
|
|
|
|
|
|
# 确保数据类型正确
|
|
|
|
|
|
numeric_columns = ['open', 'high', 'low', 'close', 'volume']
|
|
|
|
|
|
for col in numeric_columns:
|
|
|
|
|
|
df[col] = pd.to_numeric(df[col], errors='coerce')
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(f"✅ 成功读取 {len(df)} 条数据 (Peewee ORM)")
|
|
|
|
|
|
logger.info(f"📈 数据范围: {df.index.min()} 到 {df.index.max()}")
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
return df
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
logger.error(f"❌ 读取股票数据失败 (Peewee): {e}")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
import traceback
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
return pd.DataFrame()
|
2025-07-24 11:28:41 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class KlineChartRenderer:
|
|
|
|
|
|
"""
|
|
|
|
|
|
K线图表渲染器
|
|
|
|
|
|
专门负责图表的绘制和显示
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
"""
|
|
|
|
|
|
初始化图表渲染器
|
|
|
|
|
|
"""
|
|
|
|
|
|
# 设置中文字体
|
|
|
|
|
|
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文
|
|
|
|
|
|
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
|
|
|
|
|
|
|
|
|
|
|
|
# 图表配置
|
|
|
|
|
|
self.figure_size = (15, 10)
|
|
|
|
|
|
|
|
|
|
|
|
logger.info("🎨 KlineChartRenderer 初始化完成")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
def render_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-24 11:28:41 +08:00
|
|
|
|
渲染K线图表
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
df (pd.DataFrame): K线数据
|
2025-07-22 20:19:06 +08:00
|
|
|
|
stock_code (str): 股票代码
|
|
|
|
|
|
period (str): 数据周期
|
2025-07-24 11:28:41 +08:00
|
|
|
|
show_volume (bool): 是否显示成交量
|
|
|
|
|
|
show_macd (bool): 是否显示MACD指标
|
|
|
|
|
|
macd_params (dict): MACD参数配置
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
Returns:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
bool: 渲染是否成功
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
try:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
if df is None or df.empty:
|
|
|
|
|
|
logger.error("❌ 没有数据可绘制")
|
|
|
|
|
|
return False
|
2025-07-22 22:42:43 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
logger.info(f"🎨 开始绘制K线图 - {stock_code} ({period})")
|
|
|
|
|
|
|
|
|
|
|
|
# 设置默认MACD参数
|
|
|
|
|
|
if macd_params is None:
|
|
|
|
|
|
macd_params = {
|
|
|
|
|
|
'fast_period': 12,
|
|
|
|
|
|
'slow_period': 26,
|
|
|
|
|
|
'signal_period': 9
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 创建画布和子图
|
|
|
|
|
|
plt.figure(figsize=self.figure_size)
|
|
|
|
|
|
|
|
|
|
|
|
# 计算子图数量和布局
|
|
|
|
|
|
subplot_count = 1 # K线图
|
|
|
|
|
|
if show_volume:
|
|
|
|
|
|
subplot_count += 1
|
|
|
|
|
|
if show_macd:
|
|
|
|
|
|
subplot_count += 1
|
|
|
|
|
|
|
|
|
|
|
|
if subplot_count == 3: # K线+成交量+MACD
|
|
|
|
|
|
ax1 = plt.subplot(3, 1, 1) # K线图
|
|
|
|
|
|
ax2 = plt.subplot(3, 1, 2) # 成交量
|
|
|
|
|
|
ax3 = plt.subplot(3, 1, 3) # MACD
|
2025-07-23 10:48:32 +08:00
|
|
|
|
plt.subplots_adjust(hspace=0.3)
|
2025-07-24 11:28:41 +08:00
|
|
|
|
elif subplot_count == 2: # K线 + (成交量 或 MACD)
|
|
|
|
|
|
ax1 = plt.subplot(2, 1, 1) # K线图
|
|
|
|
|
|
if show_volume:
|
|
|
|
|
|
ax2 = plt.subplot(2, 1, 2) # 成交量
|
|
|
|
|
|
else:
|
|
|
|
|
|
ax3 = plt.subplot(2, 1, 2) # MACD
|
2025-07-23 10:48:32 +08:00
|
|
|
|
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-24 11:28:41 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class StockKlineViewer:
|
|
|
|
|
|
"""
|
|
|
|
|
|
股票K线图查看器 - 主控制器
|
|
|
|
|
|
负责协调数据管理器和图表渲染器
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
"""
|
|
|
|
|
|
初始化K线查看器
|
|
|
|
|
|
"""
|
|
|
|
|
|
self.data_manager = StockDataManager()
|
|
|
|
|
|
self.chart_renderer = KlineChartRenderer()
|
|
|
|
|
|
|
|
|
|
|
|
logger.info("🚀 StockKlineViewer 初始化完成")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
def show_kline_chart(self, stock_code, period='1d', start_date=None, end_date=None,
|
|
|
|
|
|
show_volume=True, show_macd=True, macd_params=None):
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
显示K线图表
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 股票代码
|
|
|
|
|
|
period (str): 数据周期
|
|
|
|
|
|
start_date (str): 开始日期
|
|
|
|
|
|
end_date (str): 结束日期
|
2025-07-24 11:28:41 +08:00
|
|
|
|
show_volume (bool): 是否显示成交量
|
|
|
|
|
|
show_macd (bool): 是否显示MACD指标
|
|
|
|
|
|
macd_params (dict): MACD参数配置
|
|
|
|
|
|
|
2025-07-22 20:19:06 +08:00
|
|
|
|
Returns:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
bool: 显示是否成功
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
|
|
|
|
|
try:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 连接数据库
|
|
|
|
|
|
if not self.data_manager.connect_database():
|
|
|
|
|
|
return False
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 读取数据
|
|
|
|
|
|
df = self.data_manager.read_stock_data(stock_code, period, start_date, end_date)
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
if df.empty:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
logger.error("❌ 没有找到数据")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
return False
|
|
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
# 渲染图表
|
|
|
|
|
|
success = self.chart_renderer.render_chart(df, stock_code, period, show_volume, show_macd, macd_params)
|
|
|
|
|
|
|
|
|
|
|
|
# 断开数据库连接
|
|
|
|
|
|
self.data_manager.disconnect_database()
|
|
|
|
|
|
|
|
|
|
|
|
return success
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
2025-07-24 11:28:41 +08:00
|
|
|
|
logger.error(f"❌ 显示K线图失败: {e}")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
import traceback
|
|
|
|
|
|
traceback.print_exc()
|
2025-07-24 11:28:41 +08:00
|
|
|
|
|
|
|
|
|
|
# 确保数据库连接关闭
|
|
|
|
|
|
self.data_manager.disconnect_database()
|
2025-07-22 20:19:06 +08:00
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
主函数 - 演示K线图查看器的使用
|
2025-07-22 20:19:06 +08:00
|
|
|
|
"""
|
2025-07-24 11:28:41 +08:00
|
|
|
|
print("📈 股票K线图查看器")
|
|
|
|
|
|
print("=" * 50)
|
|
|
|
|
|
|
|
|
|
|
|
# 创建K线查看器
|
|
|
|
|
|
viewer = StockKlineViewer()
|
|
|
|
|
|
|
|
|
|
|
|
# 测试股票代码列表 - 使用完整格式确保与数据库表名一致
|
|
|
|
|
|
test_stocks = ['601658.SH', '601398.SH', '510310.SH']
|
|
|
|
|
|
|
|
|
|
|
|
for stock_code in test_stocks:
|
|
|
|
|
|
print(f"\n🔍 查看股票: {stock_code}")
|
|
|
|
|
|
|
|
|
|
|
|
# 配置MACD参数
|
|
|
|
|
|
macd_config = {
|
|
|
|
|
|
'fast_period': 12,
|
|
|
|
|
|
'slow_period': 26,
|
|
|
|
|
|
'signal_period': 9
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 显示K线图(包含成交量和MACD)
|
|
|
|
|
|
success = viewer.show_kline_chart(
|
|
|
|
|
|
stock_code=stock_code,
|
|
|
|
|
|
period='1d',
|
|
|
|
|
|
show_volume=True,
|
|
|
|
|
|
show_macd=True,
|
|
|
|
|
|
macd_params=macd_config
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if success:
|
|
|
|
|
|
print(f"✅ {stock_code} K线图显示完成")
|
|
|
|
|
|
else:
|
|
|
|
|
|
print(f"❌ {stock_code} K线图显示失败")
|
|
|
|
|
|
|
|
|
|
|
|
# 询问是否继续
|
|
|
|
|
|
user_input = input("\n继续查看下一个股票? (y/n, 默认y): ").strip().lower()
|
|
|
|
|
|
if user_input == 'n':
|
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
|
|
print("\n👋 程序结束")
|
2025-07-22 20:19:06 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
main()
|