重构K线查看器:模块化代码结构,修复Pylance错误
- 移除重复的datetime导入 - 添加类型注解(typing.Any)支持Pylance类型检查 - 提取配置加载为独立方法(_load_indicator_config, _load_macd_config, _load_rsi_config) - 提取指标计算为独立方法(_calculate_macd, _calculate_rsi) - 提取键盘导航功能为独立方法(_handle_scroll_left/right, _handle_zoom_in/out等) - 提取鼠标悬停信息构建为独立方法(_build_hover_info) - 添加None检查防止类型错误 - 统一时间选择器逻辑:Tab切换时不修改时间范围 - 恢复30m周期支持 - 更新MACD/RSI配色方案(MACD快线白色慢线黄色,RSI快线黄色中线绿色慢线蓝色) - 删除旧的cache示例文件
This commit is contained in:
parent
cfa9613da6
commit
b4fd5492ed
@ -1,293 +0,0 @@
|
||||
"""
|
||||
缓存模块使用示例 - Phase 1
|
||||
|
||||
演示如何在实际场景中使用缓存管理器
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
|
||||
from cache.cache_manager import CacheManager
|
||||
from cache.market_data_cache import MarketDataCache
|
||||
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(
|
||||
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MockDBManager:
|
||||
"""模拟数据库管理器"""
|
||||
|
||||
def get_klines(self, symbols, start_date, end_date, period):
|
||||
"""返回模拟K线数据"""
|
||||
logger.info(
|
||||
f"Loading klines from DB: {symbols[0]}, {start_date} to {end_date}, period={period}"
|
||||
)
|
||||
|
||||
# 生成模拟数据
|
||||
date_range = pd.date_range(start=start_date, end=end_date, freq="1D")
|
||||
data = {
|
||||
"open": [100.0 + i * 0.5 for i in range(len(date_range))],
|
||||
"high": [101.0 + i * 0.5 for i in range(len(date_range))],
|
||||
"low": [99.0 + i * 0.5 for i in range(len(date_range))],
|
||||
"close": [100.5 + i * 0.5 for i in range(len(date_range))],
|
||||
"volume": [1000000 + i * 1000 for i in range(len(date_range))],
|
||||
}
|
||||
df = pd.DataFrame(data, index=date_range)
|
||||
return df
|
||||
|
||||
|
||||
def example_01_basic_usage():
|
||||
"""示例1:基本使用"""
|
||||
print("\n" + "=" * 60)
|
||||
print("示例1:基本使用 - 缓存初始化、存取、统计")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. 初始化配置
|
||||
config = {
|
||||
"cache": {
|
||||
"enabled": True,
|
||||
"mode": "static",
|
||||
"max_memory_mb": 1024,
|
||||
"preload": {
|
||||
"enabled": False # 暂不预加载
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
db_manager = MockDBManager()
|
||||
cache_manager = CacheManager(config, db_manager)
|
||||
|
||||
# 2. 手动设置缓存
|
||||
print("\n步骤1: 设置缓存数据")
|
||||
test_data = {
|
||||
"klines": pd.DataFrame(
|
||||
{
|
||||
"open": [100, 101, 102],
|
||||
"high": [101, 102, 103],
|
||||
"low": [99, 100, 101],
|
||||
"close": [100.5, 101.5, 102.5],
|
||||
"volume": [1000000, 1100000, 1200000],
|
||||
},
|
||||
index=pd.date_range("2025-01-01", periods=3, freq="1D"),
|
||||
)
|
||||
}
|
||||
cache_manager.set("159915.SZ", "1d", test_data)
|
||||
print("✓ 缓存已设置: 159915.SZ_1d")
|
||||
|
||||
# 3. 从缓存读取
|
||||
print("\n步骤2: 从缓存读取数据")
|
||||
klines = cache_manager.get("159915.SZ", "1d")
|
||||
if klines is not None:
|
||||
print(f"✓ 读取成功,共 {len(klines)} 条记录")
|
||||
print(klines)
|
||||
|
||||
# 4. 查看统计信息
|
||||
print("\n步骤3: 查看缓存统计")
|
||||
stats = cache_manager.get_stats()
|
||||
print(f"缓存大小: {stats['size']} 项")
|
||||
print(f"内存占用: {stats['memory_mb']:.2f} MB")
|
||||
print(f"命中率: {stats['hit_rate']:.1%}")
|
||||
print(f"总请求数: {stats['total_requests']}")
|
||||
|
||||
|
||||
def example_02_preload():
|
||||
"""示例2:预加载功能"""
|
||||
print("\n" + "=" * 60)
|
||||
print("示例2:预加载功能 - 系统启动时批量加载数据")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. 配置预加载
|
||||
config = {
|
||||
"cache": {
|
||||
"enabled": True,
|
||||
"mode": "static",
|
||||
"max_memory_mb": 1024,
|
||||
"preload": {"enabled": True, "time_range": "1M", "periods": ["1d"]},
|
||||
}
|
||||
}
|
||||
|
||||
db_manager = MockDBManager()
|
||||
cache_manager = CacheManager(config, db_manager)
|
||||
|
||||
# 2. 执行预加载
|
||||
print("\n步骤1: 执行预加载")
|
||||
symbols = ["159915.SZ", "601658.SH", "000001.SZ"]
|
||||
cache_manager.preload(symbols)
|
||||
|
||||
# 3. 验证预加载结果
|
||||
print("\n步骤2: 验证预加载结果")
|
||||
stats = cache_manager.get_stats()
|
||||
print(f"✓ 预加载完成,缓存 {stats['size']} 项")
|
||||
print(f"✓ 内存占用: {stats['memory_mb']:.2f} MB")
|
||||
|
||||
# 4. 测试缓存命中
|
||||
print("\n步骤3: 测试缓存命中")
|
||||
klines = cache_manager.get("159915.SZ", "1d")
|
||||
if klines is not None:
|
||||
print(f"✓ 命中缓存,数据量: {len(klines)} 条")
|
||||
|
||||
# 5. 查看最终统计
|
||||
stats = cache_manager.get_stats()
|
||||
print("\n最终统计:")
|
||||
print(f" 命中次数: {stats['hit_count']}")
|
||||
print(f" 未命中次数: {stats['miss_count']}")
|
||||
print(f" 命中率: {stats['hit_rate']:.1%}")
|
||||
|
||||
|
||||
def example_03_time_range_query():
|
||||
"""示例3:时间范围查询"""
|
||||
print("\n" + "=" * 60)
|
||||
print("示例3:时间范围查询 - 按日期范围查询数据")
|
||||
print("=" * 60)
|
||||
|
||||
config = {
|
||||
"cache": {"enabled": True, "mode": "static", "preload": {"enabled": False}}
|
||||
}
|
||||
|
||||
db_manager = MockDBManager()
|
||||
cache_manager = CacheManager(config, db_manager)
|
||||
|
||||
# 1. 准备数据(10天)
|
||||
print("\n步骤1: 设置10天的K线数据")
|
||||
date_range = pd.date_range("2025-01-01", periods=10, freq="1D")
|
||||
test_data = {
|
||||
"klines": pd.DataFrame(
|
||||
{"close": [100 + i for i in range(10)]}, index=date_range
|
||||
)
|
||||
}
|
||||
cache_manager.set("159915.SZ", "1d", test_data)
|
||||
print("✓ 缓存已设置: 2025-01-01 到 2025-01-10")
|
||||
|
||||
# 2. 查询全部数据
|
||||
print("\n步骤2: 查询全部数据")
|
||||
all_data = cache_manager.get("159915.SZ", "1d")
|
||||
if all_data is not None:
|
||||
print(f"✓ 全部数据: {len(all_data)} 条")
|
||||
|
||||
# 3. 查询部分时间范围
|
||||
print("\n步骤3: 查询 2025-01-03 到 2025-01-07")
|
||||
start = datetime(2025, 1, 3)
|
||||
end = datetime(2025, 1, 7)
|
||||
partial_data = cache_manager.get("159915.SZ", "1d", start=start, end=end)
|
||||
if partial_data is not None:
|
||||
print(f"✓ 查询结果: {len(partial_data)} 条")
|
||||
print(partial_data)
|
||||
|
||||
|
||||
def example_04_invalidate():
|
||||
"""示例4:缓存失效"""
|
||||
print("\n" + "=" * 60)
|
||||
print("示例4:缓存失效 - 清除缓存数据")
|
||||
print("=" * 60)
|
||||
|
||||
config = {
|
||||
"cache": {"enabled": True, "mode": "static", "preload": {"enabled": False}}
|
||||
}
|
||||
|
||||
db_manager = MockDBManager()
|
||||
cache_manager = CacheManager(config, db_manager)
|
||||
|
||||
# 1. 设置多个缓存
|
||||
print("\n步骤1: 设置多个缓存项")
|
||||
test_data = {"klines": pd.DataFrame({"close": [100]}, index=[datetime(2025, 1, 1)])}
|
||||
cache_manager.set("159915.SZ", "1d", test_data)
|
||||
cache_manager.set("159915.SZ", "1m", test_data)
|
||||
cache_manager.set("601658.SH", "1d", test_data)
|
||||
print(f"✓ 设置了 {cache_manager.get_stats()['size']} 个缓存项")
|
||||
|
||||
# 2. 失效特定缓存
|
||||
print("\n步骤2: 失效 159915.SZ_1d")
|
||||
cache_manager.invalidate("159915.SZ", "1d")
|
||||
print(f"✓ 剩余 {cache_manager.get_stats()['size']} 个缓存项")
|
||||
|
||||
# 3. 失效某个标的所有周期
|
||||
print("\n步骤3: 失效 159915.SZ 所有周期")
|
||||
cache_manager.invalidate("159915.SZ")
|
||||
print(f"✓ 剩余 {cache_manager.get_stats()['size']} 个缓存项")
|
||||
|
||||
# 4. 清空全部缓存
|
||||
print("\n步骤4: 清空全部缓存")
|
||||
cache_manager.invalidate()
|
||||
print(f"✓ 剩余 {cache_manager.get_stats()['size']} 个缓存项")
|
||||
|
||||
|
||||
def example_05_market_data_cache():
|
||||
"""示例5:MarketDataCache使用"""
|
||||
print("\n" + "=" * 60)
|
||||
print("示例5:MarketDataCache - 市场数据专用缓存")
|
||||
print("=" * 60)
|
||||
|
||||
config = {
|
||||
"cache": {"enabled": True, "mode": "static", "preload": {"enabled": False}}
|
||||
}
|
||||
|
||||
db_manager = MockDBManager()
|
||||
cache_manager = CacheManager(config, db_manager)
|
||||
market_cache = MarketDataCache(cache_manager)
|
||||
|
||||
# 1. 设置K线和指标数据
|
||||
print("\n步骤1: 设置K线和指标数据")
|
||||
date_range = pd.date_range("2025-01-01", periods=5, freq="1D")
|
||||
test_data = {
|
||||
"klines": pd.DataFrame({"close": [100, 101, 102, 103, 104]}, index=date_range),
|
||||
"macd": pd.DataFrame(
|
||||
{
|
||||
"dif": [0.5, 0.6, 0.7, 0.8, 0.9],
|
||||
"dea": [0.4, 0.5, 0.6, 0.7, 0.8],
|
||||
"macd": [0.1, 0.1, 0.1, 0.1, 0.1],
|
||||
},
|
||||
index=date_range,
|
||||
),
|
||||
}
|
||||
cache_manager.set("159915.SZ", "1d", test_data)
|
||||
print("✓ K线和MACD指标已缓存")
|
||||
|
||||
# 2. 获取K线
|
||||
print("\n步骤2: 获取K线数据")
|
||||
klines = market_cache.get_klines("159915.SZ", "1d")
|
||||
if klines is not None:
|
||||
print(f"✓ K线数据: {len(klines)} 条")
|
||||
print(klines)
|
||||
|
||||
# 3. 获取指标
|
||||
print("\n步骤3: 获取MACD指标")
|
||||
macd = market_cache.get_indicator("159915.SZ", "1d", "macd")
|
||||
if macd is not None:
|
||||
print(f"✓ MACD数据: {len(macd)} 条")
|
||||
print(macd)
|
||||
|
||||
|
||||
def main():
|
||||
"""运行所有示例"""
|
||||
print("\n" + "=" * 60)
|
||||
print("缓存模块使用示例 - Phase 1")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
example_01_basic_usage()
|
||||
example_02_preload()
|
||||
example_03_time_range_query()
|
||||
example_04_invalidate()
|
||||
example_05_market_data_cache()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✓ 所有示例运行完成!")
|
||||
print("=" * 60)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"示例运行失败: {e}", exc_info=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -9,7 +9,7 @@ import os
|
||||
import io
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from PyQt6.QtWidgets import (
|
||||
QApplication,
|
||||
@ -64,65 +64,13 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
self.setParent(parent)
|
||||
|
||||
# 存储完整数据
|
||||
self.full_data = None
|
||||
self.full_data: Any = None # DataFrame类型
|
||||
self.current_start = 0 # 当前显示起始位置
|
||||
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._load_indicator_config()
|
||||
|
||||
# 创建专业黑色主题样式(红涨绿跌)
|
||||
self.style = mpf.make_mpf_style(
|
||||
@ -158,15 +106,72 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
self._resize_timer = None
|
||||
|
||||
# 鼠标悬停显示数据
|
||||
self.current_display_data = None # 当前显示的数据
|
||||
self.current_macd_data = None # MACD数据
|
||||
self.current_rsi_data = None # RSI数据
|
||||
self.crosshair_vlines = [] # 十字光标垂直线列表(多个子图)
|
||||
self.info_text = None # 信息文本
|
||||
self.current_display_data: Any = None # 当前显示的数据(DataFrame)
|
||||
self.current_macd_data: Any = None # MACD数据(DataFrame)
|
||||
self.current_rsi_data: Any = None # RSI数据(DataFrame)
|
||||
self.crosshair_vlines: list = [] # 十字光标垂直线列表(多个子图)
|
||||
self.info_text: Any = None # 信息文本
|
||||
|
||||
# 连接鼠标移动事件
|
||||
self.mpl_connect("motion_notify_event", self.on_mouse_move)
|
||||
|
||||
def _load_indicator_config(self):
|
||||
"""加载指标配置参数"""
|
||||
try:
|
||||
config = Config("configs/global.yaml")
|
||||
indicators_config = config.get("indicators")
|
||||
|
||||
if not indicators_config:
|
||||
raise ValueError("配置文件中未找到 'indicators' 配置项")
|
||||
|
||||
# 加载MACD参数
|
||||
self._load_macd_config(indicators_config)
|
||||
# 加载RSI参数
|
||||
self._load_rsi_config(indicators_config)
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ 配置文件读取失败: {e}")
|
||||
print("请检查 configs/global.yaml 文件中的 indicators 配置项")
|
||||
sys.exit(1)
|
||||
|
||||
def _load_macd_config(self, indicators_config):
|
||||
"""加载MACD配置"""
|
||||
macd_config = indicators_config.get("macd")
|
||||
if not macd_config:
|
||||
raise ValueError("配置文件中未找到 'indicators.macd' 配置项")
|
||||
|
||||
required_keys = ["fast_period", "slow_period", "signal_period"]
|
||||
for key in required_keys:
|
||||
if key not in macd_config:
|
||||
raise ValueError(f"配置文件中未找到 'indicators.macd.{key}'")
|
||||
|
||||
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}"
|
||||
)
|
||||
|
||||
def _load_rsi_config(self, indicators_config):
|
||||
"""加载RSI配置"""
|
||||
rsi_config = indicators_config.get("rsi")
|
||||
if not rsi_config:
|
||||
raise ValueError("配置文件中未找到 'indicators.rsi' 配置项")
|
||||
|
||||
required_keys = ["fast", "mid", "slow"]
|
||||
for key in required_keys:
|
||||
if key not in rsi_config:
|
||||
raise ValueError(f"配置文件中未找到 'indicators.rsi.{key}'")
|
||||
|
||||
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}"
|
||||
)
|
||||
|
||||
def resizeEvent(self, event):
|
||||
"""处理窗口缩放事件 - 延迟重绘避免崩溃"""
|
||||
super().resizeEvent(event)
|
||||
@ -186,51 +191,8 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
# 获取鼠标位置对应的数据索引
|
||||
x_index = int(round(event.xdata))
|
||||
if 0 <= x_index < len(self.current_display_data):
|
||||
# 获取该K线的数据
|
||||
data_row = self.current_display_data.iloc[x_index]
|
||||
|
||||
# 获取时间信息(从_original_index列)
|
||||
if "_original_index" in data_row:
|
||||
time_value = data_row["_original_index"]
|
||||
date_str = (
|
||||
time_value.strftime("%Y-%m-%d %H:%M")
|
||||
if hasattr(time_value, "strftime")
|
||||
else str(time_value)
|
||||
)
|
||||
else:
|
||||
date_str = f"Index: {x_index}"
|
||||
|
||||
# 构建显示文本 - OHLC
|
||||
info_text = (
|
||||
f"{date_str}\n"
|
||||
f"O: {data_row['open']:.2f} H: {data_row['high']:.2f}\n"
|
||||
f"L: {data_row['low']:.2f} C: {data_row['close']:.2f}\n"
|
||||
f"Vol: {data_row['volume']:.0f}"
|
||||
)
|
||||
|
||||
# 添加MACD数据
|
||||
if self.current_macd_data is not None and x_index < len(
|
||||
self.current_macd_data
|
||||
):
|
||||
macd_row = self.current_macd_data.iloc[x_index]
|
||||
info_text += (
|
||||
f"\n\nMACD\n"
|
||||
f"DIF: {macd_row['dif']:.3f}\n"
|
||||
f"DEA: {macd_row['dea']:.3f}\n"
|
||||
f"Hist: {macd_row['histogram']:.3f}"
|
||||
)
|
||||
|
||||
# 添加RSI数据
|
||||
if self.current_rsi_data is not None and x_index < len(
|
||||
self.current_rsi_data
|
||||
):
|
||||
rsi_row = self.current_rsi_data.iloc[x_index]
|
||||
info_text += (
|
||||
f"\n\nRSI\n"
|
||||
f"RSI6: {rsi_row['rsi6']:.1f}\n"
|
||||
f"RSI12: {rsi_row['rsi12']:.1f}\n"
|
||||
f"RSI24: {rsi_row['rsi24']:.1f}"
|
||||
)
|
||||
# 构建信息文本
|
||||
info_text = self._build_hover_info(x_index)
|
||||
|
||||
# 清除旧的十字光标和文本
|
||||
for line in self.crosshair_vlines:
|
||||
@ -276,71 +238,140 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
except Exception:
|
||||
pass # 忽略鼠标移动时的错误
|
||||
|
||||
def _build_hover_info(self, x_index):
|
||||
"""构建鼠标悬停时的信息文本"""
|
||||
if self.current_display_data is None:
|
||||
return ""
|
||||
data_row = self.current_display_data.iloc[x_index]
|
||||
|
||||
# 获取时间信息
|
||||
if "_original_index" in data_row:
|
||||
time_value = data_row["_original_index"]
|
||||
date_str = (
|
||||
time_value.strftime("%Y-%m-%d %H:%M")
|
||||
if hasattr(time_value, "strftime")
|
||||
else str(time_value)
|
||||
)
|
||||
else:
|
||||
date_str = f"Index: {x_index}"
|
||||
|
||||
# OHLC信息
|
||||
info_text = (
|
||||
f"{date_str}\n"
|
||||
f"O: {data_row['open']:.2f} H: {data_row['high']:.2f}\n"
|
||||
f"L: {data_row['low']:.2f} C: {data_row['close']:.2f}\n"
|
||||
f"Vol: {data_row['volume']:.0f}"
|
||||
)
|
||||
|
||||
# 添加MACD数据
|
||||
if self.current_macd_data is not None and x_index < len(self.current_macd_data):
|
||||
macd_row = self.current_macd_data.iloc[x_index]
|
||||
info_text += (
|
||||
f"\n\nMACD\n"
|
||||
f"DIF: {macd_row['dif']:.3f}\n"
|
||||
f"DEA: {macd_row['dea']:.3f}\n"
|
||||
f"Hist: {macd_row['histogram']:.3f}"
|
||||
)
|
||||
|
||||
# 添加RSI数据
|
||||
if self.current_rsi_data is not None and x_index < len(self.current_rsi_data):
|
||||
rsi_row = self.current_rsi_data.iloc[x_index]
|
||||
info_text += (
|
||||
f"\n\nRSI\n"
|
||||
f"RSI6: {rsi_row['rsi6']:.1f}\n"
|
||||
f"RSI12: {rsi_row['rsi12']:.1f}\n"
|
||||
f"RSI24: {rsi_row['rsi24']:.1f}"
|
||||
)
|
||||
|
||||
return info_text
|
||||
|
||||
def keyPressEvent(self, event):
|
||||
"""处理键盘事件"""
|
||||
if self.full_data is None or len(self.full_data) == 0:
|
||||
return
|
||||
|
||||
step = max(1, self.display_count // 10) # 每次移动10%
|
||||
total_len = len(self.full_data)
|
||||
key = event.key()
|
||||
if key == Qt.Key.Key_Left:
|
||||
self._handle_scroll_left()
|
||||
elif key == Qt.Key.Key_Right:
|
||||
self._handle_scroll_right()
|
||||
elif key == Qt.Key.Key_Up:
|
||||
self._handle_zoom_in()
|
||||
elif key == Qt.Key.Key_Down:
|
||||
self._handle_zoom_out()
|
||||
elif key == Qt.Key.Key_Home:
|
||||
self._handle_goto_start()
|
||||
elif key == Qt.Key.Key_End:
|
||||
self._handle_goto_end()
|
||||
|
||||
if event.key() == Qt.Key.Key_Left:
|
||||
# 左移
|
||||
def _handle_scroll_left(self):
|
||||
"""向左滚动"""
|
||||
if self.full_data is None:
|
||||
return
|
||||
step = max(1, self.display_count // 10)
|
||||
total_len = len(self.full_data)
|
||||
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
|
||||
)
|
||||
self.current_end = min(total_len, self.current_start + self.display_count)
|
||||
self.update_display()
|
||||
|
||||
elif event.key() == Qt.Key.Key_Right:
|
||||
# 右移
|
||||
def _handle_scroll_right(self):
|
||||
"""向右滚动"""
|
||||
if self.full_data is None:
|
||||
return
|
||||
step = max(1, self.display_count // 10)
|
||||
total_len = len(self.full_data)
|
||||
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
|
||||
)
|
||||
self.current_end = min(total_len, self.current_start + self.display_count)
|
||||
self.update_display()
|
||||
|
||||
elif event.key() == Qt.Key.Key_Up:
|
||||
# 放大(显示更少数据)
|
||||
def _handle_zoom_in(self):
|
||||
"""放大显示(显示更少数据)"""
|
||||
if self.full_data is None:
|
||||
return
|
||||
total_len = len(self.full_data)
|
||||
old_count = self.display_count
|
||||
self.display_count = max(5, self.display_count - 5) # 每次减少5条
|
||||
self.display_count = max(5, self.display_count - 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
|
||||
)
|
||||
self.update_display()
|
||||
self._recenter_view(total_len)
|
||||
|
||||
elif event.key() == Qt.Key.Key_Down:
|
||||
# 缩小(显示更多数据)
|
||||
def _handle_zoom_out(self):
|
||||
"""缩小显示(显示更多数据)"""
|
||||
if self.full_data is None:
|
||||
return
|
||||
total_len = len(self.full_data)
|
||||
old_count = self.display_count
|
||||
self.display_count = min(total_len, self.display_count + 5) # 每次增加5条
|
||||
self.display_count = min(total_len, self.display_count + 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
|
||||
)
|
||||
self.update_display()
|
||||
self._recenter_view(total_len)
|
||||
|
||||
elif event.key() == Qt.Key.Key_Home:
|
||||
# 回到最开始
|
||||
def _handle_goto_start(self):
|
||||
"""跳转到开始"""
|
||||
if self.full_data is None:
|
||||
return
|
||||
total_len = len(self.full_data)
|
||||
self.current_start = 0
|
||||
self.current_end = min(total_len, self.display_count)
|
||||
self.update_display()
|
||||
|
||||
elif event.key() == Qt.Key.Key_End:
|
||||
# 跳转到末尾
|
||||
def _handle_goto_end(self):
|
||||
"""跳转到结束"""
|
||||
if self.full_data is None:
|
||||
return
|
||||
total_len = len(self.full_data)
|
||||
self.current_start = max(0, total_len - self.display_count)
|
||||
self.current_end = total_len
|
||||
self.update_display()
|
||||
|
||||
def _recenter_view(self, total_len):
|
||||
"""缩放时重新居中视图"""
|
||||
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)
|
||||
self.update_display()
|
||||
|
||||
def update_display(self):
|
||||
"""更新显示区域"""
|
||||
if self.full_data is None:
|
||||
@ -509,28 +540,45 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
|
||||
self.draw()
|
||||
|
||||
def _plot_macd(self, df, ax):
|
||||
"""绘制MACD指标(使用配置文件参数)"""
|
||||
try:
|
||||
def _calculate_macd(self, df):
|
||||
"""计算MACD指标"""
|
||||
import pandas as pd
|
||||
|
||||
# 数据量检查
|
||||
min_length = self.macd_slow + self.macd_signal
|
||||
if len(df) < min_length:
|
||||
return
|
||||
|
||||
# 计算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=self.macd_signal, adjust=False).mean()
|
||||
histogram = macd - signal
|
||||
|
||||
# 保存MACD数据供鼠标悬停使用
|
||||
self.current_macd_data = pd.DataFrame(
|
||||
return pd.DataFrame(
|
||||
{"dif": macd, "dea": signal, "histogram": histogram}
|
||||
).reset_index(drop=True)
|
||||
|
||||
def _calculate_rsi(self, df, period):
|
||||
"""计算单个周期的RSI"""
|
||||
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))
|
||||
return rsi
|
||||
|
||||
def _plot_macd(self, df, ax):
|
||||
"""绘制MACD指标(使用配置文件参数)"""
|
||||
try:
|
||||
# 数据量检查
|
||||
min_length = self.macd_slow + self.macd_signal
|
||||
if len(df) < min_length:
|
||||
return
|
||||
|
||||
# 计算MACD
|
||||
self.current_macd_data = self._calculate_macd(df)
|
||||
|
||||
# 提取数据
|
||||
macd = self.current_macd_data["dif"]
|
||||
signal = self.current_macd_data["dea"]
|
||||
histogram = self.current_macd_data["histogram"]
|
||||
|
||||
# 绘制MACD柱状图(红涨绿跌)
|
||||
colors = ["#ff0000" if x >= 0 else "#00ff00" for x in histogram]
|
||||
ax.bar(
|
||||
@ -541,8 +589,8 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
width=0.8,
|
||||
)
|
||||
|
||||
# 绘制MACD和信号线
|
||||
ax.plot(macd.values, color="#00ffff", linewidth=1.5, label="MACD(DIF)")
|
||||
# 绘制MACD和信号线(快线白色,慢线黄色)
|
||||
ax.plot(macd.values, color="#ffffff", 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)
|
||||
@ -567,25 +615,18 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
if len(df) < self.rsi_slow + 1:
|
||||
return
|
||||
|
||||
rsi_data = {}
|
||||
# RSI颜色配置
|
||||
colors = {
|
||||
self.rsi_fast: "#ffff00",
|
||||
self.rsi_mid: "#00ffff",
|
||||
self.rsi_slow: "#ff00ff",
|
||||
self.rsi_fast: "#ffff00", # 快线:黄色
|
||||
self.rsi_mid: "#00ff00", # 中线:绿色
|
||||
self.rsi_slow: "#0000ff", # 慢线:蓝色
|
||||
}
|
||||
|
||||
# 计算RSI(使用配置文件参数)
|
||||
# 计算并绘制RSI
|
||||
rsi_data = {}
|
||||
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()
|
||||
rs = gain / loss
|
||||
rsi = 100 - (100 / (1 + rs))
|
||||
|
||||
# 保存RSI数据
|
||||
rsi = self._calculate_rsi(df, period)
|
||||
rsi_data[f"rsi{period}"] = rsi
|
||||
|
||||
# 绘制RSI线
|
||||
ax.plot(
|
||||
rsi.values,
|
||||
color=colors[period],
|
||||
@ -836,25 +877,7 @@ class SimpleKlineViewer(QMainWindow):
|
||||
if index < 0 or index >= len(self.period_list):
|
||||
return
|
||||
|
||||
tab_name, period = self.period_list[index]
|
||||
|
||||
# 调整日期范围
|
||||
today = datetime.now()
|
||||
if period == Period.DAY_1:
|
||||
# 日线:默认一年
|
||||
self.start_date_edit.setDate(QDate(2024, 1, 1))
|
||||
self.end_date_edit.setDate(QDate(today.year, today.month, today.day))
|
||||
else:
|
||||
# 分钟线:默认最近15天
|
||||
from datetime import timedelta
|
||||
|
||||
start_date = today - timedelta(days=15)
|
||||
self.start_date_edit.setDate(
|
||||
QDate(start_date.year, start_date.month, start_date.day)
|
||||
)
|
||||
self.end_date_edit.setDate(QDate(today.year, today.month, today.day))
|
||||
|
||||
# 自动加载数据
|
||||
# 切换Tab时直接加载数据,不修改时间范围
|
||||
self.load_current_tab_data()
|
||||
|
||||
def on_symbol_changed(self, symbol):
|
||||
|
||||
@ -140,7 +140,7 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
K线对象列表
|
||||
"""
|
||||
# 转换周期格式
|
||||
xt_period = self.PERIOD_MAPPING.get(period, period)
|
||||
xt_period = self.PERIOD_MAPPING[period]
|
||||
|
||||
# 转换日期格式为 YYYYMMDD
|
||||
start_str = start_date.strftime("%Y%m%d")
|
||||
|
||||
Loading…
Reference in New Issue
Block a user