实现GUI多子图K线图表 - 专业黑色主题
主要改进: 1. K线图改造为4个子图布局(K线+成交量+MACD+RSI) 2. 应用专业黑色主题(#0a0a0a背景) 3. 配色调整为青色上涨(#00ffff)、红色下跌(#ff0000) 4. 增加MA5/10/20/30/60五条均线 5. 实现MACD和RSI指标绘制 6. 修复数据存储的主键冲突和SQL过长问题 7. 完善DownloaderManager参数处理 技术细节: - 使用matplotlib gridspec控制子图高度比例(6:2:1.5:1.5) - EMA计算MACD指标(12/26/9) - RSI多周期显示(6/12/24) - 数据分批保存(100条/批) - 保存前删除冲突记录避免主键错误 文件变更: - simple_kline_viewer.py: 4子图布局+黑色主题+指标计算 - mysql_storage.py: 分批保存+冲突处理+时间范围检查 - downloader_manager.py: 修复Config兼容性 - requirements.txt: 新增项目依赖清单 - docs/tech_designs/gui_design.md: 更新技术设计文档 - src/gui/*: GUI三层架构实现(Presentation/Controller/Adapter) 测试状态: - 601658.SH 1d数据473条成功显示 - 4个子图正常渲染 - 黑色主题和专业配色生效 - MACD/RSI指标计算正确 - 数据下载和存储流程完整
This commit is contained in:
parent
232a06d460
commit
ab31734097
2
.gitignore
vendored
2
.gitignore
vendored
@ -6,7 +6,7 @@ __pycache__/
|
|||||||
|
|
||||||
# 项目缓存和学习资料
|
# 项目缓存和学习资料
|
||||||
caches/
|
caches/
|
||||||
learning_materials/
|
learning_materials/*
|
||||||
|
|
||||||
# XtQuant 数据目录
|
# XtQuant 数据目录
|
||||||
data/datadir/
|
data/datadir/
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
36
requirements.txt
Normal file
36
requirements.txt
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
# QTrade 项目依赖库
|
||||||
|
# 安装命令: pip install -r requirements.txt
|
||||||
|
# 或在conda环境中: conda run -n py311 pip install -r requirements.txt
|
||||||
|
|
||||||
|
# ==================== GUI框架 ====================
|
||||||
|
PyQt6>=6.10.0
|
||||||
|
|
||||||
|
# ==================== 数据处理 ====================
|
||||||
|
pandas>=2.0.0
|
||||||
|
numpy>=1.24.0
|
||||||
|
|
||||||
|
# ==================== 图表绘制 ====================
|
||||||
|
matplotlib>=3.7.0
|
||||||
|
mplfinance>=0.12.0
|
||||||
|
|
||||||
|
# ==================== 技术指标计算 ====================
|
||||||
|
# TA-Lib推荐使用conda安装: conda install -c conda-forge ta-lib
|
||||||
|
# Windows系统pip安装需要预编译whl: https://github.com/cgohlke/talib-build/releases
|
||||||
|
TA-Lib>=0.4.28
|
||||||
|
|
||||||
|
# ==================== 数据库 ====================
|
||||||
|
pymysql>=1.1.0
|
||||||
|
sqlalchemy>=2.0.0
|
||||||
|
|
||||||
|
# ==================== 数据验证 ====================
|
||||||
|
pydantic>=2.0.0
|
||||||
|
|
||||||
|
# ==================== 配置文件 ====================
|
||||||
|
pyyaml>=6.0
|
||||||
|
|
||||||
|
# ==================== 工具库 ====================
|
||||||
|
python-dateutil>=2.8.0
|
||||||
|
pytz>=2023.0
|
||||||
|
|
||||||
|
# ==================== 数据源(可选) ====================
|
||||||
|
xtquant # 迅投QMT数据源
|
||||||
774
simple_kline_viewer.py
Normal file
774
simple_kline_viewer.py
Normal file
@ -0,0 +1,774 @@
|
|||||||
|
"""
|
||||||
|
简单K线查看器
|
||||||
|
使用DataService直接显示K线数据
|
||||||
|
支持键盘导航和缩放
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
import io
|
||||||
|
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
|
||||||
|
|
||||||
|
# 设置控制台编码为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)
|
||||||
|
|
||||||
|
def keyPressEvent(self, event):
|
||||||
|
"""处理键盘事件"""
|
||||||
|
print(
|
||||||
|
f"[键盘] 按下: {event.key()}, 数据量: {len(self.full_data) if self.full_data is not None else 0}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.full_data is None or len(self.full_data) == 0:
|
||||||
|
print("[键盘] 无数据,忽略")
|
||||||
|
return
|
||||||
|
|
||||||
|
step = max(1, self.display_count // 10) # 每次移动10%
|
||||||
|
total_len = len(self.full_data)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"[键盘] 当前: start={self.current_start}, end={self.current_end}, display={self.display_count}, total={total_len}"
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
print(f"[键盘] 左移到: {self.current_start}-{self.current_end}")
|
||||||
|
self.update_display()
|
||||||
|
else:
|
||||||
|
print("[键盘] 已在最开始")
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
print(f"[键盘] 右移到: {self.current_start}-{self.current_end}")
|
||||||
|
self.update_display()
|
||||||
|
else:
|
||||||
|
print("[键盘] 已在最末尾")
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
print(f"[键盘] 放大到: {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
|
||||||
|
)
|
||||||
|
print(f"[键盘] 缩小到: {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)
|
||||||
|
print("[键盘] 跳转到开始")
|
||||||
|
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
|
||||||
|
print("[键盘] 跳转到末尾")
|
||||||
|
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
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"[Canvas] 加载数据: 总量={total_len}, 显示={self.display_count}, 范围={self.current_start}-{self.current_end}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 显示
|
||||||
|
self.update_display()
|
||||||
|
|
||||||
|
# 自动获取键盘焦点
|
||||||
|
self.setFocus()
|
||||||
|
|
||||||
|
def _plot_data(self, df, title="K线图"):
|
||||||
|
"""实际绘制K线图(专业交易风格)"""
|
||||||
|
if df is None or df.empty:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 清空旧图
|
||||||
|
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控制高度比例: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")
|
||||||
|
|
||||||
|
# 绘制K线和更多均线(5/10/20/30/60)
|
||||||
|
mpf.plot(
|
||||||
|
plot_df,
|
||||||
|
type="candle",
|
||||||
|
style=self.style,
|
||||||
|
mav=(5, 10, 20, 30, 60),
|
||||||
|
volume=ax2,
|
||||||
|
ax=ax1,
|
||||||
|
warn_too_much_data=10000,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 计算并绘制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:
|
||||||
|
# 计算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
|
||||||
|
|
||||||
|
# 绘制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:
|
||||||
|
# 计算RSI(6,12,24)
|
||||||
|
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))
|
||||||
|
|
||||||
|
colors = {6: "#ffff00", 12: "#00ffff", 24: "#ff00ff"}
|
||||||
|
ax.plot(
|
||||||
|
rsi.values, color=colors[period], linewidth=1, label=f"RSI{period}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 绘制参考线
|
||||||
|
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(
|
||||||
|
f"下载参数: symbols={self.symbols}, periods={self.periods}, {self.start_date} ~ {self.end_date}"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.data_service.download_klines(
|
||||||
|
symbols=self.symbols,
|
||||||
|
start_date=self.start_date,
|
||||||
|
end_date=self.end_date,
|
||||||
|
periods=self.periods,
|
||||||
|
)
|
||||||
|
|
||||||
|
success_msg = (
|
||||||
|
f"下载完成: {len(self.symbols)}个标的, {len(self.periods)}个周期"
|
||||||
|
)
|
||||||
|
print(success_msg)
|
||||||
|
self.finished.emit(True, success_msg)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
error_msg = f"下载失败: {str(e)}"
|
||||||
|
print(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"])
|
||||||
|
control_layout.addWidget(self.symbol_combo)
|
||||||
|
|
||||||
|
# 周期选择
|
||||||
|
control_layout.addWidget(QLabel("周期:"))
|
||||||
|
self.period_combo = QComboBox()
|
||||||
|
self.period_combo.addItems(["1m", "5m", "15m", "30m", "60m", "1d"])
|
||||||
|
self.period_combo.setCurrentText("1d") # 默认日线
|
||||||
|
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):
|
||||||
|
"""周期切换时自动调整日期范围"""
|
||||||
|
if period == "1d":
|
||||||
|
# 日线:默认一年
|
||||||
|
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()
|
||||||
@ -130,14 +130,21 @@ class DownloaderManager:
|
|||||||
# 创建下载器
|
# 创建下载器
|
||||||
try:
|
try:
|
||||||
downloader_class = DownloaderFactory.create(self.downloader_type)
|
downloader_class = DownloaderFactory.create(self.downloader_type)
|
||||||
|
|
||||||
|
# 获取数据库名称(兼容Config对象和dict)
|
||||||
|
if isinstance(self.config, Config):
|
||||||
|
database = self.config.get("database.database", "qtrade_backtest")
|
||||||
|
else:
|
||||||
|
database = self.config.get("database", {}).get(
|
||||||
|
"database", "qtrade_backtest"
|
||||||
|
)
|
||||||
|
|
||||||
downloader = downloader_class(
|
downloader = downloader_class(
|
||||||
symbols=symbols_to_download,
|
symbols=symbols_to_download,
|
||||||
start_date=start_date,
|
start_date=start_date,
|
||||||
end_date=end_date,
|
end_date=end_date,
|
||||||
periods=[period],
|
periods=[period],
|
||||||
database=self.config.get("database", {}).get(
|
database=database,
|
||||||
"database", "qtrade_backtest"
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# 执行下载
|
# 执行下载
|
||||||
|
|||||||
@ -206,22 +206,56 @@ class MySQLStorage(StorageLayer):
|
|||||||
|
|
||||||
df_to_save = df[columns].copy()
|
df_to_save = df[columns].copy()
|
||||||
|
|
||||||
# 保存到数据库
|
# 删除时间范围内的旧数据,避免主键冲突
|
||||||
engine = self.db_manager._create_db_engine(self.database)
|
engine = self.db_manager._create_db_engine(self.database)
|
||||||
|
batch_size = 100 # 每批100条
|
||||||
|
total_saved = 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
# 获取要插入的时间范围
|
||||||
|
min_time = df_to_save["timestamp"].min()
|
||||||
|
max_time = df_to_save["timestamp"].max()
|
||||||
|
|
||||||
|
# 删除该时间范围内的旧数据
|
||||||
with engine.begin() as conn:
|
with engine.begin() as conn:
|
||||||
df_to_save.to_sql(
|
delete_sql = text(
|
||||||
table_name,
|
f"""
|
||||||
conn,
|
DELETE FROM {table_name}
|
||||||
if_exists="append",
|
WHERE symbol = :symbol
|
||||||
index=False,
|
AND timestamp >= :min_time
|
||||||
method="multi",
|
AND timestamp <= :max_time
|
||||||
|
"""
|
||||||
)
|
)
|
||||||
|
result = conn.execute(
|
||||||
|
delete_sql,
|
||||||
|
{"symbol": symbol, "min_time": min_time, "max_time": max_time},
|
||||||
|
)
|
||||||
|
deleted_count = result.rowcount
|
||||||
|
if deleted_count > 0:
|
||||||
|
logger.info(
|
||||||
|
f"Deleted {deleted_count} old records for {symbol}_{period} in range {min_time} ~ {max_time}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 分批保存新数据
|
||||||
|
with engine.begin() as conn:
|
||||||
|
for i in range(0, len(df_to_save), batch_size):
|
||||||
|
batch = df_to_save.iloc[i : i + batch_size]
|
||||||
|
batch.to_sql(
|
||||||
|
table_name,
|
||||||
|
conn,
|
||||||
|
if_exists="append",
|
||||||
|
index=False,
|
||||||
|
)
|
||||||
|
total_saved += len(batch)
|
||||||
|
if len(df_to_save) > batch_size:
|
||||||
|
logger.debug(
|
||||||
|
f"Saved batch {i // batch_size + 1}: {len(batch)} records"
|
||||||
|
)
|
||||||
finally:
|
finally:
|
||||||
engine.dispose()
|
engine.dispose()
|
||||||
|
|
||||||
logger.info(f"Saved {len(df_to_save)} klines: {symbol}_{period}")
|
logger.info(f"Saved {total_saved} klines: {symbol}_{period}")
|
||||||
return len(df_to_save)
|
return total_saved
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to save klines {symbol}_{period}: {e}")
|
logger.error(f"Failed to save klines {symbol}_{period}: {e}")
|
||||||
@ -274,7 +308,7 @@ class MySQLStorage(StorageLayer):
|
|||||||
method="multi",
|
method="multi",
|
||||||
)
|
)
|
||||||
print(f"[DEBUG] to_sql返回值: {result}")
|
print(f"[DEBUG] to_sql返回值: {result}")
|
||||||
print(f"[DEBUG] 事务已提交")
|
print("[DEBUG] 事务已提交")
|
||||||
finally:
|
finally:
|
||||||
engine.dispose()
|
engine.dispose()
|
||||||
|
|
||||||
@ -298,16 +332,36 @@ class MySQLStorage(StorageLayer):
|
|||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
检查K线数据是否存在且完整
|
检查K线数据是否存在且完整
|
||||||
|
|
||||||
|
检查逻辑:
|
||||||
|
1. 查询数据库中该标的在指定时间范围内的实际数据范围
|
||||||
|
2. 如果数据库的时间范围完全覆盖请求的时间范围,则认为数据存在
|
||||||
|
3. 否则认为数据不存在或不完整,需要下载
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
df = self.load_klines(symbol, period, start_date, end_date)
|
# 获取数据库中实际的数据时间范围
|
||||||
|
date_range = self.get_date_range(symbol, period)
|
||||||
|
|
||||||
if df is None or df.empty:
|
if date_range is None:
|
||||||
|
# 数据库中没有任何数据
|
||||||
|
logger.debug(f"No data in DB for {symbol}_{period}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 简单检查:是否有数据
|
db_start, db_end = date_range
|
||||||
# TODO: 可以增强为检查数据完整性(期望的交易日数量)
|
|
||||||
return True
|
# 检查数据库的时间范围是否覆盖请求的时间范围
|
||||||
|
if db_start <= start_date and db_end >= end_date:
|
||||||
|
logger.debug(
|
||||||
|
f"Data exists: {symbol}_{period} DB[{db_start.date()}~{db_end.date()}] "
|
||||||
|
f"covers requested[{start_date.date()}~{end_date.date()}]"
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
logger.debug(
|
||||||
|
f"Data incomplete: {symbol}_{period} DB[{db_start.date()}~{db_end.date()}] "
|
||||||
|
f"does not cover requested[{start_date.date()}~{end_date.date()}]"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to check existence {symbol}_{period}: {e}")
|
logger.error(f"Failed to check existence {symbol}_{period}: {e}")
|
||||||
|
|||||||
6
src/gui/__init__.py
Normal file
6
src/gui/__init__.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
"""
|
||||||
|
QTrade GUI Module
|
||||||
|
使用PyQt6和matplotlib构建的K线图表GUI应用
|
||||||
|
"""
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
4
src/gui/adapters/__init__.py
Normal file
4
src/gui/adapters/__init__.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""
|
||||||
|
Adapter Layer - 适配层
|
||||||
|
负责与DataService对接
|
||||||
|
"""
|
||||||
292
src/gui/adapters/data_adapter.py
Normal file
292
src/gui/adapters/data_adapter.py
Normal file
@ -0,0 +1,292 @@
|
|||||||
|
"""
|
||||||
|
数据适配器基类
|
||||||
|
负责与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
|
||||||
67
src/gui/app.py
Normal file
67
src/gui/app.py
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
"""
|
||||||
|
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()
|
||||||
4
src/gui/controllers/__init__.py
Normal file
4
src/gui/controllers/__init__.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""
|
||||||
|
Controller Layer - 控制层
|
||||||
|
负责事件处理和状态管理
|
||||||
|
"""
|
||||||
101
src/gui/controllers/chart_controller.py
Normal file
101
src/gui/controllers/chart_controller.py
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
"""
|
||||||
|
图表控制器
|
||||||
|
负责图表相关操作和数据加载
|
||||||
|
"""
|
||||||
|
|
||||||
|
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)
|
||||||
65
src/gui/controllers/main_controller.py
Normal file
65
src/gui/controllers/main_controller.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
"""
|
||||||
|
主控制器
|
||||||
|
负责应用级事件处理和状态管理
|
||||||
|
"""
|
||||||
|
|
||||||
|
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}
|
||||||
4
src/gui/models/__init__.py
Normal file
4
src/gui/models/__init__.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""
|
||||||
|
Models - 视图模型
|
||||||
|
负责UI状态和配置
|
||||||
|
"""
|
||||||
4
src/gui/presentation/__init__.py
Normal file
4
src/gui/presentation/__init__.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""
|
||||||
|
Presentation Layer - 显示层
|
||||||
|
负责UI组件和界面展示
|
||||||
|
"""
|
||||||
1
src/gui/presentation/charts/__init__.py
Normal file
1
src/gui/presentation/charts/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
"""图表组件模块"""
|
||||||
223
src/gui/presentation/charts/indicator_canvas.py
Normal file
223
src/gui/presentation/charts/indicator_canvas.py
Normal file
@ -0,0 +1,223 @@
|
|||||||
|
"""
|
||||||
|
指标画布 - 绘制技术指标图表
|
||||||
|
"""
|
||||||
|
|
||||||
|
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()
|
||||||
126
src/gui/presentation/charts/kline_canvas.py
Normal file
126
src/gui/presentation/charts/kline_canvas.py
Normal file
@ -0,0 +1,126 @@
|
|||||||
|
"""
|
||||||
|
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()
|
||||||
192
src/gui/presentation/main_window.py
Normal file
192
src/gui/presentation/main_window.py
Normal file
@ -0,0 +1,192 @@
|
|||||||
|
"""
|
||||||
|
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)",
|
||||||
|
)
|
||||||
1
src/gui/presentation/widgets/__init__.py
Normal file
1
src/gui/presentation/widgets/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
"""自定义控件模块"""
|
||||||
69
src/gui/presentation/widgets/indicator_panel.py
Normal file
69
src/gui/presentation/widgets/indicator_panel.py
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
"""
|
||||||
|
指标面板 - 技术指标图表展示
|
||||||
|
"""
|
||||||
|
|
||||||
|
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"
|
||||||
84
src/gui/presentation/widgets/kline_widget.py
Normal file
84
src/gui/presentation/widgets/kline_widget.py
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
"""
|
||||||
|
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()
|
||||||
Loading…
Reference in New Issue
Block a user