From e2c2d951d2732c5a3989c5c2b932599a4d4eee62 Mon Sep 17 00:00:00 2001 From: Stone Date: Sat, 27 Sep 2025 22:17:36 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=88=86=E6=9E=90=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=EF=BC=8C=E5=A2=9E=E5=8A=A0=E5=9B=BE=E5=BD=A2=E5=8C=96?= =?UTF-8?q?=E5=88=86=E6=9E=90=E7=95=8C=E9=9D=A2=EF=BC=8C=E8=83=BD=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E6=8C=87=E5=AE=9A=E6=97=A5=E6=9C=9F=E7=9A=8415?= =?UTF-8?q?=E5=88=86=E9=92=9F=E6=BB=91=E5=8A=A8=E5=B9=B3=E5=9D=87=E7=BA=BF?= =?UTF-8?q?=EF=BC=8C=E6=9F=A5=E7=9C=8B=E7=9B=B8=E5=BA=94=E7=9A=84=E9=87=91?= =?UTF-8?q?=E5=8F=89/=E6=AD=BB=E5=8F=89=E5=8F=91=E7=94=9F=E6=83=85?= =?UTF-8?q?=E5=86=B5=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/analyzer/__init__.py | 10 + src/analyzer/core/__init__.py | 4 + src/analyzer/core/data_loader.py | 219 +++++++++++++++++ src/analyzer/core/indicators.py | 58 +++++ src/analyzer/main.py | 52 ++++ src/analyzer/ui/__init__.py | 4 + src/analyzer/ui/main_window.py | 158 +++++++++++++ src/analyzer/widgets/__init__.py | 4 + src/analyzer/widgets/kline_chart_widget.py | 223 ++++++++++++++++++ src/data_process_model/database_config.py | 5 +- src/data_process_model/database_manager.py | 7 +- src/data_process_model/main.py | 2 +- src/data_process_model/stock_models.py | 18 +- src/data_process_model/stockdata_manager.py | 22 +- .../technical_indicators.py | 12 +- 15 files changed, 782 insertions(+), 16 deletions(-) create mode 100644 src/analyzer/__init__.py create mode 100644 src/analyzer/core/__init__.py create mode 100644 src/analyzer/core/data_loader.py create mode 100644 src/analyzer/core/indicators.py create mode 100644 src/analyzer/main.py create mode 100644 src/analyzer/ui/__init__.py create mode 100644 src/analyzer/ui/main_window.py create mode 100644 src/analyzer/widgets/__init__.py create mode 100644 src/analyzer/widgets/kline_chart_widget.py diff --git a/src/analyzer/__init__.py b/src/analyzer/__init__.py new file mode 100644 index 0000000..d15fa4a --- /dev/null +++ b/src/analyzer/__init__.py @@ -0,0 +1,10 @@ +# src/analyzer/__init__.py +""" +股票数据分析工具包 + +基于PySide6的K线图形化分析工具,支持多时间周期的移动平均线分析 +和金叉/死叉信号检测。 +""" + +__version__ = "1.0.0" +__author__ = "QTrade Team" \ No newline at end of file diff --git a/src/analyzer/core/__init__.py b/src/analyzer/core/__init__.py new file mode 100644 index 0000000..86dd1b1 --- /dev/null +++ b/src/analyzer/core/__init__.py @@ -0,0 +1,4 @@ +# src/analyzer/core/__init__.py +""" +核心业务逻辑模块 +""" \ No newline at end of file diff --git a/src/analyzer/core/data_loader.py b/src/analyzer/core/data_loader.py new file mode 100644 index 0000000..f147ad3 --- /dev/null +++ b/src/analyzer/core/data_loader.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +""" +数据加载器 + +负责从数据库中加载股票K线数据,参考back_trader模块的实现 +""" + +import pandas as pd +from datetime import datetime, timedelta, time +from typing import Optional, List +import sys +import os + +# 导入数据处理模块 +sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) +from data_process_model.database_manager import DatabaseManager + +# 导入股票模型创建函数 +try: + from data_process_model.stock_models import create_stock_kline_model +except ImportError: + try: + from stock_models import create_stock_kline_model + except ImportError: + create_stock_kline_model = None + +class DataLoader: + """数据加载器类""" + + def __init__(self): + self.db_manager = DatabaseManager() + + def get_available_stocks(self) -> List[str]: + """ + 获取数据库中可用的股票列表 + + Returns: + List[str]: 股票代码列表 + """ + try: + # 直接使用SQL查询获取所有K线表 + query = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'qtrade_stock_data' AND table_name LIKE 'kline_%%_1m'" + + # 使用DatabaseManager的execute_sql方法 + result = self.db_manager.execute_sql(query) + + # 提取股票代码 + stock_codes = [] + if result: + for row in result: + table_name = row[0] if isinstance(row, (list, tuple)) else row + # 从表名提取股票代码 + # 例如: kline_300339_sz_1m -> 300339.SZ + parts = table_name.replace('kline_', '').replace('_1m', '').split('_') + if len(parts) >= 2: + stock_code = parts[0] + '.' + parts[1].upper() + stock_codes.append(stock_code) + + return sorted(list(set(stock_codes))) # 去重并排序 + + except Exception as e: + print(f"获取股票列表失败: {e}") + return [] + + def load_kline_data(self, stock_code: str, date_selected: datetime, timeframe: str) -> Optional[pd.DataFrame]: + """ + 加载指定股票、日期和时间周期的K线数据 + + Args: + stock_code: 股票代码 (如 '300339.SZ') + date_selected: 选择的日期 + timeframe: 时间周期 ('15m', '30m', '60m') + + Returns: + Optional[pd.DataFrame]: K线数据,包含 datetime, open, high, low, close, volume 列 + """ + try: + # 检查是否成功导入了create_stock_kline_model函数 + if create_stock_kline_model is None: + raise ImportError("无法导入create_stock_kline_model函数") + + # 获取1分钟原始数据 + # 确保 date_selected 是 date 对象 + if isinstance(date_selected, datetime): + target_date = date_selected.date() + else: + target_date = date_selected + + start_datetime = datetime.combine(target_date, time(9, 30)) + end_datetime = datetime.combine(target_date, time(15, 0)) + + # 创建1分钟数据模型和表名 + model_class = create_stock_kline_model(stock_code, '1m') + table_name = model_class._meta.table_name + + # 直接使用SQL查询 + sql_query = f""" + SELECT timestamp as datetime, open, high, low, close, volume + FROM {table_name} + WHERE timestamp >= %s AND timestamp <= %s + ORDER BY timestamp + """ + + # 使用DatabaseManager执行查询 + result = self.db_manager.execute_sql(sql_query, (start_datetime, end_datetime)) + + if not result: + return None + + # 转换为DataFrame + data_list = [] + for record in result: + data_list.append({ + 'datetime': record[0], + 'open': float(record[1]), + 'high': float(record[2]), + 'low': float(record[3]), + 'close': float(record[4]), + 'volume': int(record[5]) + }) + + if not data_list: + return None + + df_1m = pd.DataFrame(data_list) + df_1m['datetime'] = pd.to_datetime(df_1m['datetime']) + + # 过滤出交易时间内的数据 + df_1m = self._filter_trading_hours(df_1m, date_selected) + + if df_1m.empty: + return None + + # 重采样到目标时间周期 + df_resampled = self._resample_data(df_1m, timeframe) + + return df_resampled + + except Exception as e: + print(f"加载K线数据失败: {e}") + return None + + def _filter_trading_hours(self, df: pd.DataFrame, target_date: datetime) -> pd.DataFrame: + """ + 过滤出交易时间内的数据 + + A股交易时间: + 上午: 09:30-11:30 + 下午: 13:00-15:00 + """ + if df.empty: + return df + + # 确保 target_date 是 date 对象 + if isinstance(target_date, datetime): + compare_date = target_date.date() + else: + compare_date = target_date + + # 过滤出目标日期 + df = df[df['datetime'].dt.date == compare_date].copy() + + # 过滤交易时间 + df = df[ + ((df['datetime'].dt.time >= time(9, 30)) & (df['datetime'].dt.time <= time(11, 30))) | + ((df['datetime'].dt.time >= time(13, 0)) & (df['datetime'].dt.time <= time(15, 0))) + ] + + return df.sort_values('datetime').reset_index(drop=True) + + def _resample_data(self, df_1m: pd.DataFrame, timeframe: str) -> pd.DataFrame: + """ + 将1分钟数据重采样到指定时间周期 + + Args: + df_1m: 1分钟K线数据 + timeframe: 目标时间周期 ('15m', '30m', '60m') + + Returns: + pd.DataFrame: 重采样后的数据 + """ + if df_1m.empty: + return df_1m + + # 设置datetime为索引 + df_1m = df_1m.set_index('datetime') + + # 确保数值列的数据类型 + numeric_columns = ['open', 'high', 'low', 'close', 'volume'] + for col in numeric_columns: + if col in df_1m.columns: + df_1m[col] = pd.to_numeric(df_1m[col], errors='coerce') + + # 重采样规则 + resample_rule = { + '15m': '15min', + '30m': '30min', + '60m': '60min' + }.get(timeframe, '15min') + + # OHLC重采样 + ohlc_dict = { + 'open': 'first', + 'high': 'max', + 'low': 'min', + 'close': 'last', + 'volume': 'sum' + } + + # 执行重采样 + df_resampled = df_1m.resample(resample_rule).agg(ohlc_dict) + + # 删除没有数据的行(NaN) + df_resampled = df_resampled.dropna() + + # 重置索引,使datetime成为普通列 + df_resampled = df_resampled.reset_index() + + return df_resampled \ No newline at end of file diff --git a/src/analyzer/core/indicators.py b/src/analyzer/core/indicators.py new file mode 100644 index 0000000..b5a74ec --- /dev/null +++ b/src/analyzer/core/indicators.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +""" +技术指标计算器 + +负责计算移动平均线和检测金叉死叉信号 +""" + +import pandas as pd +import numpy as np +from typing import Tuple + +class MovingAverageIndicator: + """移动平均线指标计算器""" + + @staticmethod + def calculate_ma(prices: pd.Series, period: int) -> pd.Series: + """ + 计算简单移动平均线 + + Args: + prices: 价格序列 + period: 计算周期 + + Returns: + pd.Series: 移动平均线值 + """ + return prices.rolling(window=period, min_periods=1).mean() + + @staticmethod + def find_crossovers(fast_ma: pd.Series, slow_ma: pd.Series) -> Tuple[pd.Series, pd.Series]: + """ + 检测移动平均线的金叉和死叉 + + 金叉:短期均线向上穿过长期均线 + 死叉:短期均线向下穿过长期均线 + + Args: + fast_ma: 短期移动平均线 (例如MA5) + slow_ma: 长期移动平均线 (例如MA20) + + Returns: + Tuple[pd.Series, pd.Series]: (金叉位置, 死叉位置) + """ + if len(fast_ma) == 0 or len(slow_ma) == 0: + return pd.Series(dtype=bool), pd.Series(dtype=bool) + + # 计算两条均线的差值 + diff = fast_ma - slow_ma + + # 检测穿越点 + # 金叉:差值从负转正 + golden_cross = (diff > 0) & (diff.shift(1) <= 0) + + # 死叉:差值从正转负 + death_cross = (diff < 0) & (diff.shift(1) >= 0) + + # 返回发生交叉的位置 + return golden_cross[golden_cross], death_cross[death_cross] \ No newline at end of file diff --git a/src/analyzer/main.py b/src/analyzer/main.py new file mode 100644 index 0000000..66e0fbb --- /dev/null +++ b/src/analyzer/main.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +股票K线分析工具主程序 + +这是一个基于PySide6的图形化股票数据分析工具,支持: +- 多时间周期K线图显示(15分钟、30分钟、60分钟) +- 移动平均线计算和显示(MA5、MA20) +- 金叉/死叉信号自动检测和标记 +- 从数据库中选择股票和日期进行分析 + +使用方法: + python src/analyzer/main.py +""" + +import sys +import os +from pathlib import Path + +# 添加项目根目录到Python路径 +project_root = Path(__file__).parent.parent +sys.path.insert(0, str(project_root)) + +try: + from PySide6.QtWidgets import QApplication + from PySide6.QtCore import QCoreApplication +except ImportError: + print("错误: 未安装PySide6库") + print("请运行: pip install PySide6") + sys.exit(1) + +from analyzer.ui.main_window import MainWindow + +def main(): + """主函数""" + # 设置应用程序属性 + QCoreApplication.setApplicationName("股票K线分析工具") + QCoreApplication.setApplicationVersion("1.0.0") + QCoreApplication.setOrganizationName("QTrade") + + # 创建应用程序实例 + app = QApplication(sys.argv) + + # 创建并显示主窗口 + window = MainWindow() + window.show() + + # 运行应用程序 + return app.exec() + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/src/analyzer/ui/__init__.py b/src/analyzer/ui/__init__.py new file mode 100644 index 0000000..3def078 --- /dev/null +++ b/src/analyzer/ui/__init__.py @@ -0,0 +1,4 @@ +# src/analyzer/ui/__init__.py +""" +UI模块 - 用户界面组件 +""" \ No newline at end of file diff --git a/src/analyzer/ui/main_window.py b/src/analyzer/ui/main_window.py new file mode 100644 index 0000000..43533fd --- /dev/null +++ b/src/analyzer/ui/main_window.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +""" +主窗口UI类 + +提供股票数据选择界面和K线图显示功能 +""" + +import sys +from datetime import date, timedelta +from PySide6.QtWidgets import ( + QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, + QComboBox, QPushButton, QDateEdit, QLabel, + QGroupBox, QMessageBox, QStatusBar, QSplitter +) +from PySide6.QtCore import Qt, QDate, QThread, Signal +from PySide6.QtGui import QFont + +from analyzer.widgets.kline_chart_widget import KlineChartWidget +from analyzer.core.data_loader import DataLoader + +class MainWindow(QMainWindow): + """主窗口类""" + + def __init__(self): + super().__init__() + self.data_loader = DataLoader() + self.init_ui() + self.load_stock_list() + + def init_ui(self): + """初始化用户界面""" + self.setWindowTitle("股票K线分析工具") + self.setGeometry(100, 100, 1400, 900) + + # 创建中央部件 + central_widget = QWidget() + self.setCentralWidget(central_widget) + + # 创建主布局 + main_layout = QVBoxLayout(central_widget) + + # 创建控制面板 + control_panel = self.create_control_panel() + main_layout.addWidget(control_panel) + + # 创建分割器,用于分割控制面板和图表 + splitter = QSplitter(Qt.Vertical) + + # 创建K线图表组件 + self.kline_chart = KlineChartWidget() + splitter.addWidget(self.kline_chart) + + main_layout.addWidget(splitter) + + # 创建状态栏 + self.status_bar = QStatusBar() + self.setStatusBar(self.status_bar) + self.status_bar.showMessage("就绪") + + def create_control_panel(self): + """创建控制面板""" + group_box = QGroupBox("数据选择") + layout = QHBoxLayout(group_box) + + # 股票选择 + layout.addWidget(QLabel("股票代码:")) + self.stock_combo = QComboBox() + self.stock_combo.setMinimumWidth(120) + layout.addWidget(self.stock_combo) + + layout.addWidget(QLabel(" ")) # 分隔符 + + # 日期选择 + layout.addWidget(QLabel("日期:")) + self.date_edit = QDateEdit() + self.date_edit.setDate(QDate.currentDate()) + self.date_edit.setCalendarPopup(True) + self.date_edit.setMinimumWidth(120) + layout.addWidget(self.date_edit) + + layout.addWidget(QLabel(" ")) # 分隔符 + + # 时间周期选择 + layout.addWidget(QLabel("时间周期:")) + self.timeframe_combo = QComboBox() + self.timeframe_combo.addItems(['15分钟', '30分钟', '60分钟']) + self.timeframe_combo.setCurrentText('15分钟') + self.timeframe_combo.setMinimumWidth(80) + layout.addWidget(self.timeframe_combo) + + layout.addWidget(QLabel(" ")) # 分隔符 + + # 查询按钮 + self.query_button = QPushButton("分析") + self.query_button.clicked.connect(self.analyze_data) + self.query_button.setMinimumWidth(80) + layout.addWidget(self.query_button) + + # 添加弹性空间 + layout.addStretch() + + return group_box + + def load_stock_list(self): + """加载股票列表""" + try: + self.status_bar.showMessage("正在加载股票列表...") + stocks = self.data_loader.get_available_stocks() + + self.stock_combo.clear() + if stocks: + self.stock_combo.addItems(stocks) + self.status_bar.showMessage(f"已加载 {len(stocks)} 只股票") + else: + self.status_bar.showMessage("未找到股票数据") + + except Exception as e: + error_msg = f"加载股票列表失败: {str(e)}" + self.status_bar.showMessage(error_msg) + QMessageBox.warning(self, "警告", error_msg) + + def analyze_data(self): + """分析数据""" + stock_code = self.stock_combo.currentText() + selected_date = self.date_edit.date().toPython() + timeframe_text = self.timeframe_combo.currentText() + + # 转换时间周期 + timeframe_map = { + '15分钟': '15m', + '30分钟': '30m', + '60分钟': '60m' + } + timeframe = timeframe_map.get(timeframe_text, '15m') + + if not stock_code: + QMessageBox.warning(self, "警告", "请选择股票代码") + return + + try: + self.status_bar.showMessage(f"正在分析 {stock_code} {selected_date} ({timeframe_text})...") + self.query_button.setEnabled(False) + + # 调用图表组件进行绘制 + success = self.kline_chart.plot_kline_data(stock_code, selected_date, timeframe) + + if success: + self.status_bar.showMessage(f"分析完成: {stock_code} {selected_date} ({timeframe_text})") + else: + self.status_bar.showMessage("分析失败: 无数据或出现错误") + + except Exception as e: + error_msg = f"分析失败: {str(e)}" + self.status_bar.showMessage(error_msg) + QMessageBox.critical(self, "错误", error_msg) + + finally: + self.query_button.setEnabled(True) \ No newline at end of file diff --git a/src/analyzer/widgets/__init__.py b/src/analyzer/widgets/__init__.py new file mode 100644 index 0000000..a130ab3 --- /dev/null +++ b/src/analyzer/widgets/__init__.py @@ -0,0 +1,4 @@ +# src/analyzer/widgets/__init__.py +""" +自定义Widget组件模块 +""" \ No newline at end of file diff --git a/src/analyzer/widgets/kline_chart_widget.py b/src/analyzer/widgets/kline_chart_widget.py new file mode 100644 index 0000000..18f9a9a --- /dev/null +++ b/src/analyzer/widgets/kline_chart_widget.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +""" +K线图表组件 + +使用matplotlib绘制K线图,包含移动平均线和交叉信号标记 +""" + +import pandas as pd +import numpy as np +from datetime import datetime, timedelta +from typing import Optional, Tuple, List + +from PySide6.QtWidgets import QWidget, QVBoxLayout, QMessageBox +import matplotlib.pyplot as plt +from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas +from matplotlib.figure import Figure +from matplotlib.patches import Rectangle +import matplotlib.dates as mdates + +from analyzer.core.data_loader import DataLoader +from analyzer.core.indicators import MovingAverageIndicator + +# 设置matplotlib中文字体 +plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'Arial'] +plt.rcParams['axes.unicode_minus'] = False + +class KlineChartWidget(QWidget): + """K线图表组件""" + + def __init__(self, parent=None): + super().__init__(parent) + self.data_loader = DataLoader() + self.ma_indicator = MovingAverageIndicator() + self.init_ui() + + def init_ui(self): + """初始化UI""" + layout = QVBoxLayout(self) + + # 创建matplotlib图形 + self.figure = Figure(figsize=(14, 8), dpi=100) + self.canvas = FigureCanvas(self.figure) + layout.addWidget(self.canvas) + + # 设置样式 + self.figure.patch.set_facecolor('white') + + def plot_kline_data(self, stock_code: str, date_selected: datetime, timeframe: str) -> bool: + """ + 绘制K线数据 + + Args: + stock_code: 股票代码 + date_selected: 选择的日期 + timeframe: 时间周期 ('15m', '30m', '60m') + + Returns: + bool: 是否成功绘制 + """ + try: + # 清空之前的图形 + self.figure.clear() + + # 获取数据 + df = self.data_loader.load_kline_data(stock_code, date_selected, timeframe) + if df is None or df.empty: + self._show_no_data_message() + return False + + # 计算移动平均线 + df['ma5'] = self.ma_indicator.calculate_ma(df['close'], 5) + df['ma20'] = self.ma_indicator.calculate_ma(df['close'], 20) + + # 保存当前数据框供时间轴设置使用 + self._current_df = df + + # 检测金叉死叉 + golden_crosses, death_crosses = self.ma_indicator.find_crossovers(df['ma5'], df['ma20']) + + # 绘制图形 + ax = self.figure.add_subplot(111) + + # 绘制K线 + self._plot_candlesticks(ax, df) + + # 绘制移动平均线 + self._plot_moving_averages(ax, df) + + # 标记金叉死叉 + self._plot_crossover_signals(ax, df, golden_crosses, death_crosses) + + # 设置图形样式 + self._setup_chart_style(ax, stock_code, date_selected, timeframe) + + # 刷新画布 + self.canvas.draw() + + return True + + except Exception as e: + QMessageBox.critical(self, "绘图错误", f"绘制K线图时发生错误:\n{str(e)}") + return False + + def _plot_candlesticks(self, ax, df: pd.DataFrame): + """绘制K线""" + for i, (idx, row) in enumerate(df.iterrows()): + # 确定颜色:红涨绿跌 + color = 'red' if row['close'] >= row['open'] else 'green' + + # 绘制影线 + ax.plot([i, i], [row['low'], row['high']], color='black', linewidth=0.8) + + # 绘制实体 + height = abs(row['close'] - row['open']) + bottom = min(row['open'], row['close']) + rect = Rectangle((i-0.4, bottom), 0.8, height, + facecolor=color, edgecolor='black', linewidth=0.5, alpha=0.8) + ax.add_patch(rect) + + def _plot_moving_averages(self, ax, df: pd.DataFrame): + """绘制移动平均线""" + x_positions = range(len(df)) + + # MA5线 - 过滤掉NaN值,确保线条连续 + ma5_valid = df['ma5'].dropna() + if not ma5_valid.empty: + ma5_x = [i for i in x_positions if not pd.isna(df.iloc[i]['ma5'])] + ma5_y = [df.iloc[i]['ma5'] for i in ma5_x] + ax.plot(ma5_x, ma5_y, label='MA5', color='blue', linewidth=1.5, alpha=0.8) + + # MA20线 - 过滤掉NaN值,确保线条连续 + ma20_valid = df['ma20'].dropna() + if not ma20_valid.empty: + ma20_x = [i for i in x_positions if not pd.isna(df.iloc[i]['ma20'])] + ma20_y = [df.iloc[i]['ma20'] for i in ma20_x] + ax.plot(ma20_x, ma20_y, label='MA20', color='orange', linewidth=1.5, alpha=0.8) + + def _plot_crossover_signals(self, ax, df: pd.DataFrame, golden_crosses: pd.Series, death_crosses: pd.Series): + """标记金叉死叉信号""" + if not golden_crosses.empty: + # 金叉标记(向上箭头) + for idx in golden_crosses.index: + pos = df.index.get_loc(idx) + price = df.loc[idx, 'low'] * 0.995 # 在最低价下方一点 + ax.annotate('↗', xy=(pos, price), fontsize=16, color='gold', + ha='center', va='top', weight='bold') + + if not death_crosses.empty: + # 死叉标记(向下箭头) + for idx in death_crosses.index: + pos = df.index.get_loc(idx) + price = df.loc[idx, 'high'] * 1.005 # 在最高价上方一点 + ax.annotate('↘', xy=(pos, price), fontsize=16, color='purple', + ha='center', va='bottom', weight='bold') + + def _setup_chart_style(self, ax, stock_code: str, date_selected: datetime, timeframe: str): + """设置图表样式""" + # 设置标题 + timeframe_names = {'15m': '15分钟', '30m': '30分钟', '60m': '60分钟'} + title = f"{stock_code} K线图 - {date_selected.strftime('%Y-%m-%d')} ({timeframe_names.get(timeframe, timeframe)})" + ax.set_title(title, fontsize=14, pad=20) + + # 设置坐标轴标签 + ax.set_xlabel('时间', fontsize=12) + ax.set_ylabel('价格', fontsize=12) + + # 设置X轴时间格式显示 + self._setup_time_axis(ax) + + # 设置网格 + ax.grid(True, alpha=0.3) + + # 设置图例 + ax.legend(loc='upper left') + + # 紧凑布局 + self.figure.tight_layout() + + def _setup_time_axis(self, ax): + """设置时间轴格式""" + import matplotlib.dates as mdates + + # 获取当前数据框 + if hasattr(self, '_current_df') and self._current_df is not None: + df = self._current_df + + # 设置X轴刻度位置和标签 + num_ticks = min(len(df), 8) # 最多显示8个时间刻度 + tick_positions = [] + tick_labels = [] + + if num_ticks > 1: + step = len(df) // (num_ticks - 1) + for i in range(0, len(df), step): + if i < len(df): + tick_positions.append(i) + # 格式化时间为 HH:MM + time_str = df.iloc[i]['datetime'].strftime('%H:%M') + tick_labels.append(time_str) + + # 确保最后一个点也被包含 + if tick_positions[-1] != len(df) - 1: + tick_positions.append(len(df) - 1) + time_str = df.iloc[-1]['datetime'].strftime('%H:%M') + tick_labels.append(time_str) + + ax.set_xticks(tick_positions) + ax.set_xticklabels(tick_labels, rotation=45, ha='right') + else: + # 如果没有数据,使用默认格式 + ax.tick_params(axis='x', rotation=45) + + def _show_no_data_message(self): + """显示无数据消息""" + self.figure.clear() + ax = self.figure.add_subplot(111) + ax.text(0.5, 0.5, '该日期无数据\n\n请尝试选择其他交易日', + ha='center', va='center', fontsize=16, + bbox=dict(boxstyle="round,pad=1", facecolor="lightgray")) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + ax.axis('off') + self.canvas.draw() \ No newline at end of file diff --git a/src/data_process_model/database_config.py b/src/data_process_model/database_config.py index 5e7697e..aa48e82 100644 --- a/src/data_process_model/database_config.py +++ b/src/data_process_model/database_config.py @@ -7,7 +7,10 @@ from peewee import MySQLDatabase, Model import logging # 导入公共配置 -from common import LOG_PREFIXES +try: + from .common import LOG_PREFIXES +except ImportError: + from common import LOG_PREFIXES # 配置日志 logging.basicConfig(level=logging.INFO) diff --git a/src/data_process_model/database_manager.py b/src/data_process_model/database_manager.py index 5d038af..f40c001 100644 --- a/src/data_process_model/database_manager.py +++ b/src/data_process_model/database_manager.py @@ -11,7 +11,12 @@ from datetime import datetime import pandas as pd # 导入公共配置 -from common import LOG_PREFIXES, normalize_stock_code, get_table_name +try: + # 相对导入(当作为包的一部分时) + from .common import LOG_PREFIXES, normalize_stock_code, get_table_name +except ImportError: + # 绝对导入(当直接运行时) + from common import LOG_PREFIXES, normalize_stock_code, get_table_name logger = logging.getLogger(__name__) diff --git a/src/data_process_model/main.py b/src/data_process_model/main.py index 0f7616c..f169474 100644 --- a/src/data_process_model/main.py +++ b/src/data_process_model/main.py @@ -18,7 +18,7 @@ from stockdata_manager import get_stock_data_manager g_stock_code_list = [ #normalize_stock_code("601658.SH"), #normalize_stock_code("510310.SH"), - #normalize_stock_code("601398.SH"), + normalize_stock_code("601398.SH"), #normalize_stock_code("601288.SH"), #normalize_stock_code("601609.SH"), #normalize_stock_code("601288.SH"), diff --git a/src/data_process_model/stock_models.py b/src/data_process_model/stock_models.py index 8552b85..c9d3973 100644 --- a/src/data_process_model/stock_models.py +++ b/src/data_process_model/stock_models.py @@ -5,16 +5,22 @@ from typing import Dict from peewee import DateTimeField, DecimalField, BigIntegerField + +# 导入数据库配置 try: - from database_config import BaseModel, get_database -except ImportError: from .database_config import BaseModel, get_database -from database_manager import BaseModel, get_database +except ImportError: + from database_config import BaseModel, get_database # 导入公共配置 -from common import ( - normalize_stock_code, get_table_name, LOG_PREFIXES -) +try: + from .common import ( + normalize_stock_code, get_table_name, LOG_PREFIXES + ) +except ImportError: + from common import ( + normalize_stock_code, get_table_name, LOG_PREFIXES + ) import logging diff --git a/src/data_process_model/stockdata_manager.py b/src/data_process_model/stockdata_manager.py index d4eef5c..1903ca5 100644 --- a/src/data_process_model/stockdata_manager.py +++ b/src/data_process_model/stockdata_manager.py @@ -11,13 +11,25 @@ from decimal import Decimal from datetime import datetime # 导入底层依赖 -from database_manager import get_database_manager -from stock_models import create_stock_kline_model +try: + # 相对导入(当作为包的一部分时) + from .database_manager import get_database_manager + from .stock_models import create_stock_kline_model +except ImportError: + # 绝对导入(当直接运行时) + from database_manager import get_database_manager + from stock_models import create_stock_kline_model # 导入公共配置 -from common import ( - normalize_stock_code, get_table_name, - validate_kline_data, LOG_PREFIXES +try: + from .common import ( + normalize_stock_code, get_table_name, + validate_kline_data, LOG_PREFIXES + ) +except ImportError: + from common import ( + normalize_stock_code, get_table_name, + validate_kline_data, LOG_PREFIXES ) logger = logging.getLogger(__name__) diff --git a/src/data_process_model/technical_indicators.py b/src/data_process_model/technical_indicators.py index 75fd513..186e9ea 100644 --- a/src/data_process_model/technical_indicators.py +++ b/src/data_process_model/technical_indicators.py @@ -7,11 +7,19 @@ import numpy as np import talib from typing import Dict, Any, Optional, List from dataclasses import dataclass, field -from stockdata_manager import StockDataManager +try: + # 相对导入(当作为包的一部分时) + from .stockdata_manager import StockDataManager +except ImportError: + # 绝对导入(当直接运行时) + from stockdata_manager import StockDataManager import logging # 导入公共配置 -from common import LOG_PREFIXES, validate_kline_data +try: + from .common import LOG_PREFIXES, validate_kline_data +except ImportError: + from common import LOG_PREFIXES, validate_kline_data logger = logging.getLogger(__name__)