QTrade/simple_kline_viewer.py
cuizhan 37a5df8bf6 重构配置系统:改为Config/Logger单例模式,拆分环境配置文件
主要改动:
1. Config类改为单例模式,支持根据global.yaml的current_mode自动加载环境配置
2. Logger类改为单例模式,通过类方法直接访问
3. 拆分配置文件:global.yaml仅指定模式,backtest.yaml/simulation.yaml/production.yaml存储各环境配置
4. 移除所有config参数传递,使用Config.get()直接访问
5. 移除所有logger实例传递,使用Logger.info()等类方法直接访问
6. 修复初始化顺序:Config.initialize() -> Logger.initialize() -> 其他组件
7. 修复Logger参数默认值,确保所有方法可正常调用
8. 新增三个环境配置文件结构统一,只有参数值不同
9. 客户端URL端口修正为8030(回测)/8020(模拟)/8010(实盘)

配置文件变更:
- configs/global.yaml:简化为仅包含current_mode
- configs/backtest.yaml:回测环境完整配置
- configs/simulation.yaml:模拟环境完整配置
- configs/production.yaml:实盘环境完整配置

代码重构:
- src/core/config.py:单例模式,自动加载环境配置
- src/core/logger.py:单例模式,类方法访问
- 所有模块:移除config/logger参数,使用单例访问
2026-01-12 19:07:23 +08:00

1094 lines
37 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
简单K线查看器
使用DataService直接显示K线数据
支持键盘导航和缩放
"""
import sys
import os
import io
import traceback
from datetime import datetime
from typing import Any
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QLabel,
QComboBox,
QPushButton,
QDateEdit,
QMessageBox,
QTabWidget,
)
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
from src.core.constants import Period
# 设置控制台编码为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: Any = None # DataFrame类型
self.current_start = 0 # 当前显示起始位置
self.current_end = 100 # 当前显示结束位置
self.display_count = 100 # 默认显示100条
# 加载指标配置参数
self._load_indicator_config()
# 创建专业黑色主题样式(红涨绿跌)
self.style = mpf.make_mpf_style(
base_mpf_style="nightclouds",
marketcolors=mpf.make_marketcolors(
up="#ff0000", # 红色上涨
down="#00ff00", # 绿色下跌
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)
# 防止resize过于频繁触发重绘
self._resize_timer = None
# 鼠标悬停显示数据
self.current_display_data: Any = None # 当前显示的数据(DataFrame)
self.current_macd_data: Any = None # MACD数据(DataFrame)
self.current_rsi_data: Any = None # RSI数据(DataFrame)
self.crosshair_vlines: list = [] # 十字光标垂直线列表(多个子图)
self.info_text: Any = None # 信息文本
# 连接鼠标移动事件
self.mpl_connect("motion_notify_event", self.on_mouse_move)
def _load_indicator_config(self):
"""加载指标配置参数"""
try:
config = Config("configs/global.yaml")
indicators_config = config.get("indicators")
if not indicators_config:
raise ValueError("配置文件中未找到 'indicators' 配置项")
# 加载MACD参数
self._load_macd_config(indicators_config)
# 加载RSI参数
self._load_rsi_config(indicators_config)
except Exception as e:
print(f"\n❌ 配置文件读取失败: {e}")
print("请检查 configs/global.yaml 文件中的 indicators 配置项")
sys.exit(1)
def _load_macd_config(self, indicators_config):
"""加载MACD配置"""
macd_config = indicators_config.get("macd")
if not macd_config:
raise ValueError("配置文件中未找到 'indicators.macd' 配置项")
required_keys = ["fast_period", "slow_period", "signal_period"]
for key in required_keys:
if key not in macd_config:
raise ValueError(f"配置文件中未找到 'indicators.macd.{key}'")
self.macd_fast = macd_config["fast_period"]
self.macd_slow = macd_config["slow_period"]
self.macd_signal = macd_config["signal_period"]
print(
f"[配置] MACD参数: fast={self.macd_fast}, slow={self.macd_slow}, signal={self.macd_signal}"
)
def _load_rsi_config(self, indicators_config):
"""加载RSI配置"""
rsi_config = indicators_config.get("rsi")
if not rsi_config:
raise ValueError("配置文件中未找到 'indicators.rsi' 配置项")
required_keys = ["fast", "mid", "slow"]
for key in required_keys:
if key not in rsi_config:
raise ValueError(f"配置文件中未找到 'indicators.rsi.{key}'")
self.rsi_fast = rsi_config["fast"]
self.rsi_mid = rsi_config["mid"]
self.rsi_slow = rsi_config["slow"]
print(
f"[配置] RSI参数: fast={self.rsi_fast}, mid={self.rsi_mid}, slow={self.rsi_slow}"
)
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):
# 构建信息文本
info_text = self._build_hover_info(x_index)
# 清除旧的十字光标和文本
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 # 忽略鼠标移动时的错误
def _build_hover_info(self, x_index):
"""构建鼠标悬停时的信息文本"""
if self.current_display_data is None:
return ""
data_row = self.current_display_data.iloc[x_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}"
)
return info_text
def keyPressEvent(self, event):
"""处理键盘事件"""
if self.full_data is None or len(self.full_data) == 0:
return
key = event.key()
if key == Qt.Key.Key_Left:
self._handle_scroll_left()
elif key == Qt.Key.Key_Right:
self._handle_scroll_right()
elif key == Qt.Key.Key_Up:
self._handle_zoom_in()
elif key == Qt.Key.Key_Down:
self._handle_zoom_out()
elif key == Qt.Key.Key_Home:
self._handle_goto_start()
elif key == Qt.Key.Key_End:
self._handle_goto_end()
def _handle_scroll_left(self):
"""向左滚动"""
if self.full_data is None:
return
step = max(1, self.display_count // 10)
total_len = len(self.full_data)
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()
def _handle_scroll_right(self):
"""向右滚动"""
if self.full_data is None:
return
step = max(1, self.display_count // 10)
total_len = len(self.full_data)
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()
def _handle_zoom_in(self):
"""放大显示(显示更少数据)"""
if self.full_data is None:
return
total_len = len(self.full_data)
old_count = self.display_count
self.display_count = max(5, self.display_count - 5)
if self.display_count != old_count:
self._recenter_view(total_len)
def _handle_zoom_out(self):
"""缩小显示(显示更多数据)"""
if self.full_data is None:
return
total_len = len(self.full_data)
old_count = self.display_count
self.display_count = min(total_len, self.display_count + 5)
if self.display_count != old_count:
self._recenter_view(total_len)
def _handle_goto_start(self):
"""跳转到开始"""
if self.full_data is None:
return
total_len = len(self.full_data)
self.current_start = 0
self.current_end = min(total_len, self.display_count)
self.update_display()
def _handle_goto_end(self):
"""跳转到结束"""
if self.full_data is None:
return
total_len = len(self.full_data)
self.current_start = max(0, total_len - self.display_count)
self.current_end = total_len
self.update_display()
def _recenter_view(self, total_len):
"""缩放时重新居中视图"""
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()
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
# 数据量检查
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)
# 清空旧图
self.fig.clear()
# 准备数据 - 用于绘制(保留原始索引用于时间轴)
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控制高度比例:5:2:2:2,增加指标显示区域
from matplotlib import gridspec
gs = gridspec.GridSpec(4, 1, height_ratios=[5, 2, 2, 2], hspace=0.1)
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")
# 根据数据量动态选择均线周期
# 避免均线周期大于数据量导致的问题
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线(不包含均线)
mpf.plot(
plot_df,
type="candle",
style=self.style,
volume=ax2,
ax=ax1,
warn_too_much_data=10000,
)
# 手动绘制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",
)
# 计算并绘制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 _calculate_macd(self, df):
"""计算MACD指标"""
import pandas as pd
exp1 = df["close"].ewm(span=self.macd_fast, adjust=False).mean()
exp2 = df["close"].ewm(span=self.macd_slow, adjust=False).mean()
macd = exp1 - exp2
signal = macd.ewm(span=self.macd_signal, adjust=False).mean()
histogram = macd - signal
return pd.DataFrame(
{"dif": macd, "dea": signal, "histogram": histogram}
).reset_index(drop=True)
def _calculate_rsi(self, df, period):
"""计算单个周期的RSI"""
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))
return rsi
def _plot_macd(self, df, ax):
"""绘制MACD指标(使用配置文件参数)"""
try:
# 数据量检查
min_length = self.macd_slow + self.macd_signal
if len(df) < min_length:
return
# 计算MACD
self.current_macd_data = self._calculate_macd(df)
# 提取数据
macd = self.current_macd_data["dif"]
signal = self.current_macd_data["dea"]
histogram = self.current_macd_data["histogram"]
# 绘制MACD柱状图(红涨绿跌)
colors = ["#ff0000" if x >= 0 else "#00ff00" for x in histogram]
ax.bar(
range(len(histogram)),
histogram.values,
color=colors,
alpha=0.6,
width=0.8,
)
# 绘制MACD和信号线(快线白色,慢线黄色)
ax.plot(macd.values, color="#ffffff", linewidth=1.5, label="MACD(DIF)")
ax.plot(signal.values, color="#ffff00", linewidth=1.5, label="DEA")
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}")
traceback.print_exc()
def _plot_rsi(self, df, ax):
"""绘制RSI指标(使用配置文件参数)"""
try:
import pandas as pd
# 数据量检查
if len(df) < self.rsi_slow + 1:
return
# RSI颜色配置
colors = {
self.rsi_fast: "#ffff00", # 快线:黄色
self.rsi_mid: "#00ff00", # 中线:绿色
self.rsi_slow: "#0000ff", # 慢线:蓝色
}
# 计算并绘制RSI
rsi_data = {}
for period in [self.rsi_fast, self.rsi_mid, self.rsi_slow]:
rsi = self._calculate_rsi(df, period)
rsi_data[f"rsi{period}"] = rsi
ax.plot(
rsi.values,
color=colors[period],
linewidth=1.5,
label=f"RSI{period}",
)
# 保存RSI数据供鼠标悬停使用
self.current_rsi_data = pd.DataFrame(rsi_data).reset_index(drop=True)
# 绘制参考线
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()
class DataLoadThread(QThread):
"""异步数据加载线程"""
# 定义信号
finished = pyqtSignal(object, str, object) # (dataframe, error_message, canvas)
progress = pyqtSignal(str) # 进度信息
def __init__(self, data_service, symbol, period, start_date, end_date, canvas):
super().__init__()
self.data_service = data_service
self.symbol = symbol
self.period = period
self.start_date = start_date
self.end_date = end_date
self.canvas = canvas
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, self.canvas)
else:
print(f"查询成功: {len(df)} 条数据")
print(f"日期范围: {df.index[0]} ~ {df.index[-1]}")
self.finished.emit(df, "", self.canvas)
except Exception as e:
error_msg = f"加载失败: {str(e)}"
print(error_msg)
import traceback
traceback.print_exc()
self.finished.emit(None, error_msg, self.canvas)
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(
f"[下载线程] 下载参数: symbols={self.symbols}, periods={self.periods}, {self.start_date} ~ {self.end_date}"
)
print("[下载线程] 开始调用 download_klines...")
self.data_service.download_klines(
symbols=self.symbols,
start_date=self.start_date,
end_date=self.end_date,
periods=self.periods,
)
print("[下载线程] download_klines 调用完成")
success_msg = (
f"下载完成: {len(self.symbols)}个标的, {len(self.periods)}个周期"
)
print(f"[下载线程] {success_msg}")
self.finished.emit(True, success_msg)
except Exception as e:
error_msg = f"下载失败: {str(e)}"
print(f"[下载线程] {error_msg}")
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"])
self.symbol_combo.currentTextChanged.connect(self.on_symbol_changed)
control_layout.addWidget(self.symbol_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")
today = datetime.now()
self.end_date_edit.setDate(
QDate(today.year, today.month, today.day)
) # 默认今天
control_layout.addWidget(self.end_date_edit)
# 下载所有周期按钮
self.download_btn = QPushButton("下载所有周期数据")
self.download_btn.clicked.connect(self.download_all_periods)
control_layout.addWidget(self.download_btn)
# 说明文字
control_layout.addWidget(QLabel(" | 提示: 按←→键移动, ↑↓键缩放, Home/End跳转"))
control_layout.addStretch()
layout.addLayout(control_layout)
# 周期Tab标签页
self.period_tabs = QTabWidget()
self.period_tabs.currentChanged.connect(self.on_tab_changed)
# 创建各周期的Tab
self.period_list = [
("1分钟", Period.MIN_1),
("5分钟", Period.MIN_5),
("15分钟", Period.MIN_15),
("30分钟", Period.MIN_30),
("60分钟", Period.MIN_60),
("日线", Period.DAY_1),
]
# 为每个周期创建画布
self.canvases = {}
self.toolbars = {}
for tab_name, period in self.period_list:
tab_widget = QWidget()
tab_layout = QVBoxLayout(tab_widget)
# 创建该周期的画布
canvas = KlineCanvas(self)
toolbar = NavigationToolbar2QT(canvas, self)
tab_layout.addWidget(toolbar)
tab_layout.addWidget(canvas)
self.canvases[period] = canvas
self.toolbars[period] = toolbar
self.period_tabs.addTab(tab_widget, tab_name)
# 默认选择日线Tab
self.period_tabs.setCurrentIndex(5) # 日线是第6个Tab
layout.addWidget(self.period_tabs)
# 移除原来的单一画布和工具栏
# self.canvas = KlineCanvas(self)
# self.toolbar = NavigationToolbar2QT(self.canvas, self)
# 状态栏
self._show_status("就绪")
# 加载初始数据(当前Tab)
self.load_current_tab_data()
def on_tab_changed(self, index):
"""Tab切换时自动加载对应周期的数据"""
if index < 0 or index >= len(self.period_list):
return
# 切换Tab时直接加载数据,不修改时间范围
self.load_current_tab_data()
def on_symbol_changed(self, symbol):
"""标的切换时自动加载当前Tab的数据"""
self.load_current_tab_data()
def get_current_period(self):
"""获取当前选中的周期"""
index = self.period_tabs.currentIndex()
if index < 0 or index >= len(self.period_list):
return Period.DAY_1
return self.period_list[index][1]
def get_current_canvas(self):
"""获取当前周期的画布"""
period = self.get_current_period()
return self.canvases.get(period)
def load_current_tab_data(self):
"""加载当前Tab的数据"""
period = self.get_current_period()
canvas = self.get_current_canvas()
if canvas:
self.load_data(period, canvas)
def load_data(self, period=None, canvas=None):
"""异步加载K线数据"""
# 防止重复加载
if self.loading:
QMessageBox.warning(self, "提示", "数据加载中,请稍候...")
return
symbol = self.symbol_combo.currentText()
if period is None:
period = self.get_current_period()
if canvas is None:
canvas = self.get_current_canvas()
# 从日期选择器获取日期范围
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.download_btn.setEnabled(False)
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, canvas
)
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, canvas):
"""数据加载完成回调"""
# 恢复加载状态
self.loading = False
self.download_btn.setEnabled(True)
if error_msg:
# 加载失败
self._show_status(error_msg)
QMessageBox.critical(self, "错误", error_msg)
elif df is not None and canvas is not None:
# 加载成功
symbol = self.symbol_combo.currentText()
period = self.get_current_period()
title = f"{symbol} {period} K线图"
canvas.plot_kline(df, title)
success_msg = f"加载成功: {len(df)} 条数据 | 按←→键移动, ↑↓键缩放"
self._show_status(success_msg)
def download_all_periods(self):
"""异步下载所有周期的数据"""
# 防止重复下载
if self.downloading:
QMessageBox.warning(self, "提示", "数据下载中,请稍候...")
return
if self.loading:
QMessageBox.warning(self, "提示", "数据加载中,请稍候...")
return
# 获取参数
symbol = self.symbol_combo.currentText()
all_periods = [period for _, period in self.period_list]
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"周期: 所有周期 ({', '.join(all_periods)})\n"
f"日期范围: {start_date.date()} ~ {end_date.date()}\n\n"
f"下载后会自动计算指标并保存\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._show_status(
f"正在下载 {symbol} 所有周期 {start_date.date()} ~ {end_date.date()} 数据..."
)
# 创建并启动异步下载线程
self.download_thread = DataDownloadThread(
self.data_service, [symbol], all_periods, 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("下载所有周期数据")
if success:
# 下载成功,清空所有周期的缓存
symbol = self.symbol_combo.currentText()
# 清空该标的所有周期的缓存
if hasattr(self.data_service, "cache") and hasattr(
self.data_service.cache, "_cache"
):
for _, period in self.period_list:
cache_key = f"{symbol}_{period}"
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)
# 自动刷新当前Tab的数据
self.load_current_tab_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("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()