2025-12-22 21:10:36 +08:00
|
|
|
|
"""
|
|
|
|
|
|
简单K线查看器
|
|
|
|
|
|
使用DataService直接显示K线数据
|
|
|
|
|
|
支持键盘导航和缩放
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import sys
|
|
|
|
|
|
import os
|
|
|
|
|
|
import io
|
2025-12-22 21:22:26 +08:00
|
|
|
|
import traceback
|
2025-12-22 21:10:36 +08:00
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
from PyQt6.QtWidgets import (
|
|
|
|
|
|
QApplication,
|
|
|
|
|
|
QMainWindow,
|
|
|
|
|
|
QWidget,
|
|
|
|
|
|
QVBoxLayout,
|
|
|
|
|
|
QHBoxLayout,
|
|
|
|
|
|
QLabel,
|
|
|
|
|
|
QComboBox,
|
|
|
|
|
|
QPushButton,
|
|
|
|
|
|
QDateEdit,
|
|
|
|
|
|
QMessageBox,
|
|
|
|
|
|
)
|
|
|
|
|
|
from PyQt6.QtCore import Qt, QDate, QThread, pyqtSignal
|
|
|
|
|
|
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
|
|
|
|
|
|
from matplotlib.backends.backend_qt import NavigationToolbar2QT
|
|
|
|
|
|
from matplotlib.figure import Figure
|
|
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
import mplfinance as mpf
|
|
|
|
|
|
|
|
|
|
|
|
from src.core.config import Config
|
|
|
|
|
|
from src.data_service import DataService
|
2025-12-23 17:56:01 +08:00
|
|
|
|
from src.core.constants import Period
|
2025-12-22 21:10:36 +08:00
|
|
|
|
|
|
|
|
|
|
# 设置控制台编码为UTF-8解决中文乱码
|
|
|
|
|
|
if sys.platform == "win32":
|
|
|
|
|
|
# 设置控制台代码页为65001(UTF-8)
|
|
|
|
|
|
os.system("chcp 65001 > nul")
|
|
|
|
|
|
# 重置输出流
|
|
|
|
|
|
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
|
|
|
|
|
|
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
|
|
|
|
|
|
|
|
|
|
|
|
# 添加项目根目录到路径
|
|
|
|
|
|
project_root = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
|
sys.path.insert(0, project_root)
|
|
|
|
|
|
|
|
|
|
|
|
# 设置中文字体
|
|
|
|
|
|
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "Arial Unicode MS"]
|
|
|
|
|
|
plt.rcParams["axes.unicode_minus"] = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class KlineCanvas(FigureCanvasQTAgg):
|
|
|
|
|
|
"""K线画布 - 支持键盘导航"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, parent=None):
|
|
|
|
|
|
self.fig = Figure(figsize=(16, 10), dpi=100)
|
|
|
|
|
|
super().__init__(self.fig)
|
|
|
|
|
|
self.setParent(parent)
|
|
|
|
|
|
|
|
|
|
|
|
# 存储完整数据
|
|
|
|
|
|
self.full_data = None
|
|
|
|
|
|
self.current_start = 0 # 当前显示起始位置
|
|
|
|
|
|
self.current_end = 100 # 当前显示结束位置
|
|
|
|
|
|
self.display_count = 100 # 默认显示100条
|
|
|
|
|
|
|
|
|
|
|
|
# 创建专业黑色主题样式(青涨红跌)
|
|
|
|
|
|
self.style = mpf.make_mpf_style(
|
|
|
|
|
|
base_mpf_style="nightclouds",
|
|
|
|
|
|
marketcolors=mpf.make_marketcolors(
|
|
|
|
|
|
up="#00ffff", # 青色上涨
|
|
|
|
|
|
down="#ff0000", # 红色下跌
|
|
|
|
|
|
edge="inherit",
|
|
|
|
|
|
wick="inherit",
|
|
|
|
|
|
volume="in",
|
|
|
|
|
|
alpha=0.9,
|
|
|
|
|
|
),
|
|
|
|
|
|
mavcolors=[
|
|
|
|
|
|
"#00ff00",
|
|
|
|
|
|
"#ffff00",
|
|
|
|
|
|
"#ff00ff",
|
|
|
|
|
|
"#00ffff",
|
|
|
|
|
|
"#ffa500",
|
|
|
|
|
|
], # MA5/10/20/30/60颜色
|
|
|
|
|
|
facecolor="#0a0a0a", # 黑色背景
|
|
|
|
|
|
edgecolor="#333333",
|
|
|
|
|
|
figcolor="#0a0a0a",
|
|
|
|
|
|
gridcolor="#333333",
|
|
|
|
|
|
gridstyle="--",
|
|
|
|
|
|
gridaxis="both",
|
|
|
|
|
|
y_on_right=False,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 启用键盘焦点
|
|
|
|
|
|
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 防止resize过于频繁触发重绘
|
|
|
|
|
|
self._resize_timer = None
|
|
|
|
|
|
|
|
|
|
|
|
# 鼠标悬停显示数据
|
|
|
|
|
|
self.current_display_data = None # 当前显示的数据
|
|
|
|
|
|
self.current_macd_data = None # MACD数据
|
|
|
|
|
|
self.current_rsi_data = None # RSI数据
|
|
|
|
|
|
self.crosshair_vlines = [] # 十字光标垂直线列表(多个子图)
|
|
|
|
|
|
self.info_text = None # 信息文本
|
|
|
|
|
|
|
|
|
|
|
|
# 连接鼠标移动事件
|
|
|
|
|
|
self.mpl_connect("motion_notify_event", self.on_mouse_move)
|
|
|
|
|
|
|
|
|
|
|
|
def resizeEvent(self, event):
|
|
|
|
|
|
"""处理窗口缩放事件 - 延迟重绘避免崩溃"""
|
|
|
|
|
|
super().resizeEvent(event)
|
|
|
|
|
|
# 不立即重绘,避免缩放时频繁重绘导致崩溃
|
|
|
|
|
|
# 窗口缩放会自动触发matplotlib的重绘
|
|
|
|
|
|
|
|
|
|
|
|
def on_mouse_move(self, event):
|
|
|
|
|
|
"""鼠标移动事件 - 显示OHLC和指标信息"""
|
|
|
|
|
|
if event.inaxes is None or self.current_display_data is None:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 检查鼠标是否在任一子图上
|
|
|
|
|
|
if event.inaxes not in self.fig.axes:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
# 获取鼠标位置对应的数据索引
|
|
|
|
|
|
x_index = int(round(event.xdata))
|
|
|
|
|
|
if 0 <= x_index < len(self.current_display_data):
|
|
|
|
|
|
# 获取该K线的数据
|
|
|
|
|
|
data_row = self.current_display_data.iloc[x_index]
|
|
|
|
|
|
|
|
|
|
|
|
# 获取时间信息(从_original_index列)
|
|
|
|
|
|
if "_original_index" in data_row:
|
|
|
|
|
|
time_value = data_row["_original_index"]
|
|
|
|
|
|
date_str = (
|
|
|
|
|
|
time_value.strftime("%Y-%m-%d %H:%M")
|
|
|
|
|
|
if hasattr(time_value, "strftime")
|
|
|
|
|
|
else str(time_value)
|
|
|
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
date_str = f"Index: {x_index}"
|
|
|
|
|
|
|
|
|
|
|
|
# 构建显示文本 - OHLC
|
|
|
|
|
|
info_text = (
|
|
|
|
|
|
f"{date_str}\n"
|
|
|
|
|
|
f"O: {data_row['open']:.2f} H: {data_row['high']:.2f}\n"
|
|
|
|
|
|
f"L: {data_row['low']:.2f} C: {data_row['close']:.2f}\n"
|
|
|
|
|
|
f"Vol: {data_row['volume']:.0f}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 添加MACD数据
|
|
|
|
|
|
if self.current_macd_data is not None and x_index < len(
|
|
|
|
|
|
self.current_macd_data
|
|
|
|
|
|
):
|
|
|
|
|
|
macd_row = self.current_macd_data.iloc[x_index]
|
|
|
|
|
|
info_text += (
|
|
|
|
|
|
f"\n\nMACD\n"
|
|
|
|
|
|
f"DIF: {macd_row['dif']:.3f}\n"
|
|
|
|
|
|
f"DEA: {macd_row['dea']:.3f}\n"
|
|
|
|
|
|
f"Hist: {macd_row['histogram']:.3f}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 添加RSI数据
|
|
|
|
|
|
if self.current_rsi_data is not None and x_index < len(
|
|
|
|
|
|
self.current_rsi_data
|
|
|
|
|
|
):
|
|
|
|
|
|
rsi_row = self.current_rsi_data.iloc[x_index]
|
|
|
|
|
|
info_text += (
|
|
|
|
|
|
f"\n\nRSI\n"
|
|
|
|
|
|
f"RSI6: {rsi_row['rsi6']:.1f}\n"
|
|
|
|
|
|
f"RSI12: {rsi_row['rsi12']:.1f}\n"
|
|
|
|
|
|
f"RSI24: {rsi_row['rsi24']:.1f}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 清除旧的十字光标和文本
|
|
|
|
|
|
for line in self.crosshair_vlines:
|
|
|
|
|
|
line.remove()
|
|
|
|
|
|
self.crosshair_vlines.clear()
|
|
|
|
|
|
|
|
|
|
|
|
if self.info_text is not None:
|
|
|
|
|
|
self.info_text.remove()
|
|
|
|
|
|
|
|
|
|
|
|
# 在所有子图上绘制十字光标垂直线
|
|
|
|
|
|
for ax in self.fig.axes:
|
|
|
|
|
|
vline = ax.axvline(
|
|
|
|
|
|
x=x_index,
|
|
|
|
|
|
color="yellow",
|
|
|
|
|
|
linewidth=0.8,
|
|
|
|
|
|
alpha=0.7,
|
|
|
|
|
|
linestyle="--",
|
|
|
|
|
|
)
|
|
|
|
|
|
self.crosshair_vlines.append(vline)
|
|
|
|
|
|
|
|
|
|
|
|
# 在第一个子图(K线图)的右上角显示信息文本
|
|
|
|
|
|
ax1 = self.fig.axes[0]
|
|
|
|
|
|
self.info_text = ax1.text(
|
|
|
|
|
|
0.98,
|
|
|
|
|
|
0.95,
|
|
|
|
|
|
info_text,
|
|
|
|
|
|
transform=ax1.transAxes,
|
|
|
|
|
|
verticalalignment="top",
|
|
|
|
|
|
horizontalalignment="right",
|
|
|
|
|
|
bbox=dict(
|
|
|
|
|
|
boxstyle="round",
|
|
|
|
|
|
facecolor="#1a1a1a",
|
|
|
|
|
|
alpha=0.9,
|
|
|
|
|
|
edgecolor="yellow",
|
|
|
|
|
|
),
|
|
|
|
|
|
color="white",
|
|
|
|
|
|
fontsize=8,
|
|
|
|
|
|
family="monospace",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
self.draw_idle()
|
|
|
|
|
|
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass # 忽略鼠标移动时的错误
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
def keyPressEvent(self, event):
|
|
|
|
|
|
"""处理键盘事件"""
|
|
|
|
|
|
if self.full_data is None or len(self.full_data) == 0:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
step = max(1, self.display_count // 10) # 每次移动10%
|
|
|
|
|
|
total_len = len(self.full_data)
|
|
|
|
|
|
|
|
|
|
|
|
if event.key() == Qt.Key.Key_Left:
|
|
|
|
|
|
# 左移
|
|
|
|
|
|
if self.current_start > 0:
|
|
|
|
|
|
self.current_start = max(0, self.current_start - step)
|
|
|
|
|
|
self.current_end = min(
|
|
|
|
|
|
total_len, self.current_start + self.display_count
|
|
|
|
|
|
)
|
|
|
|
|
|
self.update_display()
|
|
|
|
|
|
|
|
|
|
|
|
elif event.key() == Qt.Key.Key_Right:
|
|
|
|
|
|
# 右移
|
|
|
|
|
|
if self.current_end < total_len:
|
|
|
|
|
|
max_start = max(0, total_len - self.display_count)
|
|
|
|
|
|
self.current_start = min(max_start, self.current_start + step)
|
|
|
|
|
|
self.current_end = min(
|
|
|
|
|
|
total_len, self.current_start + self.display_count
|
|
|
|
|
|
)
|
|
|
|
|
|
self.update_display()
|
|
|
|
|
|
|
|
|
|
|
|
elif event.key() == Qt.Key.Key_Up:
|
|
|
|
|
|
# 放大(显示更少数据)
|
|
|
|
|
|
old_count = self.display_count
|
|
|
|
|
|
self.display_count = max(5, self.display_count - 5) # 每次减少5条
|
|
|
|
|
|
if self.display_count != old_count:
|
|
|
|
|
|
# 保持中心位置
|
|
|
|
|
|
center = (self.current_start + self.current_end) // 2
|
|
|
|
|
|
self.current_start = max(0, center - self.display_count // 2)
|
|
|
|
|
|
self.current_end = min(
|
|
|
|
|
|
total_len, self.current_start + self.display_count
|
|
|
|
|
|
)
|
|
|
|
|
|
self.update_display()
|
|
|
|
|
|
|
|
|
|
|
|
elif event.key() == Qt.Key.Key_Down:
|
|
|
|
|
|
# 缩小(显示更多数据)
|
|
|
|
|
|
old_count = self.display_count
|
|
|
|
|
|
self.display_count = min(total_len, self.display_count + 5) # 每次增加5条
|
|
|
|
|
|
if self.display_count != old_count:
|
|
|
|
|
|
# 保持中心位置
|
|
|
|
|
|
center = (self.current_start + self.current_end) // 2
|
|
|
|
|
|
self.current_start = max(0, center - self.display_count // 2)
|
|
|
|
|
|
self.current_end = min(
|
|
|
|
|
|
total_len, self.current_start + self.display_count
|
|
|
|
|
|
)
|
|
|
|
|
|
self.update_display()
|
|
|
|
|
|
|
|
|
|
|
|
elif event.key() == Qt.Key.Key_Home:
|
|
|
|
|
|
# 回到最开始
|
|
|
|
|
|
self.current_start = 0
|
|
|
|
|
|
self.current_end = min(total_len, self.display_count)
|
|
|
|
|
|
self.update_display()
|
|
|
|
|
|
|
|
|
|
|
|
elif event.key() == Qt.Key.Key_End:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 跳转到末尾
|
2025-12-22 21:10:36 +08:00
|
|
|
|
self.current_start = max(0, total_len - self.display_count)
|
|
|
|
|
|
self.current_end = total_len
|
|
|
|
|
|
self.update_display()
|
|
|
|
|
|
|
|
|
|
|
|
def update_display(self):
|
|
|
|
|
|
"""更新显示区域"""
|
|
|
|
|
|
if self.full_data is None:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 确保范围有效
|
|
|
|
|
|
self.current_start = max(0, self.current_start)
|
|
|
|
|
|
self.current_end = min(len(self.full_data), self.current_end)
|
|
|
|
|
|
|
|
|
|
|
|
# 获取显示数据
|
|
|
|
|
|
display_data = self.full_data.iloc[self.current_start : self.current_end]
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制
|
|
|
|
|
|
title = f"K线图 ({self.current_start + 1}-{self.current_end}/{len(self.full_data)}条, 按←→移动, ↑↓缩放)"
|
|
|
|
|
|
self._plot_data(display_data, title)
|
|
|
|
|
|
|
|
|
|
|
|
def plot_kline(self, df, title="K线图"):
|
|
|
|
|
|
"""绘制K线图"""
|
|
|
|
|
|
if df is None or df.empty:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 保存完整数据
|
|
|
|
|
|
self.full_data = df.copy()
|
|
|
|
|
|
total_len = len(df)
|
|
|
|
|
|
|
|
|
|
|
|
# 根据数据量调整初始显示范围
|
|
|
|
|
|
if total_len <= 20:
|
|
|
|
|
|
# 数据很少,显示所有
|
|
|
|
|
|
self.display_count = total_len
|
|
|
|
|
|
elif total_len <= 100:
|
|
|
|
|
|
# 数据中等,显示一半
|
|
|
|
|
|
self.display_count = max(10, total_len // 2)
|
|
|
|
|
|
else:
|
|
|
|
|
|
# 数据较多,显示100条
|
|
|
|
|
|
self.display_count = 100
|
|
|
|
|
|
|
|
|
|
|
|
# 初始化显示范围(显示最后的数据)
|
|
|
|
|
|
self.current_start = max(0, total_len - self.display_count)
|
|
|
|
|
|
self.current_end = total_len
|
|
|
|
|
|
|
|
|
|
|
|
# 显示
|
|
|
|
|
|
self.update_display()
|
|
|
|
|
|
|
|
|
|
|
|
# 自动获取键盘焦点
|
|
|
|
|
|
self.setFocus()
|
|
|
|
|
|
|
|
|
|
|
|
def _plot_data(self, df, title="K线图"):
|
|
|
|
|
|
"""实际绘制K线图(专业交易风格)"""
|
|
|
|
|
|
if df is None or df.empty:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 数据量检查
|
|
|
|
|
|
data_len = len(df)
|
|
|
|
|
|
if data_len < 2:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 保存当前显示的数据,用于鼠标悬停
|
|
|
|
|
|
# 重置索引,使其从0开始,与mplfinance的x轴坐标对应
|
|
|
|
|
|
# 同时保存原始索引值用于显示时间
|
|
|
|
|
|
self.current_display_data = df.copy()
|
|
|
|
|
|
self.current_display_data["_original_index"] = df.index
|
|
|
|
|
|
self.current_display_data = self.current_display_data.reset_index(drop=True)
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
# 清空旧图
|
|
|
|
|
|
self.fig.clear()
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 准备数据 - 用于绘制(保留原始索引用于时间轴)
|
2025-12-22 21:10:36 +08:00
|
|
|
|
plot_df = df.copy()
|
|
|
|
|
|
for col in ["open", "high", "low", "close", "volume"]:
|
|
|
|
|
|
if col not in plot_df.columns and col.capitalize() in plot_df.columns:
|
|
|
|
|
|
plot_df[col] = plot_df[col.capitalize()]
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
# 创建4个子图(K线+成交量+MACD+RSI)
|
|
|
|
|
|
# 使用gridspec控制高度比例:6:2:1.5:1.5
|
|
|
|
|
|
from matplotlib import gridspec
|
|
|
|
|
|
|
|
|
|
|
|
gs = gridspec.GridSpec(4, 1, height_ratios=[6, 2, 1.5, 1.5], hspace=0.05)
|
|
|
|
|
|
ax1 = self.fig.add_subplot(gs[0]) # K线
|
|
|
|
|
|
ax2 = self.fig.add_subplot(gs[1], sharex=ax1) # 成交量
|
|
|
|
|
|
ax3 = self.fig.add_subplot(gs[2], sharex=ax1) # MACD
|
|
|
|
|
|
ax4 = self.fig.add_subplot(gs[3], sharex=ax1) # RSI
|
|
|
|
|
|
|
|
|
|
|
|
# 设置黑色背景
|
|
|
|
|
|
for ax in [ax1, ax2, ax3, ax4]:
|
|
|
|
|
|
ax.set_facecolor("#0a0a0a")
|
|
|
|
|
|
ax.grid(True, alpha=0.2, color="#333333")
|
|
|
|
|
|
|
|
|
|
|
|
self.fig.patch.set_facecolor("#0a0a0a")
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 根据数据量动态选择均线周期
|
|
|
|
|
|
# 避免均线周期大于数据量导致的问题
|
|
|
|
|
|
ma_periods = []
|
|
|
|
|
|
for period in [5, 10, 20, 30, 60]:
|
|
|
|
|
|
if data_len >= period + 5: # 留一些余量
|
|
|
|
|
|
ma_periods.append(period)
|
|
|
|
|
|
|
|
|
|
|
|
# 如果数据量不足,至少显示一条均线
|
|
|
|
|
|
if not ma_periods and data_len >= 3:
|
|
|
|
|
|
ma_periods = [min(3, data_len - 1)]
|
|
|
|
|
|
|
|
|
|
|
|
# 先绘制K线(不包含均线)
|
2025-12-22 21:10:36 +08:00
|
|
|
|
mpf.plot(
|
|
|
|
|
|
plot_df,
|
|
|
|
|
|
type="candle",
|
|
|
|
|
|
style=self.style,
|
|
|
|
|
|
volume=ax2,
|
|
|
|
|
|
ax=ax1,
|
|
|
|
|
|
warn_too_much_data=10000,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 手动绘制MA均线以显示图例
|
|
|
|
|
|
ma_colors = ["#00ff00", "#ffff00", "#ff00ff", "#00ffff", "#ffa500"]
|
|
|
|
|
|
for i, period in enumerate(ma_periods):
|
|
|
|
|
|
ma = plot_df["close"].rolling(window=period).mean()
|
|
|
|
|
|
ax1.plot(
|
|
|
|
|
|
ma.values,
|
|
|
|
|
|
label=f"MA{period}",
|
|
|
|
|
|
color=ma_colors[i % len(ma_colors)],
|
|
|
|
|
|
linewidth=1,
|
|
|
|
|
|
alpha=0.8,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 显示MA图例
|
|
|
|
|
|
if ma_periods:
|
|
|
|
|
|
ax1.legend(
|
|
|
|
|
|
loc="upper left",
|
|
|
|
|
|
fontsize=8,
|
|
|
|
|
|
facecolor="#0a0a0a",
|
|
|
|
|
|
edgecolor="white",
|
|
|
|
|
|
labelcolor="white",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
# 计算并绘制MACD
|
|
|
|
|
|
self._plot_macd(plot_df, ax3)
|
|
|
|
|
|
|
|
|
|
|
|
# 计算并绘制RSI
|
|
|
|
|
|
self._plot_rsi(plot_df, ax4)
|
|
|
|
|
|
|
|
|
|
|
|
# 设置标题和标签
|
|
|
|
|
|
ax1.set_title(title, color="white", fontsize=12, pad=10)
|
|
|
|
|
|
ax1.set_ylabel("价格", color="white")
|
|
|
|
|
|
ax2.set_ylabel("成交量", color="white")
|
|
|
|
|
|
ax3.set_ylabel("MACD", color="white", fontsize=9)
|
|
|
|
|
|
ax4.set_ylabel("RSI", color="white", fontsize=9)
|
|
|
|
|
|
ax4.set_xlabel("日期", color="white")
|
|
|
|
|
|
|
|
|
|
|
|
# 隐藏除最后一个子图外的x轴标签
|
|
|
|
|
|
for ax in [ax1, ax2, ax3]:
|
|
|
|
|
|
plt.setp(ax.get_xticklabels(), visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
# 设置刻度颜色
|
|
|
|
|
|
for ax in [ax1, ax2, ax3, ax4]:
|
|
|
|
|
|
ax.tick_params(colors="white", labelsize=8)
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"绘制失败: {e}")
|
|
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
ax = self.fig.add_subplot(111)
|
|
|
|
|
|
ax.set_facecolor("#0a0a0a")
|
|
|
|
|
|
ax.text(
|
|
|
|
|
|
0.5, 0.5, f"绘制失败: {str(e)}", ha="center", va="center", color="white"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
self.draw()
|
|
|
|
|
|
|
|
|
|
|
|
def _plot_macd(self, df, ax):
|
|
|
|
|
|
"""绘制MACD指标"""
|
|
|
|
|
|
try:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 数据量检查:MACD需要至少26+9=35条数据
|
|
|
|
|
|
if len(df) < 35:
|
|
|
|
|
|
ax.text(
|
|
|
|
|
|
0.5,
|
|
|
|
|
|
0.5,
|
|
|
|
|
|
f"数据不足(需要35条,当前{len(df)}条)",
|
|
|
|
|
|
ha="center",
|
|
|
|
|
|
va="center",
|
|
|
|
|
|
color="white",
|
|
|
|
|
|
transform=ax.transAxes,
|
|
|
|
|
|
)
|
|
|
|
|
|
return
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
# 计算MACD
|
|
|
|
|
|
exp1 = df["close"].ewm(span=12, adjust=False).mean()
|
|
|
|
|
|
exp2 = df["close"].ewm(span=26, adjust=False).mean()
|
|
|
|
|
|
macd = exp1 - exp2
|
|
|
|
|
|
signal = macd.ewm(span=9, adjust=False).mean()
|
|
|
|
|
|
histogram = macd - signal
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 保存MACD数据供鼠标悬停使用
|
|
|
|
|
|
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
self.current_macd_data = pd.DataFrame(
|
|
|
|
|
|
{"dif": macd, "dea": signal, "histogram": histogram}
|
|
|
|
|
|
).reset_index(drop=True)
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
# 绘制MACD柱状图
|
|
|
|
|
|
colors = ["#00ff00" if x >= 0 else "#ff0000" for x in histogram]
|
|
|
|
|
|
ax.bar(range(len(histogram)), histogram, color=colors, alpha=0.6, width=0.8)
|
|
|
|
|
|
|
|
|
|
|
|
# 绘制MACD和信号线
|
|
|
|
|
|
ax.plot(macd.values, color="#00ffff", linewidth=1, label="MACD")
|
|
|
|
|
|
ax.plot(signal.values, color="#ffff00", linewidth=1, label="Signal")
|
|
|
|
|
|
|
|
|
|
|
|
ax.axhline(0, color="white", linewidth=0.5, alpha=0.5)
|
|
|
|
|
|
ax.legend(
|
|
|
|
|
|
loc="upper left",
|
|
|
|
|
|
fontsize=8,
|
|
|
|
|
|
facecolor="#0a0a0a",
|
|
|
|
|
|
edgecolor="white",
|
|
|
|
|
|
labelcolor="white",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"MACD计算失败: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
def _plot_rsi(self, df, ax):
|
|
|
|
|
|
"""绘制RSI指标"""
|
|
|
|
|
|
try:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 数据量检查:RSI需要至少period+1条数据
|
|
|
|
|
|
if len(df) < 25: # 最大周期24+1
|
|
|
|
|
|
ax.text(
|
|
|
|
|
|
0.5,
|
|
|
|
|
|
0.5,
|
|
|
|
|
|
f"数据不足(需要25条,当前{len(df)}条)",
|
|
|
|
|
|
ha="center",
|
|
|
|
|
|
va="center",
|
|
|
|
|
|
color="white",
|
|
|
|
|
|
transform=ax.transAxes,
|
|
|
|
|
|
)
|
|
|
|
|
|
return
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
# 计算RSI(6,12,24)
|
2025-12-23 17:56:01 +08:00
|
|
|
|
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
rsi_data = {}
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
for period in [6, 12, 24]:
|
|
|
|
|
|
delta = df["close"].diff()
|
|
|
|
|
|
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
|
|
|
|
|
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
|
|
|
|
|
|
rs = gain / loss
|
|
|
|
|
|
rsi = 100 - (100 / (1 + rs))
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 保存RSI数据
|
|
|
|
|
|
rsi_data[f"rsi{period}"] = rsi
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
colors = {6: "#ffff00", 12: "#00ffff", 24: "#ff00ff"}
|
|
|
|
|
|
ax.plot(
|
|
|
|
|
|
rsi.values, color=colors[period], linewidth=1, label=f"RSI{period}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 保存RSI数据供鼠标悬停使用
|
|
|
|
|
|
self.current_rsi_data = pd.DataFrame(rsi_data).reset_index(drop=True)
|
|
|
|
|
|
|
2025-12-22 21:10:36 +08:00
|
|
|
|
# 绘制参考线
|
|
|
|
|
|
ax.axhline(80, color="red", linewidth=0.5, alpha=0.5, linestyle="--")
|
|
|
|
|
|
ax.axhline(50, color="white", linewidth=0.5, alpha=0.3)
|
|
|
|
|
|
ax.axhline(20, color="green", linewidth=0.5, alpha=0.5, linestyle="--")
|
|
|
|
|
|
|
|
|
|
|
|
ax.set_ylim([0, 100])
|
|
|
|
|
|
ax.legend(
|
|
|
|
|
|
loc="upper left",
|
|
|
|
|
|
fontsize=8,
|
|
|
|
|
|
facecolor="#0a0a0a",
|
|
|
|
|
|
edgecolor="white",
|
|
|
|
|
|
labelcolor="white",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"RSI计算失败: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
ax = self.fig.add_subplot(111)
|
|
|
|
|
|
ax.text(0.5, 0.5, f"绘制失败: {str(e)}", ha="center", va="center")
|
|
|
|
|
|
|
|
|
|
|
|
self.draw()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class DataLoadThread(QThread):
|
|
|
|
|
|
"""异步数据加载线程"""
|
|
|
|
|
|
|
|
|
|
|
|
# 定义信号
|
|
|
|
|
|
finished = pyqtSignal(object, str) # (dataframe, error_message)
|
|
|
|
|
|
progress = pyqtSignal(str) # 进度信息
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, data_service, symbol, period, start_date, end_date):
|
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
self.data_service = data_service
|
|
|
|
|
|
self.symbol = symbol
|
|
|
|
|
|
self.period = period
|
|
|
|
|
|
self.start_date = start_date
|
|
|
|
|
|
self.end_date = end_date
|
|
|
|
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
|
|
"""在子线程中执行数据加载"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
self.progress.emit(
|
|
|
|
|
|
f"查询: {self.symbol} {self.period} {self.start_date.date()} ~ {self.end_date.date()}"
|
|
|
|
|
|
)
|
|
|
|
|
|
print(
|
|
|
|
|
|
f"查询: {self.symbol} {self.period} {self.start_date} ~ {self.end_date}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
df = self.data_service.get_klines(
|
|
|
|
|
|
self.symbol, self.period, self.start_date, self.end_date
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if df is None or df.empty:
|
|
|
|
|
|
error_msg = f"未找到数据: {self.symbol} {self.period}"
|
|
|
|
|
|
self.finished.emit(None, error_msg)
|
|
|
|
|
|
else:
|
|
|
|
|
|
print(f"查询成功: {len(df)} 条数据")
|
|
|
|
|
|
print(f"日期范围: {df.index[0]} ~ {df.index[-1]}")
|
|
|
|
|
|
self.finished.emit(df, "")
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
error_msg = f"加载失败: {str(e)}"
|
|
|
|
|
|
print(error_msg)
|
|
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
self.finished.emit(None, error_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class DataDownloadThread(QThread):
|
|
|
|
|
|
"""异步数据下载线程"""
|
|
|
|
|
|
|
|
|
|
|
|
# 定义信号
|
|
|
|
|
|
finished = pyqtSignal(bool, str) # (success, message)
|
|
|
|
|
|
progress = pyqtSignal(str) # 进度信息
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, data_service, symbols, periods, start_date, end_date):
|
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
self.data_service = data_service
|
|
|
|
|
|
self.symbols = symbols
|
|
|
|
|
|
self.periods = periods
|
|
|
|
|
|
self.start_date = start_date
|
|
|
|
|
|
self.end_date = end_date
|
|
|
|
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
|
|
"""在子线程中执行数据下载"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
self.progress.emit(
|
|
|
|
|
|
f"开始下载: {', '.join(self.symbols)} | {', '.join(self.periods)} | {self.start_date.date()} ~ {self.end_date.date()}"
|
|
|
|
|
|
)
|
|
|
|
|
|
print(
|
2025-12-23 17:56:01 +08:00
|
|
|
|
f"[下载线程] 下载参数: symbols={self.symbols}, periods={self.periods}, {self.start_date} ~ {self.end_date}"
|
2025-12-22 21:10:36 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
print("[下载线程] 开始调用 download_klines...")
|
2025-12-22 21:10:36 +08:00
|
|
|
|
self.data_service.download_klines(
|
|
|
|
|
|
symbols=self.symbols,
|
|
|
|
|
|
start_date=self.start_date,
|
|
|
|
|
|
end_date=self.end_date,
|
|
|
|
|
|
periods=self.periods,
|
|
|
|
|
|
)
|
2025-12-23 17:56:01 +08:00
|
|
|
|
print("[下载线程] download_klines 调用完成")
|
2025-12-22 21:10:36 +08:00
|
|
|
|
|
|
|
|
|
|
success_msg = (
|
|
|
|
|
|
f"下载完成: {len(self.symbols)}个标的, {len(self.periods)}个周期"
|
|
|
|
|
|
)
|
2025-12-23 17:56:01 +08:00
|
|
|
|
print(f"[下载线程] {success_msg}")
|
2025-12-22 21:10:36 +08:00
|
|
|
|
self.finished.emit(True, success_msg)
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
error_msg = f"下载失败: {str(e)}"
|
2025-12-23 17:56:01 +08:00
|
|
|
|
print(f"[下载线程] {error_msg}")
|
2025-12-22 21:10:36 +08:00
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
self.finished.emit(False, error_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SimpleKlineViewer(QMainWindow):
|
|
|
|
|
|
"""简单K线查看器"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, data_service):
|
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
self.data_service = data_service
|
|
|
|
|
|
self.loading = False # 加载状态标志
|
|
|
|
|
|
self.downloading = False # 下载状态标志
|
|
|
|
|
|
self.load_thread = None # 加载线程引用
|
|
|
|
|
|
self.download_thread = None # 下载线程引用
|
|
|
|
|
|
self.init_ui()
|
|
|
|
|
|
|
|
|
|
|
|
def _show_status(self, message: str):
|
|
|
|
|
|
"""显示状态栏消息"""
|
|
|
|
|
|
status_bar = self.statusBar()
|
|
|
|
|
|
if status_bar:
|
|
|
|
|
|
status_bar.showMessage(message)
|
|
|
|
|
|
|
|
|
|
|
|
def init_ui(self):
|
|
|
|
|
|
"""初始化界面"""
|
|
|
|
|
|
self.setWindowTitle("K线查看器 - QTrade")
|
|
|
|
|
|
# 设置最小尺寸
|
|
|
|
|
|
self.setMinimumSize(1200, 800)
|
|
|
|
|
|
# 最大化窗口
|
|
|
|
|
|
self.showMaximized()
|
|
|
|
|
|
|
|
|
|
|
|
# 中心部件
|
|
|
|
|
|
central = QWidget()
|
|
|
|
|
|
self.setCentralWidget(central)
|
|
|
|
|
|
layout = QVBoxLayout(central)
|
|
|
|
|
|
|
|
|
|
|
|
# 控制栏
|
|
|
|
|
|
control_layout = QHBoxLayout()
|
|
|
|
|
|
|
|
|
|
|
|
# 标的选择
|
|
|
|
|
|
control_layout.addWidget(QLabel("标的:"))
|
|
|
|
|
|
self.symbol_combo = QComboBox()
|
|
|
|
|
|
self.symbol_combo.addItems(["601658.SH", "159915.SZ"])
|
|
|
|
|
|
control_layout.addWidget(self.symbol_combo)
|
|
|
|
|
|
|
|
|
|
|
|
# 周期选择
|
|
|
|
|
|
control_layout.addWidget(QLabel("周期:"))
|
|
|
|
|
|
self.period_combo = QComboBox()
|
2025-12-23 17:56:01 +08:00
|
|
|
|
self.period_combo.addItems(
|
|
|
|
|
|
[
|
|
|
|
|
|
Period.MIN_1,
|
|
|
|
|
|
Period.MIN_5,
|
|
|
|
|
|
Period.MIN_15,
|
|
|
|
|
|
Period.MIN_30,
|
|
|
|
|
|
Period.MIN_60,
|
|
|
|
|
|
Period.DAY_1,
|
|
|
|
|
|
]
|
|
|
|
|
|
)
|
|
|
|
|
|
self.period_combo.setCurrentText(Period.DAY_1) # 默认日线
|
2025-12-22 21:10:36 +08:00
|
|
|
|
self.period_combo.currentTextChanged.connect(self.on_period_changed)
|
|
|
|
|
|
control_layout.addWidget(self.period_combo)
|
|
|
|
|
|
|
|
|
|
|
|
# 开始日期
|
|
|
|
|
|
control_layout.addWidget(QLabel("开始:"))
|
|
|
|
|
|
self.start_date_edit = QDateEdit()
|
|
|
|
|
|
self.start_date_edit.setCalendarPopup(True)
|
|
|
|
|
|
self.start_date_edit.setDisplayFormat("yyyy-MM-dd")
|
|
|
|
|
|
self.start_date_edit.setDate(QDate(2024, 1, 1)) # 默认一年前
|
|
|
|
|
|
control_layout.addWidget(self.start_date_edit)
|
|
|
|
|
|
|
|
|
|
|
|
# 结束日期
|
|
|
|
|
|
control_layout.addWidget(QLabel("结束:"))
|
|
|
|
|
|
self.end_date_edit = QDateEdit()
|
|
|
|
|
|
self.end_date_edit.setCalendarPopup(True)
|
|
|
|
|
|
self.end_date_edit.setDisplayFormat("yyyy-MM-dd")
|
|
|
|
|
|
self.end_date_edit.setDate(QDate(2025, 12, 15)) # 默认当前数据最后日期
|
|
|
|
|
|
control_layout.addWidget(self.end_date_edit)
|
|
|
|
|
|
|
|
|
|
|
|
# 刷新按钮
|
|
|
|
|
|
self.refresh_btn = QPushButton("刷新")
|
|
|
|
|
|
self.refresh_btn.clicked.connect(self.load_data)
|
|
|
|
|
|
control_layout.addWidget(self.refresh_btn)
|
|
|
|
|
|
|
|
|
|
|
|
# 下载按钮
|
|
|
|
|
|
self.download_btn = QPushButton("下载数据")
|
|
|
|
|
|
self.download_btn.clicked.connect(self.download_data)
|
|
|
|
|
|
control_layout.addWidget(self.download_btn)
|
|
|
|
|
|
|
|
|
|
|
|
# 说明文字
|
|
|
|
|
|
control_layout.addWidget(QLabel(" | 提示: 按←→键移动, ↑↓键缩放, Home/End跳转"))
|
|
|
|
|
|
|
|
|
|
|
|
control_layout.addStretch()
|
|
|
|
|
|
layout.addLayout(control_layout)
|
|
|
|
|
|
|
|
|
|
|
|
# K线画布
|
|
|
|
|
|
self.canvas = KlineCanvas(self)
|
|
|
|
|
|
|
|
|
|
|
|
# 添加导航工具栏(缩放、平移等)
|
|
|
|
|
|
self.toolbar = NavigationToolbar2QT(self.canvas, self)
|
|
|
|
|
|
layout.addWidget(self.toolbar)
|
|
|
|
|
|
|
|
|
|
|
|
layout.addWidget(self.canvas)
|
|
|
|
|
|
|
|
|
|
|
|
# 状态栏
|
|
|
|
|
|
self._show_status("就绪")
|
|
|
|
|
|
|
|
|
|
|
|
# 加载初始数据
|
|
|
|
|
|
self.load_data()
|
|
|
|
|
|
|
|
|
|
|
|
def on_period_changed(self, period):
|
|
|
|
|
|
"""周期切换时自动调整日期范围"""
|
2025-12-23 17:56:01 +08:00
|
|
|
|
if period == Period.DAY_1:
|
2025-12-22 21:10:36 +08:00
|
|
|
|
# 日线:默认一年
|
|
|
|
|
|
self.start_date_edit.setDate(QDate(2024, 1, 1))
|
|
|
|
|
|
self.end_date_edit.setDate(QDate(2025, 12, 15))
|
|
|
|
|
|
else:
|
|
|
|
|
|
# 分钟线:默认最近15天
|
|
|
|
|
|
self.start_date_edit.setDate(QDate(2025, 12, 1))
|
|
|
|
|
|
self.end_date_edit.setDate(QDate(2025, 12, 15))
|
|
|
|
|
|
|
|
|
|
|
|
def load_data(self):
|
|
|
|
|
|
"""异步加载K线数据"""
|
|
|
|
|
|
# 防止重复加载
|
|
|
|
|
|
if self.loading:
|
|
|
|
|
|
QMessageBox.warning(self, "提示", "数据加载中,请稍候...")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
symbol = self.symbol_combo.currentText()
|
|
|
|
|
|
period = self.period_combo.currentText()
|
|
|
|
|
|
|
|
|
|
|
|
# 从日期选择器获取日期范围
|
|
|
|
|
|
start_qdate = self.start_date_edit.date()
|
|
|
|
|
|
end_qdate = self.end_date_edit.date()
|
|
|
|
|
|
start_date = datetime(
|
|
|
|
|
|
start_qdate.year(), start_qdate.month(), start_qdate.day()
|
|
|
|
|
|
)
|
|
|
|
|
|
end_date = datetime(end_qdate.year(), end_qdate.month(), end_qdate.day())
|
|
|
|
|
|
|
|
|
|
|
|
# 验证日期范围
|
|
|
|
|
|
if start_date > end_date:
|
|
|
|
|
|
QMessageBox.warning(self, "错误", "开始日期不能大于结束日期")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 设置加载状态
|
|
|
|
|
|
self.loading = True
|
|
|
|
|
|
self.refresh_btn.setEnabled(False)
|
|
|
|
|
|
self.refresh_btn.setText("加载中...")
|
|
|
|
|
|
self._show_status(
|
|
|
|
|
|
f"正在加载 {symbol} {period} {start_date.date()} ~ {end_date.date()} 数据..."
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 创建并启动异步加载线程
|
|
|
|
|
|
self.load_thread = DataLoadThread(
|
|
|
|
|
|
self.data_service, symbol, period, start_date, end_date
|
|
|
|
|
|
)
|
|
|
|
|
|
self.load_thread.progress.connect(self.on_load_progress)
|
|
|
|
|
|
self.load_thread.finished.connect(self.on_load_finished)
|
|
|
|
|
|
self.load_thread.start()
|
|
|
|
|
|
|
|
|
|
|
|
def on_load_progress(self, message):
|
|
|
|
|
|
"""加载进度更新"""
|
|
|
|
|
|
self._show_status(message)
|
|
|
|
|
|
|
|
|
|
|
|
def on_load_finished(self, df, error_msg):
|
|
|
|
|
|
"""数据加载完成回调"""
|
|
|
|
|
|
# 恢复加载状态
|
|
|
|
|
|
self.loading = False
|
|
|
|
|
|
self.refresh_btn.setEnabled(True)
|
|
|
|
|
|
self.refresh_btn.setText("刷新")
|
|
|
|
|
|
|
|
|
|
|
|
if error_msg:
|
|
|
|
|
|
# 加载失败
|
|
|
|
|
|
self._show_status(error_msg)
|
|
|
|
|
|
QMessageBox.critical(self, "错误", error_msg)
|
|
|
|
|
|
elif df is not None:
|
|
|
|
|
|
# 加载成功
|
|
|
|
|
|
symbol = self.symbol_combo.currentText()
|
|
|
|
|
|
period = self.period_combo.currentText()
|
|
|
|
|
|
|
|
|
|
|
|
title = f"{symbol} {period} K线图"
|
|
|
|
|
|
self.canvas.plot_kline(df, title)
|
|
|
|
|
|
|
|
|
|
|
|
success_msg = f"加载成功: {len(df)} 条数据 | 按←→键移动, ↑↓键缩放"
|
|
|
|
|
|
self._show_status(success_msg)
|
|
|
|
|
|
|
|
|
|
|
|
# 弹出成功提示
|
|
|
|
|
|
QMessageBox.information(
|
|
|
|
|
|
self,
|
|
|
|
|
|
"加载完成",
|
|
|
|
|
|
f"数据加载完成\n\n"
|
|
|
|
|
|
f"标的: {symbol}\n"
|
|
|
|
|
|
f"周期: {period}\n"
|
|
|
|
|
|
f"数据量: {len(df)} 条\n"
|
|
|
|
|
|
f"日期范围: {df.index[0]} ~ {df.index[-1]}",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def download_data(self):
|
|
|
|
|
|
"""异步下载数据"""
|
|
|
|
|
|
# 防止重复下载
|
|
|
|
|
|
if self.downloading:
|
|
|
|
|
|
QMessageBox.warning(self, "提示", "数据下载中,请稍候...")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
if self.loading:
|
|
|
|
|
|
QMessageBox.warning(self, "提示", "数据加载中,请稍候...")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 获取参数
|
|
|
|
|
|
symbol = self.symbol_combo.currentText()
|
|
|
|
|
|
period = self.period_combo.currentText()
|
|
|
|
|
|
start_qdate = self.start_date_edit.date()
|
|
|
|
|
|
end_qdate = self.end_date_edit.date()
|
|
|
|
|
|
start_date = datetime(
|
|
|
|
|
|
start_qdate.year(), start_qdate.month(), start_qdate.day()
|
|
|
|
|
|
)
|
|
|
|
|
|
end_date = datetime(end_qdate.year(), end_qdate.month(), end_qdate.day())
|
|
|
|
|
|
|
|
|
|
|
|
# 验证日期范围
|
|
|
|
|
|
if start_date > end_date:
|
|
|
|
|
|
QMessageBox.warning(self, "错误", "开始日期不能大于结束日期")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 确认下载
|
|
|
|
|
|
reply = QMessageBox.question(
|
|
|
|
|
|
self,
|
|
|
|
|
|
"确认下载",
|
|
|
|
|
|
f"将从数据源下载以下数据到数据库:\n\n"
|
|
|
|
|
|
f"标的: {symbol}\n"
|
|
|
|
|
|
f"周期: {period}\n"
|
|
|
|
|
|
f"日期范围: {start_date.date()} ~ {end_date.date()}\n\n"
|
|
|
|
|
|
f"是否继续?",
|
|
|
|
|
|
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if reply != QMessageBox.StandardButton.Yes:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# 设置下载状态
|
|
|
|
|
|
self.downloading = True
|
|
|
|
|
|
self.download_btn.setEnabled(False)
|
|
|
|
|
|
self.download_btn.setText("下载中...")
|
|
|
|
|
|
self.refresh_btn.setEnabled(False)
|
|
|
|
|
|
self._show_status(
|
|
|
|
|
|
f"正在下载 {symbol} {period} {start_date.date()} ~ {end_date.date()} 数据..."
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 创建并启动异步下载线程
|
|
|
|
|
|
self.download_thread = DataDownloadThread(
|
|
|
|
|
|
self.data_service, [symbol], [period], start_date, end_date
|
|
|
|
|
|
)
|
|
|
|
|
|
self.download_thread.progress.connect(self.on_download_progress)
|
|
|
|
|
|
self.download_thread.finished.connect(self.on_download_finished)
|
|
|
|
|
|
self.download_thread.start()
|
|
|
|
|
|
|
|
|
|
|
|
def on_download_progress(self, message):
|
|
|
|
|
|
"""下载进度更新"""
|
|
|
|
|
|
self._show_status(message)
|
|
|
|
|
|
|
|
|
|
|
|
def on_download_finished(self, success, message):
|
|
|
|
|
|
"""数据下载完成回调"""
|
|
|
|
|
|
# 恢复下载状态
|
|
|
|
|
|
self.downloading = False
|
|
|
|
|
|
self.download_btn.setEnabled(True)
|
|
|
|
|
|
self.download_btn.setText("下载数据")
|
|
|
|
|
|
self.refresh_btn.setEnabled(True)
|
|
|
|
|
|
|
|
|
|
|
|
if success:
|
|
|
|
|
|
# 下载成功,清空cache以便加载新数据
|
|
|
|
|
|
symbol = self.symbol_combo.currentText()
|
|
|
|
|
|
period = self.period_combo.currentText()
|
|
|
|
|
|
cache_key = f"{symbol}_{period}"
|
|
|
|
|
|
|
|
|
|
|
|
# 清空该标的的缓存
|
|
|
|
|
|
if hasattr(self.data_service, "cache") and hasattr(
|
|
|
|
|
|
self.data_service.cache, "_cache"
|
|
|
|
|
|
):
|
|
|
|
|
|
if cache_key in self.data_service.cache._cache:
|
|
|
|
|
|
del self.data_service.cache._cache[cache_key]
|
|
|
|
|
|
print(f"已清空缓存: {cache_key}")
|
|
|
|
|
|
|
|
|
|
|
|
self._show_status(message)
|
|
|
|
|
|
|
|
|
|
|
|
# 自动刷新数据
|
|
|
|
|
|
self.load_data()
|
|
|
|
|
|
else:
|
|
|
|
|
|
# 下载失败
|
|
|
|
|
|
self._show_status(message)
|
|
|
|
|
|
QMessageBox.critical(self, "错误", message)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
|
"""主函数"""
|
|
|
|
|
|
print("初始化K线查看器...")
|
|
|
|
|
|
|
|
|
|
|
|
# 检查环境
|
|
|
|
|
|
if "py311" not in sys.executable.lower():
|
|
|
|
|
|
print("警告: 建议使用py311环境")
|
|
|
|
|
|
|
|
|
|
|
|
# 加载配置和DataService
|
|
|
|
|
|
try:
|
|
|
|
|
|
config = Config()
|
|
|
|
|
|
config.load_with_global("configs/backtest.yaml")
|
|
|
|
|
|
data_service = DataService.from_config(config)
|
|
|
|
|
|
print("✓ DataService初始化成功")
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(f"✗ DataService初始化失败: {e}")
|
|
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
# 创建应用
|
|
|
|
|
|
app = QApplication(sys.argv)
|
|
|
|
|
|
window = SimpleKlineViewer(data_service)
|
|
|
|
|
|
window.show()
|
|
|
|
|
|
|
|
|
|
|
|
print("K线查看器启动成功")
|
|
|
|
|
|
sys.exit(app.exec())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
main()
|