重构viewer指标显示:使用配置文件参数自己计算MACD和RSI
- 移除DataService指标获取逻辑,简化viewer架构 - viewer从configs/global.yaml读取MACD(6,13,5)和RSI(6,12,24)参数 - 修正MACD柱状图颜色为红涨绿跌 - DataService.get_indicator()改为只从数据库读取,不做完整性检查和自动下载 - 修复重复索引导致的对齐问题
This commit is contained in:
parent
c3f0fef478
commit
cfa9613da6
@ -53,7 +53,10 @@ plt.rcParams["axes.unicode_minus"] = False
|
|||||||
|
|
||||||
|
|
||||||
class KlineCanvas(FigureCanvasQTAgg):
|
class KlineCanvas(FigureCanvasQTAgg):
|
||||||
"""K线画布 - 支持键盘导航"""
|
"""
|
||||||
|
K线画布 - 支持键盘导航
|
||||||
|
指标参数从配置文件读取
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self, parent=None):
|
def __init__(self, parent=None):
|
||||||
self.fig = Figure(figsize=(16, 10), dpi=100)
|
self.fig = Figure(figsize=(16, 10), dpi=100)
|
||||||
@ -66,6 +69,61 @@ class KlineCanvas(FigureCanvasQTAgg):
|
|||||||
self.current_end = 100 # 当前显示结束位置
|
self.current_end = 100 # 当前显示结束位置
|
||||||
self.display_count = 100 # 默认显示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(
|
self.style = mpf.make_mpf_style(
|
||||||
base_mpf_style="nightclouds",
|
base_mpf_style="nightclouds",
|
||||||
@ -452,42 +510,40 @@ class KlineCanvas(FigureCanvasQTAgg):
|
|||||||
self.draw()
|
self.draw()
|
||||||
|
|
||||||
def _plot_macd(self, df, ax):
|
def _plot_macd(self, df, ax):
|
||||||
"""绘制MACD指标"""
|
"""绘制MACD指标(使用配置文件参数)"""
|
||||||
try:
|
try:
|
||||||
# 数据量检查:MACD需要至少26+9=35条数据
|
import pandas as pd
|
||||||
if len(df) < 35:
|
|
||||||
ax.text(
|
# 数据量检查
|
||||||
0.5,
|
min_length = self.macd_slow + self.macd_signal
|
||||||
0.5,
|
if len(df) < min_length:
|
||||||
f"数据不足(需要35条,当前{len(df)}条)",
|
|
||||||
ha="center",
|
|
||||||
va="center",
|
|
||||||
color="white",
|
|
||||||
transform=ax.transAxes,
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# 计算MACD
|
# 计算MACD(使用配置文件参数)
|
||||||
exp1 = df["close"].ewm(span=12, adjust=False).mean()
|
exp1 = df["close"].ewm(span=self.macd_fast, adjust=False).mean()
|
||||||
exp2 = df["close"].ewm(span=26, adjust=False).mean()
|
exp2 = df["close"].ewm(span=self.macd_slow, adjust=False).mean()
|
||||||
macd = exp1 - exp2
|
macd = exp1 - exp2
|
||||||
signal = macd.ewm(span=9, adjust=False).mean()
|
signal = macd.ewm(span=self.macd_signal, adjust=False).mean()
|
||||||
histogram = macd - signal
|
histogram = macd - signal
|
||||||
|
|
||||||
# 保存MACD数据供鼠标悬停使用
|
# 保存MACD数据供鼠标悬停使用
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
self.current_macd_data = pd.DataFrame(
|
self.current_macd_data = pd.DataFrame(
|
||||||
{"dif": macd, "dea": signal, "histogram": histogram}
|
{"dif": macd, "dea": signal, "histogram": histogram}
|
||||||
).reset_index(drop=True)
|
).reset_index(drop=True)
|
||||||
|
|
||||||
# 绘制MACD柱状图
|
# 绘制MACD柱状图(红涨绿跌)
|
||||||
colors = ["#00ff00" if x >= 0 else "#ff0000" for x in histogram]
|
colors = ["#ff0000" if x >= 0 else "#00ff00" for x in histogram]
|
||||||
ax.bar(range(len(histogram)), histogram, color=colors, alpha=0.6, width=0.8)
|
ax.bar(
|
||||||
|
range(len(histogram)),
|
||||||
|
histogram.values,
|
||||||
|
color=colors,
|
||||||
|
alpha=0.6,
|
||||||
|
width=0.8,
|
||||||
|
)
|
||||||
|
|
||||||
# 绘制MACD和信号线
|
# 绘制MACD和信号线
|
||||||
ax.plot(macd.values, color="#00ffff", linewidth=1, label="MACD")
|
ax.plot(macd.values, color="#00ffff", linewidth=1.5, label="MACD(DIF)")
|
||||||
ax.plot(signal.values, color="#ffff00", linewidth=1, label="Signal")
|
ax.plot(signal.values, color="#ffff00", linewidth=1.5, label="DEA")
|
||||||
|
|
||||||
ax.axhline(0, color="white", linewidth=0.5, alpha=0.5)
|
ax.axhline(0, color="white", linewidth=0.5, alpha=0.5)
|
||||||
ax.legend(
|
ax.legend(
|
||||||
@ -499,30 +555,27 @@ class KlineCanvas(FigureCanvasQTAgg):
|
|||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"MACD计算失败: {e}")
|
print(f"MACD绘制失败: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
def _plot_rsi(self, df, ax):
|
def _plot_rsi(self, df, ax):
|
||||||
"""绘制RSI指标"""
|
"""绘制RSI指标(使用配置文件参数)"""
|
||||||
try:
|
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
|
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()
|
delta = df["close"].diff()
|
||||||
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
||||||
loss = (-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数据
|
||||||
rsi_data[f"rsi{period}"] = rsi
|
rsi_data[f"rsi{period}"] = rsi
|
||||||
|
|
||||||
colors = {6: "#ffff00", 12: "#00ffff", 24: "#ff00ff"}
|
# 绘制RSI线
|
||||||
ax.plot(
|
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数据供鼠标悬停使用
|
# 保存RSI数据供鼠标悬停使用
|
||||||
@ -555,13 +611,8 @@ class KlineCanvas(FigureCanvasQTAgg):
|
|||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"RSI计算失败: {e}")
|
print(f"RSI绘制失败: {e}")
|
||||||
|
|
||||||
traceback.print_exc()
|
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):
|
class DataLoadThread(QThread):
|
||||||
|
|||||||
@ -289,17 +289,12 @@ class DataService:
|
|||||||
end: Optional[datetime] = None,
|
end: Optional[datetime] = None,
|
||||||
) -> Optional[pd.DataFrame]:
|
) -> Optional[pd.DataFrame]:
|
||||||
"""
|
"""
|
||||||
获取技术指标数据
|
获取技术指标数据(直接从数据库读取,不做完整性检查)
|
||||||
|
|
||||||
自动处理:
|
|
||||||
1. 检查指标缓存
|
|
||||||
2. 缓存未命中 → 获取K线 + 计算指标
|
|
||||||
3. 缓存计算结果
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
symbol: 标的代码
|
symbol: 标的代码
|
||||||
period: 周期
|
period: 周期
|
||||||
indicator_name: 指标名称(如'MACD', 'KDJ')
|
indicator_name: 指标名称(如'macd', 'kdj')
|
||||||
params: 指标参数
|
params: 指标参数
|
||||||
start: 开始时间
|
start: 开始时间
|
||||||
end: 结束时间
|
end: 结束时间
|
||||||
@ -307,13 +302,12 @@ class DataService:
|
|||||||
Returns:
|
Returns:
|
||||||
指标DataFrame或None
|
指标DataFrame或None
|
||||||
"""
|
"""
|
||||||
# 先尝试从缓存获取指标
|
|
||||||
# 验证指标类型是否有效
|
# 验证指标类型是否有效
|
||||||
if not IndicatorType.is_valid(indicator_name):
|
if not IndicatorType.is_valid(indicator_name):
|
||||||
logger.error(f"Unknown indicator type: {indicator_name}")
|
logger.error(f"Unknown indicator type: {indicator_name}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 直接使用indicator_name(字符串)
|
# 先尝试从缓存获取指标
|
||||||
indicator_data = self.cache.get_indicator(symbol, period, indicator_name)
|
indicator_data = self.cache.get_indicator(symbol, period, indicator_name)
|
||||||
|
|
||||||
if indicator_data is not None:
|
if indicator_data is not None:
|
||||||
@ -327,55 +321,31 @@ class DataService:
|
|||||||
return indicator_data[mask]
|
return indicator_data[mask]
|
||||||
return indicator_data
|
return indicator_data
|
||||||
|
|
||||||
# 缓存未命中,需要计算
|
# 缓存未命中,直接从数据库读取
|
||||||
logger.info(f"Calculating indicator: {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
|
|
||||||
|
|
||||||
# 计算指标
|
|
||||||
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(
|
logger.info(
|
||||||
f"Indicator calculated and cached: {symbol}_{period}_{indicator_name}"
|
f"Loading indicator from database: {symbol}_{period}_{indicator_name}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
indicator_data = self.storage.load_indicators(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:
|
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:
|
if start is not None:
|
||||||
mask &= indicator_columns.index >= start
|
mask &= indicator_data.index >= start
|
||||||
if end is not None:
|
if end is not None:
|
||||||
mask &= indicator_columns.index <= end
|
mask &= indicator_data.index <= end
|
||||||
return indicator_columns[mask]
|
return indicator_data[mask]
|
||||||
|
return indicator_data
|
||||||
|
|
||||||
return indicator_columns
|
# 数据库中没有,返回None(不自动计算或下载)
|
||||||
|
logger.warning(
|
||||||
except Exception as e:
|
f"Indicator not found in database: {symbol}_{period}_{indicator_name}"
|
||||||
logger.error(f"Failed to calculate indicator {indicator_name}: {e}")
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def get_multiple_indicators(
|
def get_multiple_indicators(
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user