diff --git a/simple_kline_viewer.py b/simple_kline_viewer.py index e2277ab..fba5d4e 100644 --- a/simple_kline_viewer.py +++ b/simple_kline_viewer.py @@ -7,6 +7,7 @@ import sys import os import io +import traceback from datetime import datetime from PyQt6.QtWidgets import ( diff --git a/src/gui/adapters/__init__.py b/src/gui/adapters/__init__.py deleted file mode 100644 index ad07214..0000000 --- a/src/gui/adapters/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -Adapter Layer - 适配层 -负责与DataService对接 -""" diff --git a/src/gui/adapters/data_adapter.py b/src/gui/adapters/data_adapter.py deleted file mode 100644 index ac093ea..0000000 --- a/src/gui/adapters/data_adapter.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -数据适配器基类 -负责与DataService对接,封装数据访问逻辑 -""" - -from typing import Optional -import pandas as pd -from datetime import datetime - - -class DataAdapter: - """ - 数据适配器 - Adapter层核心类 - - 职责: - 1. 与DataService对接 - 2. 数据格式转换 - 3. 异步数据加载 - 4. 错误处理 - """ - - def __init__(self, data_service=None): - """ - 初始化数据适配器 - - Args: - data_service: DataService实例(后续实现) - """ - self.data_service = data_service - - def load_klines( - self, symbol: str, period: str, start_date: datetime, end_date: datetime - ) -> Optional[pd.DataFrame]: - """ - 加载K线数据 - - Args: - symbol: 标的代码,如 '600000.SH' - period: 周期,如 '1m', '5m', '1d' - start_date: 开始时间 - end_date: 结束时间 - - Returns: - DataFrame with columns: [timestamp, open, high, low, close, volume, amount] - 如果失败返回None - """ - try: - if self.data_service is None: - print("[DataAdapter] ⚠ DataService未初始化,使用模拟数据") - return self._generate_mock_data(symbol, period, start_date, end_date) - - # 调用DataService获取真实数据 - print( - f"[DataAdapter] 加载K线数据: {symbol}, {period}, {start_date.date()} - {end_date.date()}" - ) - df = self.data_service.get_klines( - symbol=symbol, period=period, start=start_date, end=end_date - ) - - if df is None or df.empty: - print(f"[DataAdapter] ⚠ 未找到数据,使用模拟数据") - return self._generate_mock_data(symbol, period, start_date, end_date) - - print(f"[DataAdapter] ✓ 加载K线数据成功: {len(df)} 条") - return df - - except Exception as e: - print(f"[DataAdapter] ✗ 加载K线数据失败: {e}") - import traceback - - traceback.print_exc() - return self._generate_mock_data(symbol, period, start_date, end_date) - - def load_indicator( - self, - symbol: str, - period: str, - indicator_name: str, - start_date: datetime, - end_date: datetime, - ) -> Optional[pd.DataFrame]: - """ - 加载技术指标数据 - - Args: - symbol: 标的代码 - period: 周期 - indicator_name: 指标名称,如 'macd', 'kdj', 'rsi', 'boll' - start_date: 开始时间 - end_date: 结束时间 - - Returns: - DataFrame with indicator columns - 如果失败返回None - """ - try: - if self.data_service is None: - print(f"[DataAdapter] ⚠ DataService未初始化,使用模拟数据") - return self._generate_mock_indicator(indicator_name) - - # 调用DataService获取真实指标数据 - print(f"[DataAdapter] 加载指标数据: {symbol}, {period}, {indicator_name}") - df = self.data_service.storage.load_indicators( - symbol=symbol, - period=period, - indicator_name=indicator_name, - start_date=start_date, - end_date=end_date, - ) - - if df is None or df.empty: - print(f"[DataAdapter] ⚠ 未找到指标数据,使用模拟数据") - return self._generate_mock_indicator(indicator_name) - - print(f"[DataAdapter] ✓ 加载指标数据成功: {len(df)} 条") - return df - - except Exception as e: - print(f"[DataAdapter] ✗ 加载指标数据失败: {e}") - import traceback - - traceback.print_exc() - return self._generate_mock_indicator(indicator_name) - - def _generate_mock_data( - self, symbol: str, period: str, start_date: datetime, end_date: datetime - ) -> pd.DataFrame: - """生成模拟K线数据(用于测试)""" - import numpy as np - - # 生成时间序列 - date_range = pd.date_range(start=start_date, end=end_date, freq="1min") - n = len(date_range) - - # 生成模拟价格数据 - base_price = 10.0 - prices = base_price + np.cumsum(np.random.randn(n) * 0.1) - - df = pd.DataFrame( - { - "timestamp": date_range, - "open": prices, - "high": prices + np.random.rand(n) * 0.1, - "low": prices - np.random.rand(n) * 0.1, - "close": prices + np.random.randn(n) * 0.05, - "volume": np.random.randint(1000, 10000, n), - "amount": np.random.randint(10000, 100000, n), - } - ) - - df.set_index("timestamp", inplace=True) - - return df - - def _generate_mock_indicator(self, indicator_name: str) -> pd.DataFrame: - """生成模拟指标数据(用于测试)""" - import numpy as np - - n = 100 - date_range = pd.date_range(start="2025-12-01", end="2025-12-22", periods=n) - - if indicator_name == "macd": - df = pd.DataFrame( - { - "timestamp": date_range, - "macd_dif": np.random.randn(n) * 0.1, - "macd_dea": np.random.randn(n) * 0.08, - "macd_histogram": np.random.randn(n) * 0.05, - } - ) - elif indicator_name == "kdj": - df = pd.DataFrame( - { - "timestamp": date_range, - "kdj_k": 50 + np.random.randn(n) * 20, - "kdj_d": 50 + np.random.randn(n) * 18, - "kdj_j": 50 + np.random.randn(n) * 25, - } - ) - else: - df = pd.DataFrame({"timestamp": date_range, "value": np.random.randn(n)}) - - df.set_index("timestamp", inplace=True) - - return df - - def get_mock_klines( - self, symbol: str, period: str, count: int = 100 - ) -> pd.DataFrame: - """ - 获取模拟K线数据(用于测试) - - Args: - symbol: 标的代码 - period: 周期 - count: K线数量 - - Returns: - 模拟的K线DataFrame - """ - import numpy as np - - # 生成时间序列 - end_date = datetime.now() - date_range = pd.date_range(end=end_date, periods=count, freq="1min") - - # 生成模拟价格数据 - base_price = 100.0 - np.random.seed(42) - - prices = [] - current_price = base_price - - for _ in range(count): - change = np.random.randn() * 0.5 - current_price += change - - open_price = current_price - high_price = current_price + abs(np.random.randn() * 0.3) - low_price = current_price - abs(np.random.randn() * 0.3) - close_price = current_price + np.random.randn() * 0.2 - volume = np.random.randint(1000, 10000) - - prices.append( - { - "open": open_price, - "high": high_price, - "low": low_price, - "close": close_price, - "volume": volume, - } - ) - - current_price = close_price - - df = pd.DataFrame(prices, index=date_range) - return df - - def get_mock_indicator(self, indicator_name: str, count: int = 100) -> pd.DataFrame: - """ - 获取模拟指标数据(用于测试) - - Args: - indicator_name: 指标名称 ('macd', 'kdj', 'rsi', 'boll') - count: 数据点数量 - - Returns: - 模拟的指标DataFrame - """ - import numpy as np - - end_date = datetime.now() - date_range = pd.date_range(end=end_date, periods=count, freq="1min") - - if indicator_name == "macd": - df = pd.DataFrame( - { - "dif": np.random.randn(count).cumsum() * 0.1, - "dea": np.random.randn(count).cumsum() * 0.1, - "macd": np.random.randn(count) * 0.2, - }, - index=date_range, - ) - - elif indicator_name == "kdj": - k = np.random.rand(count) * 100 - d = np.random.rand(count) * 100 - j = 3 * k - 2 * d - df = pd.DataFrame({"k": k, "d": d, "j": j}, index=date_range) - - elif indicator_name == "rsi": - df = pd.DataFrame( - { - "rsi_6": 30 + np.random.rand(count) * 40, - "rsi_12": 35 + np.random.rand(count) * 30, - "rsi_24": 40 + np.random.rand(count) * 20, - }, - index=date_range, - ) - - elif indicator_name == "boll": - mid = 100 + np.random.randn(count).cumsum() * 0.5 - width = 2.0 - df = pd.DataFrame( - {"upper": mid + width, "mid": mid, "lower": mid - width}, - index=date_range, - ) - - else: - raise ValueError(f"Unknown indicator: {indicator_name}") - - return df diff --git a/src/gui/app.py b/src/gui/app.py deleted file mode 100644 index 23fa7ab..0000000 --- a/src/gui/app.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -QTrade GUI应用入口 -""" - -import sys -import os - -# 添加项目根目录到Python路径 -project_root = os.path.dirname( - os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -) -if project_root not in sys.path: - sys.path.insert(0, project_root) - -from PyQt6.QtWidgets import QApplication -from src.gui.presentation.main_window import MainWindow -from src.gui.adapters.data_adapter import DataAdapter -from src.gui.controllers.chart_controller import ChartController -from src.core.config import Config -from src.data_service import DataService - - -def main(): - """应用主函数""" - print("[App] 启动QTrade GUI应用...") - - # 创建应用实例 - app = QApplication(sys.argv) - - # 设置应用信息 - app.setApplicationName("QTrade") - app.setOrganizationName("QTrade Team") - app.setApplicationVersion("0.1.0 MVP") - - print("[App] 初始化DataService...") - - # 加载配置并创建DataService - try: - config = Config() - config.load_with_global("configs/backtest.yaml") - data_service = DataService.from_config(config) - print("[App] ✓ DataService初始化成功") - except Exception as e: - print(f"[App] ✗ DataService初始化失败: {e}") - data_service = None - - print("[App] 初始化适配器和控制器...") - - # 创建适配器层(注入真实的DataService) - data_adapter = DataAdapter(data_service) - - # 创建控制器层 - chart_controller = ChartController(data_adapter) - - # 创建并显示主窗口 - print("[App] 创建主窗口...") - window = MainWindow(chart_controller) - window.show() - - print("[App] 应用启动完成!") - - # 进入事件循环 - sys.exit(app.exec()) - - -if __name__ == "__main__": - main() diff --git a/src/gui/controllers/__init__.py b/src/gui/controllers/__init__.py deleted file mode 100644 index 98dc501..0000000 --- a/src/gui/controllers/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -Controller Layer - 控制层 -负责事件处理和状态管理 -""" diff --git a/src/gui/controllers/chart_controller.py b/src/gui/controllers/chart_controller.py deleted file mode 100644 index 4279927..0000000 --- a/src/gui/controllers/chart_controller.py +++ /dev/null @@ -1,101 +0,0 @@ -""" -图表控制器 -负责图表相关操作和数据加载 -""" - -from PyQt6.QtCore import QObject, pyqtSignal -from datetime import datetime, timedelta -import pandas as pd - - -class ChartController(QObject): - """ - 图表控制器 - 负责图表数据和交互 - - 职责: - 1. 标的/周期切换 - 2. 数据加载协调 - 3. 图表更新通知 - """ - - # 定义信号 - kline_loaded = pyqtSignal(object) # K线数据加载完成,参数为DataFrame - indicator_loaded = pyqtSignal( - str, object - ) # 指标加载完成,参数为(指标名, DataFrame) - loading_started = pyqtSignal(str) # 加载开始 - loading_finished = pyqtSignal(bool, str) # 加载完成,参数为(成功/失败, 消息) - - def __init__(self, data_adapter): - """ - 初始化图表控制器 - - Args: - data_adapter: DataAdapter实例 - """ - super().__init__() - self.data_adapter = data_adapter - - # 当前状态 - self.current_symbol = "600000.SH" - self.current_period = "1m" - - def load_chart_data(self, symbol: str, period: str, indicators: list = None): - """ - 加载图表数据(K线 + 指标) - - Args: - symbol: 标的代码 - period: 周期 - indicators: 需要加载的指标列表,如 ['macd', 'kdj'] - """ - try: - self.current_symbol = symbol - self.current_period = period - - self.loading_started.emit(f"正在加载 {symbol} {period} 数据...") - - # 默认加载最近的数据 - end_date = datetime.now() - start_date = end_date - timedelta(days=30) # 最近30天 - - # 加载K线数据 - print(f"[ChartController] 加载K线数据: {symbol} {period}") - df_kline = self.data_adapter.load_klines( - symbol, period, start_date, end_date - ) - - if df_kline is not None and not df_kline.empty: - self.kline_loaded.emit(df_kline) - print(f"[ChartController] K线数据加载成功,共 {len(df_kline)} 条") - else: - self.loading_finished.emit(False, "K线数据加载失败") - return - - # 加载指标数据 - if indicators: - for indicator_name in indicators: - print(f"[ChartController] 加载指标: {indicator_name}") - df_indicator = self.data_adapter.load_indicator( - symbol, period, indicator_name, start_date, end_date - ) - - if df_indicator is not None and not df_indicator.empty: - self.indicator_loaded.emit(indicator_name, df_indicator) - print(f"[ChartController] 指标 {indicator_name} 加载成功") - - self.loading_finished.emit(True, "数据加载完成") - - except Exception as e: - print(f"[ChartController] 加载数据失败: {e}") - import traceback - - traceback.print_exc() - self.loading_finished.emit(False, f"加载失败: {e}") - - def refresh_chart(self): - """刷新图表""" - print("[ChartController] 刷新图表") - # 重新加载当前图表数据 - indicators = ["macd", "kdj", "rsi", "boll"] - self.load_chart_data(self.current_symbol, self.current_period, indicators) diff --git a/src/gui/controllers/main_controller.py b/src/gui/controllers/main_controller.py deleted file mode 100644 index 82b9c54..0000000 --- a/src/gui/controllers/main_controller.py +++ /dev/null @@ -1,65 +0,0 @@ -""" -主控制器 -负责应用级事件处理和状态管理 -""" - -from PyQt6.QtCore import QObject, pyqtSignal - - -class MainController(QObject): - """ - 主控制器 - Controller层核心类 - - 职责: - 1. 协调各个子控制器 - 2. 管理应用状态 - 3. 处理应用级事件 - """ - - # 定义信号 - status_message = pyqtSignal(str) # 状态消息信号 - - def __init__(self, data_adapter=None): - """ - 初始化主控制器 - - Args: - data_adapter: DataAdapter实例 - """ - super().__init__() - self.data_adapter = data_adapter - - # 应用状态 - self.current_symbol = None - self.current_period = None - - def set_symbol(self, symbol: str): - """ - 设置当前标的 - - Args: - symbol: 标的代码 - """ - self.current_symbol = symbol - self.status_message.emit(f"当前标的: {symbol}") - print(f"[MainController] 设置标的: {symbol}") - - def set_period(self, period: str): - """ - 设置当前周期 - - Args: - period: 周期代码 - """ - self.current_period = period - self.status_message.emit(f"当前周期: {period}") - print(f"[MainController] 设置周期: {period}") - - def get_current_state(self) -> dict: - """ - 获取当前应用状态 - - Returns: - 包含当前状态的字典 - """ - return {"symbol": self.current_symbol, "period": self.current_period} diff --git a/src/gui/models/__init__.py b/src/gui/models/__init__.py deleted file mode 100644 index b59daf8..0000000 --- a/src/gui/models/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -Models - 视图模型 -负责UI状态和配置 -""" diff --git a/src/gui/presentation/__init__.py b/src/gui/presentation/__init__.py deleted file mode 100644 index 59c596a..0000000 --- a/src/gui/presentation/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -""" -Presentation Layer - 显示层 -负责UI组件和界面展示 -""" diff --git a/src/gui/presentation/charts/__init__.py b/src/gui/presentation/charts/__init__.py deleted file mode 100644 index 11a16e8..0000000 --- a/src/gui/presentation/charts/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""图表组件模块""" diff --git a/src/gui/presentation/charts/indicator_canvas.py b/src/gui/presentation/charts/indicator_canvas.py deleted file mode 100644 index 8757ddb..0000000 --- a/src/gui/presentation/charts/indicator_canvas.py +++ /dev/null @@ -1,223 +0,0 @@ -""" -指标画布 - 绘制技术指标图表 -""" - -import pandas as pd -from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg -from matplotlib.figure import Figure -import matplotlib.pyplot as plt - -# 设置中文字体 -plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "Arial Unicode MS"] -plt.rcParams["axes.unicode_minus"] = False - - -class IndicatorCanvas(FigureCanvasQTAgg): - """技术指标图表画布""" - - def __init__(self, parent=None, width=8, height=3, dpi=100): - self.fig = Figure(figsize=(width, height), dpi=dpi) - super().__init__(self.fig) - self.setParent(parent) - - # 背景颜色 - self.fig.patch.set_facecolor("white") - - self.current_indicator = None - self.current_df = None - - def plot_macd(self, df: pd.DataFrame): - """ - 绘制MACD指标 - - 参数: - df: MACD数据,包含列: dif, dea, macd - """ - if df is None or df.empty: - return - - self.current_indicator = "macd" - self.current_df = df - print(f"[IndicatorCanvas] 绘制MACD,数据量: {len(df)} 条") - - self.fig.clear() - ax = self.fig.add_subplot(111) - - # 绘制DIF和DEA线 - ax.plot(df.index, df["macd_dif"], label="DIF", color="blue", linewidth=1.5) - ax.plot(df.index, df["macd_dea"], label="DEA", color="orange", linewidth=1.5) - - # 绘制MACD柱状图 - colors = ["red" if x > 0 else "green" for x in df["macd_histogram"]] - ax.bar( - df.index, - df["macd_histogram"], - label="MACD", - color=colors, - alpha=0.5, - width=0.8, - ) - - # 添加零轴线 - ax.axhline(y=0, color="gray", linestyle="--", linewidth=0.8, alpha=0.5) - - # 设置标签和标题 - ax.set_title("MACD指标", fontsize=12, pad=10) - ax.set_ylabel("值", fontsize=10) - ax.legend(loc="upper left", fontsize=9) - ax.grid(True, alpha=0.3) - - # 旋转x轴标签 - self.fig.autofmt_xdate() - - self.fig.tight_layout() - self.draw() - - def plot_kdj(self, df: pd.DataFrame): - """ - 绘制KDJ指标 - - 参数: - df: KDJ数据,包含列: k, d, j - """ - if df is None or df.empty: - return - - self.current_indicator = "kdj" - self.current_df = df - - self.fig.clear() - ax = self.fig.add_subplot(111) - - # 绘制K、D、J线 - ax.plot(df.index, df["kdj_k"], label="K", color="blue", linewidth=1.5) - ax.plot(df.index, df["kdj_d"], label="D", color="orange", linewidth=1.5) - ax.plot(df.index, df["kdj_j"], label="J", color="purple", linewidth=1.5) - - # 添加超买超卖线 - ax.axhline( - y=80, - color="red", - linestyle="--", - linewidth=0.8, - alpha=0.5, - label="超买(80)", - ) - ax.axhline( - y=20, - color="green", - linestyle="--", - linewidth=0.8, - alpha=0.5, - label="超卖(20)", - ) - - # 设置标签和标题 - ax.set_title("KDJ指标", fontsize=12, pad=10) - ax.set_ylabel("值", fontsize=10) - ax.set_ylim(-10, 110) - ax.legend(loc="upper left", fontsize=9) - ax.grid(True, alpha=0.3) - - self.fig.autofmt_xdate() - self.fig.tight_layout() - self.draw() - - def plot_rsi(self, df: pd.DataFrame): - """ - 绘制RSI指标 - - 参数: - df: RSI数据,包含列: rsi_6, rsi_12, rsi_24 - """ - if df is None or df.empty: - return - - self.current_indicator = "rsi" - self.current_df = df - - self.fig.clear() - ax = self.fig.add_subplot(111) - - # 绘制不同周期的RSI线 - ax.plot(df.index, df["rsi_fast"], label="RSI(6)", color="blue", linewidth=1.5) - ax.plot(df.index, df["rsi_mid"], label="RSI(12)", color="orange", linewidth=1.5) - ax.plot(df.index, df["rsi_slow"], label="RSI(24)", color="green", linewidth=1.5) - - # 添加超买超卖线 - ax.axhline( - y=70, - color="red", - linestyle="--", - linewidth=0.8, - alpha=0.5, - label="超买(70)", - ) - ax.axhline( - y=30, - color="green", - linestyle="--", - linewidth=0.8, - alpha=0.5, - label="超卖(30)", - ) - ax.axhline( - y=50, - color="gray", - linestyle="-", - linewidth=0.8, - alpha=0.3, - label="中线(50)", - ) - - # 设置标签和标题 - ax.set_title("RSI指标", fontsize=12, pad=10) - ax.set_ylabel("值", fontsize=10) - ax.set_ylim(0, 100) - ax.legend(loc="upper left", fontsize=9) - ax.grid(True, alpha=0.3) - - self.fig.autofmt_xdate() - self.fig.tight_layout() - self.draw() - - def plot_boll(self, df: pd.DataFrame): - """ - 绘制BOLL指标 - - 参数: - df: BOLL数据,包含列: upper, mid, lower - """ - if df is None or df.empty: - return - - self.current_indicator = "boll" - self.current_df = df - - self.fig.clear() - ax = self.fig.add_subplot(111) - - # 绘制布林带 - ax.plot(df.index, df["boll_upper"], label="上轨", color="red", linewidth=1.5) - ax.plot(df.index, df["boll_mid"], label="中轨", color="blue", linewidth=1.5) - ax.plot(df.index, df["boll_lower"], label="下轨", color="green", linewidth=1.5) - - # 填充上下轨之间的区域 - ax.fill_between( - df.index, df["boll_upper"], df["boll_lower"], alpha=0.1, color="gray" - ) - - # 设置标签和标题 - ax.set_title("BOLL布林带指标", fontsize=12, pad=10) - ax.set_ylabel("价格", fontsize=10) - ax.legend(loc="upper left", fontsize=9) - ax.grid(True, alpha=0.3) - - self.fig.autofmt_xdate() - self.fig.tight_layout() - self.draw() - - def clear_plot(self): - """清除图表""" - self.fig.clear() - self.draw() diff --git a/src/gui/presentation/charts/kline_canvas.py b/src/gui/presentation/charts/kline_canvas.py deleted file mode 100644 index bb5ef40..0000000 --- a/src/gui/presentation/charts/kline_canvas.py +++ /dev/null @@ -1,126 +0,0 @@ -""" -K线画布 - 使用mplfinance绘制K线图 -""" - -import pandas as pd -import mplfinance as mpf -from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg -from matplotlib.figure import Figure -import matplotlib.pyplot as plt - -# 设置中文字体 -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, width=8, height=6, dpi=100): - self.fig = Figure(figsize=(width, height), dpi=dpi) - super().__init__(self.fig) - self.setParent(parent) - - # 当前数据 - self.current_df = None - self.ma_periods = [5, 10, 20, 60] - - # 样式配置 - self.style = "charles" # 可选: 'charles', 'classic', 'yahoo' - self.colors = mpf.make_marketcolors( - up="red", # 上涨K线颜色 - down="green", # 下跌K线颜色 - edge="inherit", - wick="inherit", - volume="in", - alpha=0.9, - ) - self.mpf_style = mpf.make_mpf_style( - marketcolors=self.colors, - gridstyle="-", - gridcolor="#E0E0E0", - facecolor="white", - figcolor="white", - ) - - def plot_kline(self, df: pd.DataFrame, ma_periods=None): - """ - 绘制K线图 - - 参数: - df: K线数据 DataFrame - 必须包含列: open, high, low, close, volume - index必须是DatetimeIndex - ma_periods: MA周期列表,如 [5, 10, 20, 60] - """ - if df is None or df.empty: - return - - self.current_df = df.copy() - - if ma_periods is not None: - self.ma_periods = ma_periods - - # 清除之前的图表 - self.fig.clear() - - # 准备数据 - 确保列名正确 - plot_df = self.current_df.copy() - - # mplfinance要求的列名必须是小写 - required_cols = ["open", "high", "low", "close", "volume"] - for col in required_cols: - if col not in plot_df.columns and col.capitalize() in plot_df.columns: - plot_df[col] = plot_df[col.capitalize()] - - # 添加均线 - mav = tuple(self.ma_periods) if self.ma_periods else None - - # 绘制K线图 - try: - print(f"[KlineCanvas] 开始绘制K线,数据量: {len(plot_df)} 条") - # 创建两个子图 - K线和成交量分开 - ax1 = self.fig.add_subplot(211) # K线图 - ax2 = self.fig.add_subplot(212) # 成交量 - - mpf.plot( - plot_df, - type="candle", - style=self.mpf_style, - mav=mav, - volume=ax2, # 将成交量绘制在第二个子图 - ax=ax1, # K线绘制在第一个子图 - ylabel="Price", - ylabel_lower="Volume", - datetime_format="%H:%M", - xrotation=15, - ) - print(f"[KlineCanvas] K线绘制成功") - except Exception as e: - print(f"[KlineCanvas] 绘制K线图失败: {e}") - import traceback - - traceback.print_exc() - # 如果mplfinance失败,使用基础matplotlib绘制 - ax = self.fig.add_subplot(111) - ax.text( - 0.5, - 0.5, - f"绘制失败: {str(e)}", - ha="center", - va="center", - transform=ax.transAxes, - ) - - self.draw() - - def update_ma_periods(self, periods): - """更新均线周期并重绘""" - self.ma_periods = periods - if self.current_df is not None: - self.plot_kline(self.current_df) - - def clear_plot(self): - """清除图表""" - self.fig.clear() - self.draw() diff --git a/src/gui/presentation/main_window.py b/src/gui/presentation/main_window.py deleted file mode 100644 index d9ddfc8..0000000 --- a/src/gui/presentation/main_window.py +++ /dev/null @@ -1,192 +0,0 @@ -""" -QTrade主窗口 -""" - -from PyQt6.QtWidgets import ( - QMainWindow, - QWidget, - QVBoxLayout, - QSplitter, - QStatusBar, - QMessageBox, - QLabel, -) -from PyQt6.QtCore import Qt -from PyQt6.QtGui import QAction - -from .widgets.kline_widget import KlineWidget -from .widgets.indicator_panel import IndicatorPanel - - -class MainWindow(QMainWindow): - """应用主窗口""" - - def __init__(self, chart_controller): - super().__init__() - self.chart_controller = chart_controller - self.init_ui() - self.connect_signals() - - def init_ui(self): - """初始化UI""" - self.setWindowTitle("QTrade - K线图表分析工具 MVP [运行中...]") - self.setGeometry(100, 100, 1400, 900) - print("[MainWindow] 窗口初始化: 1400x900") - - # 创建中心部件 - central_widget = QWidget() - self.setCentralWidget(central_widget) - - # 主布局 - main_layout = QVBoxLayout(central_widget) - main_layout.setContentsMargins(10, 10, 10, 10) - - # 创建分割器 - 上下分割 - splitter = QSplitter(Qt.Orientation.Vertical) - - # K线图控件 - self.kline_widget = KlineWidget() - splitter.addWidget(self.kline_widget) - - # 指标面板 - self.indicator_panel = IndicatorPanel() - splitter.addWidget(self.indicator_panel) - - # 设置分割比例 (K线:指标 = 2:1) - splitter.setStretchFactor(0, 2) - splitter.setStretchFactor(1, 1) - - main_layout.addWidget(splitter) - - # 创建菜单栏 - self.create_menu_bar() - - # 创建状态栏 - self.status_bar = QStatusBar() - self.setStatusBar(self.status_bar) - self.status_bar.showMessage("就绪") - - def create_menu_bar(self): - """创建菜单栏""" - menubar = self.menuBar() - - # 文件菜单 - file_menu = menubar.addMenu("文件") - - exit_action = QAction("退出", self) - exit_action.setShortcut("Ctrl+Q") - exit_action.triggered.connect(self.close) - file_menu.addAction(exit_action) - - # 帮助菜单 - help_menu = menubar.addMenu("帮助") - - about_action = QAction("关于", self) - about_action.triggered.connect(self.show_about) - help_menu.addAction(about_action) - - def connect_signals(self): - """连接信号和槽""" - # K线图控件信号 - self.kline_widget.symbol_changed.connect(self.on_symbol_changed) - self.kline_widget.period_changed.connect(self.on_period_changed) - self.kline_widget.refresh_clicked.connect(self.on_refresh_clicked) - - # 指标面板信号 - self.indicator_panel.indicator_changed.connect(self.on_indicator_changed) - - # 图表控制器信号 - self.chart_controller.kline_loaded.connect(self.on_kline_loaded) - self.chart_controller.indicator_loaded.connect(self.on_indicator_loaded) - self.chart_controller.loading_started.connect(self.on_loading_started) - self.chart_controller.loading_finished.connect(self.on_loading_finished) - - def on_symbol_changed(self, symbol): - """标的切换""" - print(f"[MainWindow] 标的切换: {symbol}") - self.load_data() - - def on_period_changed(self, period): - """周期切换""" - print(f"[MainWindow] 周期切换: {period}") - self.load_data() - - def on_refresh_clicked(self): - """刷新按钮点击""" - print("[MainWindow] 刷新按钮点击") - self.load_data() - - def on_indicator_changed(self, indicator_name): - """指标切换""" - print(f"[MainWindow] 指标切换: {indicator_name}") - # 指标数据已加载,无需重新请求 - - def load_data(self): - """加载数据""" - symbol = self.kline_widget.get_current_symbol() - period = self.kline_widget.get_current_period() - indicators = ["macd", "kdj", "rsi", "boll"] - - print(f"[MainWindow] 加载数据: {symbol} {period}") - self.chart_controller.load_chart_data(symbol, period, indicators) - - def on_kline_loaded(self, df): - """K线数据加载完成""" - print(f"[MainWindow] 收到K线数据: {len(df)} 条") - self.kline_widget.plot_kline(df, ma_periods=[5, 10, 20, 60]) - - def on_indicator_loaded(self, indicator_name, df): - """指标数据加载完成""" - print(f"[MainWindow] 收到指标数据: {indicator_name}") - - if indicator_name == "macd": - self.indicator_panel.plot_macd(df) - elif indicator_name == "kdj": - self.indicator_panel.plot_kdj(df) - elif indicator_name == "rsi": - self.indicator_panel.plot_rsi(df) - elif indicator_name == "boll": - self.indicator_panel.plot_boll(df) - - def on_loading_started(self, message): - """加载开始""" - self.status_bar.showMessage(message) - - def on_loading_finished(self, success, message): - """加载完成""" - if success: - self.status_bar.showMessage(message, 3000) - else: - self.status_bar.showMessage(f"错误: {message}", 5000) - QMessageBox.warning(self, "加载失败", message) - - def show_about(self): - """显示关于对话框""" - QMessageBox.about( - self, - "关于 QTrade", - "QTrade K线图表分析工具 MVP\n\n" - "技术栈: PyQt6 + matplotlib + mplfinance\n" - "架构: 三层架构 (Presentation/Controller/Adapter)", - ) - - def showEvent(self, event): - """窗口显示事件""" - super().showEvent(event) - # 首次显示时加载默认数据 - if not hasattr(self, "_data_loaded"): - self._data_loaded = True - print("[MainWindow] 首次显示,加载默认数据") - self.load_data() - - """显示关于信息""" - from PyQt6.QtWidgets import QMessageBox - - QMessageBox.about( - self, - "关于QTrade", - "QTrade K线图表分析工具\n\n" - "版本: 0.1.0\n" - "技术栈: PyQt6 + matplotlib\n" - "架构: 三层架构 (Presentation/Controller/Adapter)", - ) diff --git a/src/gui/presentation/widgets/__init__.py b/src/gui/presentation/widgets/__init__.py deleted file mode 100644 index b55f5d4..0000000 --- a/src/gui/presentation/widgets/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""自定义控件模块""" diff --git a/src/gui/presentation/widgets/indicator_panel.py b/src/gui/presentation/widgets/indicator_panel.py deleted file mode 100644 index cd19c16..0000000 --- a/src/gui/presentation/widgets/indicator_panel.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -指标面板 - 技术指标图表展示 -""" - -from PyQt6.QtWidgets import QWidget, QVBoxLayout, QTabWidget -from PyQt6.QtCore import pyqtSignal -from ..charts.indicator_canvas import IndicatorCanvas - - -class IndicatorPanel(QWidget): - """技术指标面板""" - - # 信号定义 - indicator_changed = pyqtSignal(str) # 指标切换 - - def __init__(self, parent=None): - super().__init__(parent) - self.init_ui() - - def init_ui(self): - """初始化UI""" - layout = QVBoxLayout(self) - - # 创建标签页 - self.tab_widget = QTabWidget() - self.tab_widget.currentChanged.connect(self._on_tab_changed) - - # 创建各个指标的画布 - self.macd_canvas = IndicatorCanvas(self, width=10, height=3) - self.kdj_canvas = IndicatorCanvas(self, width=10, height=3) - self.rsi_canvas = IndicatorCanvas(self, width=10, height=3) - self.boll_canvas = IndicatorCanvas(self, width=10, height=3) - - # 添加到标签页 - self.tab_widget.addTab(self.macd_canvas, "MACD") - self.tab_widget.addTab(self.kdj_canvas, "KDJ") - self.tab_widget.addTab(self.rsi_canvas, "RSI") - self.tab_widget.addTab(self.boll_canvas, "BOLL") - - layout.addWidget(self.tab_widget) - layout.setContentsMargins(5, 5, 5, 5) - - def _on_tab_changed(self, index): - """标签页切换事件""" - indicator_names = ["macd", "kdj", "rsi", "boll"] - if 0 <= index < len(indicator_names): - self.indicator_changed.emit(indicator_names[index]) - - def plot_macd(self, df): - """绘制MACD""" - self.macd_canvas.plot_macd(df) - - def plot_kdj(self, df): - """绘制KDJ""" - self.kdj_canvas.plot_kdj(df) - - def plot_rsi(self, df): - """绘制RSI""" - self.rsi_canvas.plot_rsi(df) - - def plot_boll(self, df): - """绘制BOLL""" - self.boll_canvas.plot_boll(df) - - def get_current_indicator(self): - """获取当前选中的指标""" - indicator_names = ["macd", "kdj", "rsi", "boll"] - index = self.tab_widget.currentIndex() - return indicator_names[index] if 0 <= index < len(indicator_names) else "macd" diff --git a/src/gui/presentation/widgets/kline_widget.py b/src/gui/presentation/widgets/kline_widget.py deleted file mode 100644 index 310aa0a..0000000 --- a/src/gui/presentation/widgets/kline_widget.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -K线图控件 - K线图展示容器 -""" - -from PyQt6.QtWidgets import ( - QWidget, - QVBoxLayout, - QHBoxLayout, - QLabel, - QComboBox, - QPushButton, - QGroupBox, -) -from PyQt6.QtCore import pyqtSignal -from ..charts.kline_canvas import KlineCanvas - - -class KlineWidget(QWidget): - """K线图控件""" - - # 信号定义 - symbol_changed = pyqtSignal(str) # 标的切换 - period_changed = pyqtSignal(str) # 周期切换 - refresh_clicked = pyqtSignal() # 刷新按钮 - - def __init__(self, parent=None): - super().__init__(parent) - self.init_ui() - - def init_ui(self): - """初始化UI""" - layout = QVBoxLayout(self) - - # 工具栏 - toolbar = self._create_toolbar() - layout.addWidget(toolbar) - - # K线画布 - self.canvas = KlineCanvas(self, width=10, height=6) - layout.addWidget(self.canvas) - - layout.setContentsMargins(5, 5, 5, 5) - layout.setSpacing(5) - - def _create_toolbar(self): - """创建工具栏""" - toolbar = QGroupBox("K线图控制") - layout = QHBoxLayout() - - # 标的选择 - layout.addWidget(QLabel("标的:")) - self.symbol_combo = QComboBox() - # 使用数据库中已有的股票 - self.symbol_combo.addItems(["601658.SH", "159915.SZ", "600000.SH", "000001.SZ"]) - self.symbol_combo.currentTextChanged.connect(self.symbol_changed.emit) - layout.addWidget(self.symbol_combo) - - # 周期选择 - layout.addWidget(QLabel("周期:")) - self.period_combo = QComboBox() - self.period_combo.addItems(["1m", "5m", "15m", "30m", "60m", "1d", "1w"]) - self.period_combo.currentTextChanged.connect(self.period_changed.emit) - layout.addWidget(self.period_combo) - - # 刷新按钮 - self.refresh_btn = QPushButton("刷新") - self.refresh_btn.clicked.connect(self.refresh_clicked.emit) - layout.addWidget(self.refresh_btn) - - layout.addStretch() - toolbar.setLayout(layout) - return toolbar - - def plot_kline(self, df, ma_periods=None): - """绘制K线图""" - self.canvas.plot_kline(df, ma_periods) - - def get_current_symbol(self): - """获取当前选中的标的""" - return self.symbol_combo.currentText() - - def get_current_period(self): - """获取当前选中的周期""" - return self.period_combo.currentText()