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:43:19 +08:00
|
|
|
|
# 导入独立的数据管理器
|
2025-07-24 11:28:41 +08:00
|
|
|
|
try:
|
2025-07-24 11:43:19 +08:00
|
|
|
|
from stock_data_manager import StockDataManager
|
2025-07-24 11:28:41 +08:00
|
|
|
|
except ImportError as e:
|
2025-07-24 11:43:19 +08:00
|
|
|
|
logger.error(f"❌ 无法导入股票数据管理器模块: {e}")
|
|
|
|
|
|
StockDataManager = None
|
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
|
2025-07-28 12:55:28 +08:00
|
|
|
|
ax.plot([i-0.3, i+0.3], [row['open'], row['open']], color=color, linewidth=2)
|
2025-07-22 22:42:43 +08:00
|
|
|
|
# 绘制上影线
|
|
|
|
|
|
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线查看器
|
|
|
|
|
|
"""
|
2025-07-24 11:43:19 +08:00
|
|
|
|
# 检查StockDataManager是否导入成功
|
|
|
|
|
|
if StockDataManager is None:
|
|
|
|
|
|
logger.error("❌ StockDataManager 模块导入失败,K线查看器无法正常工作")
|
|
|
|
|
|
self.data_manager = None
|
|
|
|
|
|
else:
|
|
|
|
|
|
self.data_manager = StockDataManager()
|
|
|
|
|
|
|
2025-07-24 11:28:41 +08:00
|
|
|
|
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:43:19 +08:00
|
|
|
|
# 检查数据管理器是否可用
|
|
|
|
|
|
if self.data_manager is None:
|
|
|
|
|
|
logger.error("❌ 数据管理器不可用,无法显示K线图")
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
# 确保数据库连接关闭
|
2025-07-24 11:43:19 +08:00
|
|
|
|
if self.data_manager is not None:
|
|
|
|
|
|
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()
|