From cfa9613da6bdb31079eda5e73a5a5dba2544681b Mon Sep 17 00:00:00 2001 From: cuizhan <3971687@qq.com> Date: Tue, 23 Dec 2025 23:39:01 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84viewer=E6=8C=87=E6=A0=87?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=EF=BC=9A=E4=BD=BF=E7=94=A8=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=8F=82=E6=95=B0=E8=87=AA=E5=B7=B1=E8=AE=A1?= =?UTF-8?q?=E7=AE=97MACD=E5=92=8CRSI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除DataService指标获取逻辑,简化viewer架构 - viewer从configs/global.yaml读取MACD(6,13,5)和RSI(6,12,24)参数 - 修正MACD柱状图颜色为红涨绿跌 - DataService.get_indicator()改为只从数据库读取,不做完整性检查和自动下载 - 修复重复索引导致的对齐问题 --- simple_kline_viewer.py | 151 +++++++++++++++++++++---------- src/data_service/data_service.py | 72 +++++---------- 2 files changed, 122 insertions(+), 101 deletions(-) diff --git a/simple_kline_viewer.py b/simple_kline_viewer.py index 8a4a5a0..63eaade 100644 --- a/simple_kline_viewer.py +++ b/simple_kline_viewer.py @@ -53,7 +53,10 @@ plt.rcParams["axes.unicode_minus"] = False class KlineCanvas(FigureCanvasQTAgg): - """K线画布 - 支持键盘导航""" + """ + K线画布 - 支持键盘导航 + 指标参数从配置文件读取 + """ def __init__(self, parent=None): self.fig = Figure(figsize=(16, 10), dpi=100) @@ -66,6 +69,61 @@ class KlineCanvas(FigureCanvasQTAgg): self.current_end = 100 # 当前显示结束位置 self.display_count = 100 # 默认显示100条 + # 加载指标配置参数 - 不使用默认值,读取失败直接报错 + try: + config = Config("configs/global.yaml") + indicators_config = config.get("indicators") + + if not indicators_config: + raise ValueError("配置文件中未找到 'indicators' 配置项") + + # MACD参数 + macd_config = indicators_config.get("macd") + if not macd_config: + raise ValueError("配置文件中未找到 'indicators.macd' 配置项") + + if "fast_period" not in macd_config: + raise ValueError("配置文件中未找到 'indicators.macd.fast_period'") + if "slow_period" not in macd_config: + raise ValueError("配置文件中未找到 'indicators.macd.slow_period'") + if "signal_period" not in macd_config: + raise ValueError("配置文件中未找到 'indicators.macd.signal_period'") + + self.macd_fast = macd_config["fast_period"] + self.macd_slow = macd_config["slow_period"] + self.macd_signal = macd_config["signal_period"] + + print( + f"[配置] MACD参数: fast={self.macd_fast}, slow={self.macd_slow}, signal={self.macd_signal}" + ) + + # RSI参数 + rsi_config = indicators_config.get("rsi") + if not rsi_config: + raise ValueError("配置文件中未找到 'indicators.rsi' 配置项") + + if "fast" not in rsi_config: + raise ValueError("配置文件中未找到 'indicators.rsi.fast'") + if "mid" not in rsi_config: + raise ValueError("配置文件中未找到 'indicators.rsi.mid'") + if "slow" not in rsi_config: + raise ValueError("配置文件中未找到 'indicators.rsi.slow'") + + self.rsi_fast = rsi_config["fast"] + self.rsi_mid = rsi_config["mid"] + self.rsi_slow = rsi_config["slow"] + + print( + f"[配置] RSI参数: fast={self.rsi_fast}, mid={self.rsi_mid}, slow={self.rsi_slow}" + ) + + except Exception as e: + print(f"\n❌ 配置文件读取失败: {e}") + print("请检查 configs/global.yaml 文件中的 indicators 配置项") + import sys + + sys.exit(1) + # 创建专业黑色主题样式(红涨绿跌) self.style = mpf.make_mpf_style( base_mpf_style="nightclouds", @@ -452,42 +510,40 @@ class KlineCanvas(FigureCanvasQTAgg): self.draw() def _plot_macd(self, df, ax): - """绘制MACD指标""" + """绘制MACD指标(使用配置文件参数)""" try: - # 数据量检查:MACD需要至少26+9=35条数据 - if len(df) < 35: - ax.text( - 0.5, - 0.5, - f"数据不足(需要35条,当前{len(df)}条)", - ha="center", - va="center", - color="white", - transform=ax.transAxes, - ) + import pandas as pd + + # 数据量检查 + min_length = self.macd_slow + self.macd_signal + if len(df) < min_length: return - # 计算MACD - exp1 = df["close"].ewm(span=12, adjust=False).mean() - exp2 = df["close"].ewm(span=26, adjust=False).mean() + # 计算MACD(使用配置文件参数) + exp1 = df["close"].ewm(span=self.macd_fast, adjust=False).mean() + exp2 = df["close"].ewm(span=self.macd_slow, adjust=False).mean() macd = exp1 - exp2 - signal = macd.ewm(span=9, adjust=False).mean() + signal = macd.ewm(span=self.macd_signal, adjust=False).mean() histogram = macd - signal # 保存MACD数据供鼠标悬停使用 - import pandas as pd - self.current_macd_data = pd.DataFrame( {"dif": macd, "dea": signal, "histogram": histogram} ).reset_index(drop=True) - # 绘制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柱状图(红涨绿跌) + colors = ["#ff0000" if x >= 0 else "#00ff00" for x in histogram] + ax.bar( + range(len(histogram)), + histogram.values, + color=colors, + alpha=0.6, + width=0.8, + ) # 绘制MACD和信号线 - ax.plot(macd.values, color="#00ffff", linewidth=1, label="MACD") - ax.plot(signal.values, color="#ffff00", linewidth=1, label="Signal") + ax.plot(macd.values, color="#00ffff", linewidth=1.5, label="MACD(DIF)") + ax.plot(signal.values, color="#ffff00", linewidth=1.5, label="DEA") ax.axhline(0, color="white", linewidth=0.5, alpha=0.5) ax.legend( @@ -499,30 +555,27 @@ class KlineCanvas(FigureCanvasQTAgg): ) except Exception as e: - print(f"MACD计算失败: {e}") + print(f"MACD绘制失败: {e}") + traceback.print_exc() def _plot_rsi(self, df, ax): - """绘制RSI指标""" + """绘制RSI指标(使用配置文件参数)""" try: - # 数据量检查:RSI需要至少period+1条数据 - if len(df) < 25: # 最大周期24+1 - ax.text( - 0.5, - 0.5, - f"数据不足(需要25条,当前{len(df)}条)", - ha="center", - va="center", - color="white", - transform=ax.transAxes, - ) - return - - # 计算RSI(6,12,24) import pandas as pd - rsi_data = {} + # 数据量检查 + if len(df) < self.rsi_slow + 1: + return - for period in [6, 12, 24]: + rsi_data = {} + colors = { + self.rsi_fast: "#ffff00", + self.rsi_mid: "#00ffff", + self.rsi_slow: "#ff00ff", + } + + # 计算RSI(使用配置文件参数) + for period in [self.rsi_fast, self.rsi_mid, self.rsi_slow]: delta = df["close"].diff() gain = (delta.where(delta > 0, 0)).rolling(window=period).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean() @@ -532,9 +585,12 @@ class KlineCanvas(FigureCanvasQTAgg): # 保存RSI数据 rsi_data[f"rsi{period}"] = rsi - colors = {6: "#ffff00", 12: "#00ffff", 24: "#ff00ff"} + # 绘制RSI线 ax.plot( - rsi.values, color=colors[period], linewidth=1, label=f"RSI{period}" + rsi.values, + color=colors[period], + linewidth=1.5, + label=f"RSI{period}", ) # 保存RSI数据供鼠标悬停使用 @@ -555,13 +611,8 @@ class KlineCanvas(FigureCanvasQTAgg): ) except Exception as e: - print(f"RSI计算失败: {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): diff --git a/src/data_service/data_service.py b/src/data_service/data_service.py index b4ebba6..47b663f 100644 --- a/src/data_service/data_service.py +++ b/src/data_service/data_service.py @@ -289,17 +289,12 @@ class DataService: end: Optional[datetime] = None, ) -> Optional[pd.DataFrame]: """ - 获取技术指标数据 - - 自动处理: - 1. 检查指标缓存 - 2. 缓存未命中 → 获取K线 + 计算指标 - 3. 缓存计算结果 + 获取技术指标数据(直接从数据库读取,不做完整性检查) Args: symbol: 标的代码 period: 周期 - indicator_name: 指标名称(如'MACD', 'KDJ') + indicator_name: 指标名称(如'macd', 'kdj') params: 指标参数 start: 开始时间 end: 结束时间 @@ -307,13 +302,12 @@ class DataService: Returns: 指标DataFrame或None """ - # 先尝试从缓存获取指标 # 验证指标类型是否有效 if not IndicatorType.is_valid(indicator_name): logger.error(f"Unknown indicator type: {indicator_name}") return None - # 直接使用indicator_name(字符串) + # 先尝试从缓存获取指标 indicator_data = self.cache.get_indicator(symbol, period, indicator_name) if indicator_data is not None: @@ -327,56 +321,32 @@ class DataService: return indicator_data[mask] return indicator_data - # 缓存未命中,需要计算 - logger.info(f"Calculating indicator: {symbol}_{period}_{indicator_name}") + # 缓存未命中,直接从数据库读取 + logger.info( + f"Loading indicator from database: {symbol}_{period}_{indicator_name}" + ) - # 获取K线数据 - klines = self.get_klines(symbol, period, start, end) - if klines is None or klines.empty: - logger.warning( - f"No klines available for indicator calculation: {symbol}_{period}" - ) - return None + indicator_data = self.storage.load_indicators(symbol, period, indicator_name) - # 计算指标 - try: - indicator_data = self.indicator_manager.calculate( - klines, indicator_names=[indicator_name.lower()] - ) - - # 提取指标列(根据指标名称获取相应的列) - indicator_columns = self._get_indicator_columns( - indicator_data, indicator_name - ) - - if indicator_columns.empty: - logger.warning(f"No indicator columns found for: {indicator_name}") - return None - - # 保存到存储和缓存 - self.storage.save_indicators( - symbol, period, indicator_name, indicator_columns - ) - self.cache.set_indicator(symbol, period, indicator_name, indicator_columns) - - logger.info( - f"Indicator calculated and cached: {symbol}_{period}_{indicator_name}" - ) + if indicator_data is not None and not indicator_data.empty: + # 保存到缓存 + self.cache.set_indicator(symbol, period, indicator_name, indicator_data) # 返回时间切片 if start is not None or end is not None: - mask = pd.Series(True, index=indicator_columns.index) + mask = pd.Series(True, index=indicator_data.index) if start is not None: - mask &= indicator_columns.index >= start + mask &= indicator_data.index >= start if end is not None: - mask &= indicator_columns.index <= end - return indicator_columns[mask] + mask &= indicator_data.index <= end + return indicator_data[mask] + return indicator_data - return indicator_columns - - except Exception as e: - logger.error(f"Failed to calculate indicator {indicator_name}: {e}") - return None + # 数据库中没有,返回None(不自动计算或下载) + logger.warning( + f"Indicator not found in database: {symbol}_{period}_{indicator_name}" + ) + return None def get_multiple_indicators( self,