""" 简单K线查看器 使用DataService直接显示K线数据 支持键盘导航和缩放 """ import sys import os import io import traceback from datetime import datetime from datetime import datetime 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 = None self.current_start = 0 # 当前显示起始位置 self.current_end = 100 # 当前显示结束位置 self.display_count = 100 # 默认显示100条 # 加载指标配置参数 - 不使用默认值,读取失败直接报错 try: config = Config("configs/global.yaml") indicators_config = config.get("indicators") if not indicators_config: raise ValueError("配置文件中未找到 'indicators' 配置项") # MACD参数 macd_config = indicators_config.get("macd") if not macd_config: raise ValueError("配置文件中未找到 'indicators.macd' 配置项") if "fast_period" not in macd_config: raise ValueError("配置文件中未找到 'indicators.macd.fast_period'") if "slow_period" not in macd_config: raise ValueError("配置文件中未找到 'indicators.macd.slow_period'") if "signal_period" not in macd_config: raise ValueError("配置文件中未找到 'indicators.macd.signal_period'") 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}" ) # RSI参数 rsi_config = indicators_config.get("rsi") if not rsi_config: raise ValueError("配置文件中未找到 'indicators.rsi' 配置项") if "fast" not in rsi_config: raise ValueError("配置文件中未找到 'indicators.rsi.fast'") if "mid" not in rsi_config: raise ValueError("配置文件中未找到 'indicators.rsi.mid'") if "slow" not in rsi_config: raise ValueError("配置文件中未找到 'indicators.rsi.slow'") 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}" ) except Exception as e: print(f"\n❌ 配置文件读取失败: {e}") print("请检查 configs/global.yaml 文件中的 indicators 配置项") import sys sys.exit(1) # 创建专业黑色主题样式(红涨绿跌) 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 = 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 # 忽略鼠标移动时的错误 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: # 跳转到末尾 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 # 数据量检查 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 _plot_macd(self, df, ax): """绘制MACD指标(使用配置文件参数)""" try: import pandas as pd # 数据量检查 min_length = self.macd_slow + self.macd_signal if len(df) < min_length: return # 计算MACD(使用配置文件参数) 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 # 保存MACD数据供鼠标悬停使用 self.current_macd_data = pd.DataFrame( {"dif": macd, "dea": signal, "histogram": histogram} ).reset_index(drop=True) # 绘制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="#00ffff", 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_data = {} colors = { self.rsi_fast: "#ffff00", self.rsi_mid: "#00ffff", self.rsi_slow: "#ff00ff", } # 计算RSI(使用配置文件参数) for period in [self.rsi_fast, self.rsi_mid, self.rsi_slow]: 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)) # 保存RSI数据 rsi_data[f"rsi{period}"] = rsi # 绘制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_name, period = self.period_list[index] # 调整日期范围 today = datetime.now() if period == Period.DAY_1: # 日线:默认一年 self.start_date_edit.setDate(QDate(2024, 1, 1)) self.end_date_edit.setDate(QDate(today.year, today.month, today.day)) else: # 分钟线:默认最近15天 from datetime import timedelta start_date = today - timedelta(days=15) self.start_date_edit.setDate( QDate(start_date.year, start_date.month, start_date.day) ) self.end_date_edit.setDate(QDate(today.year, today.month, today.day)) # 自动加载数据 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() 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()