feat: 修复数据下载和指标计算功能,修复所有pylance类型错误
- 修复 download_result 字典 key 匹配问题(symbol_period 格式) - 添加 XtQuant 连接关闭逻辑(__del__ 方法) - 修复所有相对导入错误(改为绝对导入 from src.) - 在 main.py 添加指标计算和保存功能 - 修复所有 pylance 类型错误: * 统一支持 Config 对象和 Dict 类型 * 移除未使用的导入 * 添加正确的类型注解 * 修复 SQLAlchemy params 类型问题 - 数据下载测试成功:K线 + 4种指标(MACD/KDJ/BOLL/RSI)
This commit is contained in:
parent
cbd3d183e7
commit
b01563758a
7
src/cache/cache_manager.py
vendored
7
src/cache/cache_manager.py
vendored
@ -6,11 +6,12 @@
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Dict, List, Optional, Any
|
||||
from typing import Dict, List, Optional, Any, Union
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from src.indicator_calculator.indicator_manager import IndicatorManager
|
||||
from src.data_storage.storage_layer import StorageLayer
|
||||
from src.core.config import Config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@ -28,7 +29,7 @@ class CacheManager:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: dict,
|
||||
config: Union[dict, Config],
|
||||
storage: StorageLayer,
|
||||
indicator_calc: Optional[IndicatorManager] = None,
|
||||
):
|
||||
@ -36,7 +37,7 @@ class CacheManager:
|
||||
初始化缓存管理器
|
||||
|
||||
Args:
|
||||
config: 配置字典,包含cache相关配置
|
||||
config: 配置字典或Config对象,包含cache相关配置
|
||||
storage: 存储层实例
|
||||
indicator_calc: 指标计算器实例(可选,如不提供则自动创建)
|
||||
"""
|
||||
|
||||
@ -10,7 +10,8 @@ import pandas as pd
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from src.core import get_logger, get_config
|
||||
from src.core.logger import get_logger
|
||||
from src.core.config import get_config
|
||||
from src.core.models import Kline
|
||||
from src.database_manager import DatabaseManager, get_table_definition
|
||||
|
||||
@ -136,11 +137,11 @@ class BaseDataDownloader(ABC):
|
||||
db_manager.create_database(self.database)
|
||||
|
||||
# 确保对应周期的 klines 表存在
|
||||
from ...database_manager.table_utils import (
|
||||
from src.database_manager.table_utils import (
|
||||
get_kline_table_name,
|
||||
SUPPORTED_PERIODS,
|
||||
)
|
||||
from ...database_manager.table_schemas import create_kline_table_definition
|
||||
from src.database_manager.table_schemas import create_kline_table_definition
|
||||
|
||||
# 为所有支持的周期创建表(如果不存在)
|
||||
for period in SUPPORTED_PERIODS:
|
||||
@ -376,7 +377,7 @@ class BaseDataDownloader(ABC):
|
||||
saved_count = 0
|
||||
|
||||
# 使用动态表名
|
||||
from ...database_manager.table_utils import get_kline_table_name
|
||||
from src.database_manager.table_utils import get_kline_table_name
|
||||
|
||||
table_name = get_kline_table_name(period)
|
||||
|
||||
|
||||
@ -4,12 +4,13 @@
|
||||
协调数据下载、存储、增量更新
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Dict
|
||||
from typing import List, Optional, Dict, Union
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from src.data_storage.storage_layer import StorageLayer
|
||||
from src.data_downloader import DownloaderFactory
|
||||
from src.core.logger import get_logger
|
||||
from src.core.config import Config
|
||||
|
||||
logger = get_logger("DownloaderManager")
|
||||
|
||||
@ -34,18 +35,21 @@ class DownloaderManager:
|
||||
result = manager.update_to_latest(['000001', '600000'], ['1d'])
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict, storage: StorageLayer):
|
||||
def __init__(self, config: Union[Dict, Config], storage: StorageLayer):
|
||||
"""
|
||||
初始化下载管理器
|
||||
|
||||
Args:
|
||||
config: 配置字典
|
||||
config: 配置字典或Config对象
|
||||
storage: 存储层实例
|
||||
"""
|
||||
self.config = config
|
||||
self.storage = storage
|
||||
|
||||
# 获取下载器类型
|
||||
# 获取下载器类型(兼容Config对象和dict)
|
||||
if isinstance(config, Config):
|
||||
self.downloader_type = config.get("data_source.downloader", "xtquant")
|
||||
else:
|
||||
downloader_config = config.get("data_source", {})
|
||||
self.downloader_type = downloader_config.get("downloader", "xtquant")
|
||||
|
||||
@ -143,8 +147,8 @@ class DownloaderManager:
|
||||
for symbol in symbols_to_download:
|
||||
key = f"{symbol}_{period}"
|
||||
|
||||
if symbol in download_result and not download_result[symbol].empty:
|
||||
df = download_result[symbol]
|
||||
if key in download_result and not download_result[key].empty:
|
||||
df = download_result[key]
|
||||
|
||||
try:
|
||||
saved_count = self.storage.save_klines(symbol, period, df)
|
||||
|
||||
@ -68,6 +68,14 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
# 初始化 XtQuant
|
||||
self._init_xtquant(token, optimize_addresses)
|
||||
|
||||
def __del__(self):
|
||||
"""析构函数:关闭 XtQuant 连接"""
|
||||
try:
|
||||
xtdc.close()
|
||||
self.logger.debug("XtQuant 连接已关闭")
|
||||
except Exception as e:
|
||||
self.logger.debug(f"关闭 XtQuant 连接时出错: {e}")
|
||||
|
||||
def _init_xtquant(
|
||||
self, token: Optional[str], optimize_addresses: Optional[List[str]]
|
||||
):
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
提供简洁的API,自动处理缓存、存储、下载、计算
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional, List
|
||||
from typing import Dict, Optional, List, Union
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
|
||||
@ -12,6 +12,7 @@ from src.cache.cache_manager import CacheManager
|
||||
from src.data_storage.storage_layer import StorageLayer
|
||||
from src.data_downloader.downloader_manager import DownloaderManager
|
||||
from src.core.logger import get_logger
|
||||
from src.core.config import Config
|
||||
|
||||
logger = get_logger("DataService")
|
||||
|
||||
@ -27,7 +28,11 @@ class DataService:
|
||||
- 指标计算
|
||||
|
||||
示例:
|
||||
service = DataService(config, storage, cache)
|
||||
# 方式1: 从配置创建(推荐)
|
||||
service = DataService.from_config(config)
|
||||
|
||||
# 方式2: 手动注入依赖(高级用法)
|
||||
service = DataService(config, storage, cache, downloader)
|
||||
|
||||
# 获取K线(自动处理缓存)
|
||||
klines = service.get_klines('000001', '1d', start, end)
|
||||
@ -37,28 +42,67 @@ class DataService:
|
||||
|
||||
# 批量获取
|
||||
data = service.get_multiple(['000001', '600000'], '1d', start, end)
|
||||
|
||||
# 下载数据
|
||||
service.download_klines(['000001'], start, end, ['1d'])
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Dict,
|
||||
config: Union[Dict, Config],
|
||||
storage: StorageLayer,
|
||||
cache: CacheManager,
|
||||
downloader: Optional[DownloaderManager] = None,
|
||||
):
|
||||
"""
|
||||
初始化数据服务
|
||||
|
||||
Args:
|
||||
config: 配置字典
|
||||
config: 配置字典或Config对象
|
||||
storage: 存储层实例
|
||||
cache: 缓存管理器实例
|
||||
downloader: 下载器管理器实例(可选)
|
||||
"""
|
||||
self.config = config
|
||||
self.storage = storage
|
||||
self.cache = cache
|
||||
self.downloader = downloader
|
||||
|
||||
logger.info("DataService initialized")
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config: Union[Dict, Config]) -> "DataService":
|
||||
"""
|
||||
从配置创建DataService实例(工厂方法)
|
||||
|
||||
自动初始化所有依赖组件
|
||||
|
||||
Args:
|
||||
config: 配置字典或Config对象
|
||||
|
||||
Returns:
|
||||
DataService实例
|
||||
|
||||
Example:
|
||||
config = Config()
|
||||
config.load_with_global("configs/backtest.yaml")
|
||||
service = DataService.from_config(config)
|
||||
"""
|
||||
from src.data_storage.mysql_storage import MySQLStorage
|
||||
|
||||
# 初始化存储层(MySQLStorage现在接受Union[Dict, Config])
|
||||
storage = MySQLStorage(config)
|
||||
|
||||
# 初始化缓存管理器(CacheManager现在也支持Union[Dict, Config])
|
||||
cache = CacheManager(config, storage)
|
||||
|
||||
# 初始化下载器管理器
|
||||
downloader = DownloaderManager(config, storage)
|
||||
|
||||
logger.info("DataService created from config")
|
||||
|
||||
return cls(config, storage, cache, downloader)
|
||||
|
||||
# ========== K线数据 ==========
|
||||
|
||||
def get_klines(
|
||||
@ -118,6 +162,34 @@ class DataService:
|
||||
logger.debug(f"Loaded {len(result)}/{len(symbols)} symbols")
|
||||
return result
|
||||
|
||||
def download_klines(
|
||||
self,
|
||||
symbols: List[str],
|
||||
start_date: datetime,
|
||||
end_date: datetime,
|
||||
periods: List[str],
|
||||
) -> None:
|
||||
"""
|
||||
下载K线数据
|
||||
|
||||
Args:
|
||||
symbols: 标的代码列表
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
periods: 周期列表(如['1d', '1h'])
|
||||
"""
|
||||
if self.downloader is None:
|
||||
raise RuntimeError(
|
||||
"Downloader not initialized. Use DataService.from_config() to create instance with downloader."
|
||||
)
|
||||
|
||||
self.downloader.download_and_save(
|
||||
symbols=symbols,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
periods=periods,
|
||||
)
|
||||
|
||||
# ========== 技术指标 ==========
|
||||
|
||||
def get_indicator(
|
||||
|
||||
@ -5,7 +5,7 @@ MySQL存储层实现
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict
|
||||
from typing import Optional, Dict, Union, Any
|
||||
import pandas as pd
|
||||
from sqlalchemy import text
|
||||
|
||||
@ -16,6 +16,7 @@ from src.database_manager.table_utils import (
|
||||
get_indicator_table_name,
|
||||
)
|
||||
from src.core.logger import get_logger
|
||||
from src.core.config import Config
|
||||
|
||||
logger = get_logger("MySQLStorage")
|
||||
|
||||
@ -27,17 +28,26 @@ class MySQLStorage(StorageLayer):
|
||||
整合了原来的KlineReader、IndicatorReader、IndicatorWriter逻辑
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict, db_manager: Optional[DatabaseManager] = None):
|
||||
def __init__(
|
||||
self, config: Union[Dict, Config], db_manager: Optional[DatabaseManager] = None
|
||||
):
|
||||
"""
|
||||
初始化MySQL存储
|
||||
|
||||
Args:
|
||||
config: 配置字典
|
||||
config: 配置字典或Config对象
|
||||
db_manager: 数据库管理器实例(可选)
|
||||
"""
|
||||
self.config = config
|
||||
self.db_manager = db_manager if db_manager is not None else DatabaseManager()
|
||||
self.database = config.get("database", {}).get("database", "qtrade_backtest")
|
||||
|
||||
# 兼容 Config 对象和字典
|
||||
if isinstance(config, Config):
|
||||
self.database = config.get("database.database", "qtrade_backtest")
|
||||
else:
|
||||
self.database = config.get("database", {}).get(
|
||||
"database", "qtrade_backtest"
|
||||
)
|
||||
|
||||
logger.info(f"MySQLStorage initialized: database={self.database}")
|
||||
|
||||
@ -62,11 +72,11 @@ class MySQLStorage(StorageLayer):
|
||||
|
||||
if start_date:
|
||||
where_clauses.append("timestamp >= :start_date")
|
||||
params["start_date"] = start_date
|
||||
params["start_date"] = start_date # type: ignore
|
||||
|
||||
if end_date:
|
||||
where_clauses.append("timestamp <= :end_date")
|
||||
params["end_date"] = end_date
|
||||
params["end_date"] = end_date # type: ignore
|
||||
|
||||
where_clause = " AND ".join(where_clauses)
|
||||
|
||||
@ -120,7 +130,7 @@ class MySQLStorage(StorageLayer):
|
||||
|
||||
# 构建查询
|
||||
where_clauses = ["symbol = :symbol"]
|
||||
params = {"symbol": symbol}
|
||||
params: Dict[str, Any] = {"symbol": symbol}
|
||||
|
||||
if start_date:
|
||||
where_clauses.append("timestamp >= :start_date")
|
||||
|
||||
@ -5,10 +5,10 @@
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, List, Dict
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from ..core.logger import get_logger
|
||||
from src.core.logger import get_logger
|
||||
|
||||
logger = get_logger("StorageLayer")
|
||||
|
||||
|
||||
@ -24,7 +24,8 @@ from sqlalchemy.types import DECIMAL
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from ..core import get_logger, get_config
|
||||
from src.core.logger import get_logger
|
||||
from src.core.config import get_config
|
||||
|
||||
logger = get_logger("DatabaseManager")
|
||||
|
||||
|
||||
132
src/main.py
132
src/main.py
@ -16,14 +16,8 @@ if __name__ == "__main__":
|
||||
|
||||
from src.core.config import Config, set_config
|
||||
from src.core.logger import get_logger
|
||||
|
||||
# 注意:DataProvider已废弃,此文件待重构
|
||||
# TODO: 重构为使用 src.data.DataService
|
||||
try:
|
||||
from src.data_service import DataService as DataProvider
|
||||
except ImportError:
|
||||
DataProvider = None
|
||||
print("警告:DataProvider已被移除,请使用 src.data.DataService")
|
||||
from src.data_service import DataService
|
||||
from src.indicator_calculator.indicator_manager import IndicatorManager
|
||||
|
||||
logger = get_logger("Main")
|
||||
|
||||
@ -50,9 +44,15 @@ def download_data():
|
||||
logger.info(f" 数据周期: {', '.join(periods)}")
|
||||
|
||||
try:
|
||||
# 使用 DataProvider 下载数据
|
||||
with DataProvider() as provider:
|
||||
provider.download_klines(
|
||||
# 获取配置
|
||||
config = Config()
|
||||
config.load_with_global("configs/backtest.yaml")
|
||||
|
||||
# 创建数据服务(自动初始化所有依赖)
|
||||
service = DataService.from_config(config)
|
||||
|
||||
# 下载数据
|
||||
service.download_klines(
|
||||
symbols=symbols,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
@ -81,12 +81,18 @@ def verify_data():
|
||||
period = "1m"
|
||||
|
||||
try:
|
||||
with DataProvider() as provider:
|
||||
klines = provider.get_klines(symbols, start_date, end_date, period)
|
||||
# 获取配置
|
||||
config = Config()
|
||||
config.load_with_global("configs/backtest.yaml")
|
||||
|
||||
# 创建数据服务
|
||||
service = DataService.from_config(config)
|
||||
|
||||
# 验证数据
|
||||
logger.info("\n数据验证结果:")
|
||||
for symbol, df in klines.items():
|
||||
if df.empty:
|
||||
for symbol in symbols:
|
||||
df = service.get_klines(symbol, period, start_date, end_date)
|
||||
if df is None or df.empty:
|
||||
logger.warning(f" {symbol}: 无数据")
|
||||
else:
|
||||
logger.info(f" {symbol}: {len(df)} 条记录")
|
||||
@ -105,6 +111,99 @@ def verify_data():
|
||||
raise
|
||||
|
||||
|
||||
def calculate_indicators():
|
||||
"""计算并保存指标数据"""
|
||||
|
||||
logger.info("\n" + "=" * 80)
|
||||
logger.info("开始计算技术指标")
|
||||
logger.info("=" * 80)
|
||||
|
||||
symbols = ["601658.SH", "159915.SZ"]
|
||||
start_date = datetime(2025, 12, 1)
|
||||
end_date = datetime(2025, 12, 15)
|
||||
periods = ["1m", "1d"]
|
||||
|
||||
try:
|
||||
# 获取配置
|
||||
config = Config()
|
||||
config.load_with_global("configs/backtest.yaml")
|
||||
|
||||
# 创建数据服务
|
||||
service = DataService.from_config(config)
|
||||
|
||||
# 获取指标配置
|
||||
indicator_configs = config.get("indicators", {})
|
||||
enabled_indicators = indicator_configs.get("enabled_indicators", [])
|
||||
|
||||
if not enabled_indicators:
|
||||
logger.warning("未配置指标,跳过计算")
|
||||
return
|
||||
|
||||
# 为每个指标创建配置字典
|
||||
indicators_config = {}
|
||||
for ind_name in enabled_indicators:
|
||||
ind_config = indicator_configs.get(ind_name.lower(), {})
|
||||
indicators_config[ind_name.lower()] = ind_config
|
||||
|
||||
logger.info(f"\n配置的指标: {', '.join(enabled_indicators)}")
|
||||
|
||||
# 创建指标管理器
|
||||
indicator_manager = IndicatorManager(indicators_config)
|
||||
|
||||
# 为每个标的和周期计算指标
|
||||
total_saved = 0
|
||||
for symbol in symbols:
|
||||
for period in periods:
|
||||
logger.info(f"\n处理 {symbol} [{period}]...")
|
||||
|
||||
# 获取K线数据
|
||||
klines = service.get_klines(symbol, period, start_date, end_date)
|
||||
|
||||
if klines is None or klines.empty:
|
||||
logger.warning(f" {symbol} [{period}]: 无K线数据,跳过")
|
||||
continue
|
||||
|
||||
logger.info(f" 获取到 {len(klines)} 条K线数据")
|
||||
|
||||
# 计算所有指标
|
||||
df_with_indicators = indicator_manager.calculate(klines)
|
||||
|
||||
# 保存每个指标
|
||||
for ind_name in enabled_indicators:
|
||||
try:
|
||||
# 提取指标列
|
||||
indicator = indicator_manager.indicators.get(ind_name.lower())
|
||||
if not indicator:
|
||||
continue
|
||||
|
||||
indicator_cols = indicator.get_column_names()
|
||||
indicator_data = df_with_indicators[indicator_cols]
|
||||
|
||||
# 保存到数据库
|
||||
saved_count = service.storage.save_indicators(
|
||||
symbol=symbol,
|
||||
period=period,
|
||||
indicator_name=ind_name.lower(),
|
||||
data=indicator_data,
|
||||
)
|
||||
|
||||
total_saved += saved_count
|
||||
logger.info(
|
||||
f" ✓ {ind_name.upper()}: 保存 {saved_count} 条记录"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f" ✗ {ind_name.upper()}: 保存失败 - {e}")
|
||||
|
||||
logger.info("\n" + "=" * 80)
|
||||
logger.info(f" 指标计算完成!共保存 {total_saved} 条记录")
|
||||
logger.info("=" * 80)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"\n 指标计算失败: {e}", exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
|
||||
@ -131,6 +230,9 @@ def main():
|
||||
# 执行下载
|
||||
download_data()
|
||||
|
||||
# 计算指标
|
||||
calculate_indicators()
|
||||
|
||||
# 验证数据
|
||||
verify_data()
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user