QTrade/src/data_service/data_service.py

659 lines
21 KiB
Python
Raw Normal View History

"""
数据服务 - 统一的数据访问入口
提供简洁的API,自动处理缓存、存储、下载、计算
"""
from typing import Dict, Optional, List, Union
from datetime import datetime
import pandas as pd
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.data_validator.data_validator import DataValidator
from src.indicator_calculator.indicator_manager import IndicatorManager
from src.core.logger import get_logger
from src.core.config import Config
from src.core.constants import IndicatorType, KlineColumns, IndicatorColumns
logger = get_logger("DataService")
class DataService:
"""
数据服务 - 应用程序的统一数据入口
特性:
- 简洁的API
- 透明缓存
- 自动加载
- 指标计算
示例:
# 方式1: 从配置创建(推荐)
service = DataService.from_config(config)
# 方式2: 手动注入依赖(高级用法)
service = DataService(config, storage, cache, downloader)
# 获取K线(自动处理缓存)
klines = service.get_klines('000001', '1d', start, end)
# 获取指标(自动计算和缓存)
macd = service.get_indicator('000001', '1d', 'MACD')
# 批量获取
data = service.get_multiple(['000001', '600000'], '1d', start, end)
# 下载数据
service.download_klines(['000001'], start, end, ['1d'])
"""
def __init__(
self,
config: Union[Dict, Config],
storage: StorageLayer,
cache: CacheManager,
):
"""
初始化数据服务
Args:
config: 配置字典或Config对象
storage: 存储层实例
cache: 缓存管理器实例
"""
self.config = config
self.storage = storage
self.cache = cache
# 直接在DataService中初始化validator和downloader
self.validator = DataValidator(config if isinstance(config, dict) else None)
self.downloader = DownloaderManager(config, storage)
# 初始化指标计算器
indicator_configs = {}
if isinstance(config, Config):
indicators_section = config.get("indicators", {})
enabled_indicators = indicators_section.get("enabled_indicators", [])
# 只提取各指标的参数配置
for indicator_name in enabled_indicators:
if indicator_name in indicators_section:
indicator_configs[indicator_name] = indicators_section[
indicator_name
]
elif isinstance(config, dict):
indicators_section = config.get("indicators", {})
enabled_indicators = indicators_section.get("enabled_indicators", [])
# 只提取各指标的参数配置
for indicator_name in enabled_indicators:
if indicator_name in indicators_section:
indicator_configs[indicator_name] = indicators_section[
indicator_name
]
self.indicator_manager = IndicatorManager(indicator_configs)
logger.info(
"DataService initialized with validator, downloader and indicator_manager"
)
@classmethod
def from_config(cls, config: Union[Dict, Config]) -> "DataService":
"""
从配置创建 DataService 实例(工厂方法)
自动初始化所有依赖组件:storage、cache、validator、downloader
Args:
config: 配置对象或配置字典
Returns:
DataService 实例
Example:
config = Config()
config.load_with_global("configs/backtest.yaml")
service = DataService.from_config(config)
"""
# 导入MySQLStorage(避免循环导入)
from src.data_storage.mysql_storage import MySQLStorage
# 初始化 storage
storage = MySQLStorage(config)
# 初始化 cache
cache = CacheManager(config)
# 创建 DataService 实例
return cls(config, storage, cache)
# ========== K线数据 ==========
def get_klines(
self,
symbol: str,
period: str,
startdate: Optional[datetime] = None,
enddate: Optional[datetime] = None,
) -> Optional[pd.DataFrame]:
"""
获取K线数据(智能获取+自动补全)
流程:
1. 先从cache获取(纯缓存,不做检查)
2. validator检查缓存数据完整性
3. 如果不满足,从数据库加载
4. validator检查数据库数据完整性
5. 如果还不满足,触发下载
6. 下载完成后重新获取
Args:
symbol: 标的代码
period: 周期(如'1d', '1h')
startdate: 开始时间
enddate: 结束时间
Returns:
K线DataFrame或None
"""
# 参数检查:必须提供时间范围
if startdate is None or enddate is None:
logger.error(
f"Invalid parameters for {symbol} {period}: "
f"start={startdate}, end={enddate}. Both start and end must be provided."
)
return None
# ========== 步骤1: 检查缓存 ==========
cache_data = self.cache.get_klines(symbol, period)
if cache_data is not None and not cache_data.empty:
# validator检查缓存数据完整性
validation_result = self.validator.validate_completeness(
cache_data, startdate, enddate, period
)
if validation_result.passed:
logger.debug(f"Cache data is complete for {symbol} {period}")
# 返回时间切片
mask = (cache_data.index >= startdate) & (cache_data.index <= enddate)
return cache_data[mask]
else:
logger.info(
f"Cache data incomplete for {symbol} {period}: "
f"{validation_result.details.get('issues', [])}"
)
# ========== 步骤2: 从数据库加载 ==========
logger.debug(f"Loading from storage: {symbol} {period}")
db_data = self.storage.load_klines(symbol, period, startdate, enddate)
if db_data is not None and not db_data.empty:
# validator检查数据库数据完整性
validation_result = self.validator.validate_completeness(
db_data, startdate, enddate, period
)
if validation_result.passed:
# 数据完整,更新缓存并返回
self.cache.set_klines(symbol, period, {"klines": db_data})
logger.debug(f"DB data is complete, cached: {symbol} {period}")
mask = (db_data.index >= startdate) & (db_data.index <= enddate)
return db_data[mask]
else:
logger.info(
f"DB data incomplete for {symbol} {period}: "
f"{validation_result.details.get('issues', [])}"
)
# ========== 步骤3: 触发下载 ==========
logger.info(
f"Data incomplete/missing for {symbol} {period}, triggering download"
)
try:
# 下载数据
self.downloader.download_and_save(
symbols=[symbol],
start_date=startdate,
end_date=enddate,
periods=[period],
)
# 下载完成后重新获取
final_data = self.storage.load_klines(symbol, period, startdate, enddate)
if final_data is not None and not final_data.empty:
# 更新缓存
self.cache.set_klines(symbol, period, {"klines": final_data})
logger.info(
f"Downloaded and loaded {len(final_data)} records for {symbol} {period}"
)
# 重新计算和保存指标
self._recalculate_and_save_indicators(symbol, period, final_data)
mask = (final_data.index >= startdate) & (final_data.index <= enddate)
return final_data[mask]
else:
logger.warning(
f"Download completed but still no data for {symbol} {period}"
)
return None
except Exception as e:
logger.error(f"Failed to download data for {symbol} {period}: {e}")
return None
def get_multiple(
self,
symbols: List[str],
period: str,
start: Optional[datetime] = None,
end: Optional[datetime] = None,
) -> Dict[str, pd.DataFrame]:
"""
批量获取K线数据
Args:
symbols: 标的代码列表
period: 周期
start: 开始时间
end: 结束时间
Returns:
{symbol: DataFrame} 字典
"""
result = {}
for symbol in symbols:
klines = self.get_klines(symbol, period, start, end)
if klines is not None and not klines.empty:
result[symbol] = klines
else:
logger.warning(f"No klines for {symbol}_{period}")
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(
self,
symbol: str,
period: str,
indicator_name: str,
params: Optional[Dict] = None,
start: Optional[datetime] = None,
end: Optional[datetime] = None,
) -> Optional[pd.DataFrame]:
"""
获取技术指标数据
自动处理:
1. 检查指标缓存
2. 缓存未命中 → 获取K线 + 计算指标
3. 缓存计算结果
Args:
symbol: 标的代码
period: 周期
indicator_name: 指标名称(如'MACD', 'KDJ')
params: 指标参数
start: 开始时间
end: 结束时间
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:
# 缓存命中,返回时间切片
if start is not None or end is not None:
mask = pd.Series(True, index=indicator_data.index)
if start is not None:
mask &= indicator_data.index >= start
if end is not None:
mask &= indicator_data.index <= end
return indicator_data[mask]
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(
f"Indicator calculated and cached: {symbol}_{period}_{indicator_name}"
)
# 返回时间切片
if start is not None or end is not None:
mask = pd.Series(True, index=indicator_columns.index)
if start is not None:
mask &= indicator_columns.index >= start
if end is not None:
mask &= indicator_columns.index <= end
return indicator_columns[mask]
return indicator_columns
except Exception as e:
logger.error(f"Failed to calculate indicator {indicator_name}: {e}")
return None
def get_multiple_indicators(
self,
symbols: List[str],
period: str,
indicator_name: str,
params: Optional[Dict] = None,
start: Optional[datetime] = None,
end: Optional[datetime] = None,
) -> Dict[str, pd.DataFrame]:
"""
批量获取指标数据
Args:
symbols: 标的代码列表
period: 周期
indicator_name: 指标名称
params: 指标参数
start: 开始时间
end: 结束时间
Returns:
{symbol: DataFrame} 字典
"""
result = {}
for symbol in symbols:
indicator = self.get_indicator(
symbol, period, indicator_name, params, start, end
)
if indicator is not None and not indicator.empty:
result[symbol] = indicator
else:
logger.warning(f"No indicator {indicator_name} for {symbol}_{period}")
logger.debug(f"Loaded {len(result)}/{len(symbols)} indicators")
return result
# ========== 数据管理 ==========
def preload(self, symbols: List[str], periods: Optional[List[str]] = None):
"""
预加载数据到缓存
Args:
symbols: 标的列表
periods: 周期列表(None则使用配置)
"""
logger.warning(
"DataService.preload() is deprecated. "
"Data will be automatically cached when accessed via get_klines()."
)
def invalidate(self, symbol: Optional[str] = None, period: Optional[str] = None):
"""
失效缓存
Args:
symbol: 标的代码(None=全部)
period: 周期(None=该标的所有周期)
"""
# TODO: 实现缓存失效逻辑
logger.warning("Cache invalidation not implemented in simplified CacheManager")
def exists(
self,
symbol: str,
period: str,
start: datetime,
end: datetime,
) -> bool:
"""
检查数据是否存在
Args:
symbol: 标的代码
period: 周期
start: 开始时间
end: 结束时间
Returns:
True如果数据存在
"""
return self.storage.exists(symbol, period, start, end)
def get_date_range(
self, symbol: str, period: str
) -> Optional[tuple[datetime, datetime]]:
"""
获取数据时间范围
Args:
symbol: 标的代码
period: 周期
Returns:
(最早时间, 最晚时间) 或 None
"""
return self.storage.get_date_range(symbol, period)
# ========== 内部辅助方法 ==========
def _recalculate_and_save_indicators(
self, symbol: str, period: str, klines: pd.DataFrame
) -> None:
"""
重新计算并保存所有启用的指标
Args:
symbol: 标的代码
period: 周期
klines: K线数据
"""
enabled_indicators = self.indicator_manager.get_enabled_indicators()
if not enabled_indicators:
logger.debug(
f"No indicators enabled, skip calculation for {symbol}_{period}"
)
return
logger.info(
f"Recalculating {len(enabled_indicators)} indicators for {symbol}_{period}"
)
try:
# 计算所有指标
data_with_indicators = self.indicator_manager.calculate(klines)
# 逐个保存指标
for indicator_name in enabled_indicators:
try:
# 提取指标列
indicator_columns = self._get_indicator_columns(
data_with_indicators, indicator_name
)
if not indicator_columns.empty:
# 保存到存储
self.storage.save_indicators(
symbol, period, indicator_name, indicator_columns
)
# 更新缓存
self.cache.set_indicator(
symbol, period, indicator_name, indicator_columns
)
logger.debug(
f"Saved indicator: {symbol}_{period}_{indicator_name}"
)
else:
logger.warning(
f"No columns found for indicator: {indicator_name}"
)
except Exception as e:
logger.error(f"Failed to save indicator {indicator_name}: {e}")
continue
except Exception as e:
logger.error(f"Failed to calculate indicators: {e}")
def _get_indicator_columns(
self, df: pd.DataFrame, indicator_name: str
) -> pd.DataFrame:
"""
从DataFrame中提取指标相关的列(使用常量定义)
Args:
df: 包含指标数据的DataFrame
indicator_name: 指标名称(应该是小写,如macd, kdj, boll, rsi)
Returns:
只包含指标列的DataFrame
"""
# indicator_name应该已经是小写,直接使用
# 使用IndicatorColumns常量获取列名
expected_columns = IndicatorColumns.get_columns(indicator_name)
if not expected_columns:
logger.warning(f"Unknown indicator: {indicator_name}")
return pd.DataFrame()
# 只保留DataFrame中实际存在的列
existing_columns = [col for col in expected_columns if col in df.columns]
if not existing_columns:
logger.warning(
f"No columns found for indicator {indicator_name} in DataFrame. "
f"Expected: {expected_columns}, Available: {list(df.columns)}"
)
return pd.DataFrame()
return df[existing_columns]
# ========== 统计和诊断 ==========
def get_stats(self) -> Dict:
"""
获取统计信息
Returns:
统计信息字典
"""
cache_stats = self.cache.get_stats()
return {
"cache": cache_stats,
"service": {
"storage_type": type(self.storage).__name__,
},
}
def health_check(self) -> Dict[str, bool]:
"""
健康检查
Returns:
健康状态字典
"""
checks = {}
# 检查缓存
try:
stats = self.cache.get_stats()
checks["cache"] = stats["enabled"]
except Exception as e:
logger.error(f"Cache health check failed: {e}")
checks["cache"] = False
# 检查存储
try:
# 尝试获取一个标的的时间范围
checks["storage"] = True
except Exception as e:
logger.error(f"Storage health check failed: {e}")
checks["storage"] = False
checks["overall"] = all(checks.values())
return checks
# ========== 资源管理 ==========
def close(self):
"""关闭资源"""
self.storage.close()
logger.info("DataService closed")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return False