""" MySQL存储层实现 整合原KlineReader和IndicatorWriter的逻辑 """ from datetime import datetime from typing import Optional, Dict import pandas as pd from sqlalchemy import text from .storage_layer import StorageLayer from ..database_manager import DatabaseManager from ..database_manager.table_utils import ( get_kline_table_name, get_indicator_table_name, ) from ..core.logger import get_logger logger = get_logger("MySQLStorage") class MySQLStorage(StorageLayer): """ MySQL存储实现 整合了原来的KlineReader、IndicatorReader、IndicatorWriter逻辑 """ def __init__(self, config: Dict, db_manager: Optional[DatabaseManager] = None): """ 初始化MySQL存储 Args: 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") logger.info(f"MySQLStorage initialized: database={self.database}") def load_klines( self, symbol: str, period: str, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, ) -> Optional[pd.DataFrame]: """ 从MySQL加载K线数据 整合自KlineReader.read() """ try: table_name = get_kline_table_name(period) # 构建查询 where_clauses = ["symbol = :symbol"] params = {"symbol": symbol} if start_date: where_clauses.append("timestamp >= :start_date") params["start_date"] = start_date if end_date: where_clauses.append("timestamp <= :end_date") params["end_date"] = end_date where_clause = " AND ".join(where_clauses) query = text( f""" SELECT timestamp, open, high, low, close, volume, amount FROM {table_name} WHERE {where_clause} ORDER BY timestamp """ ) engine = self.db_manager._create_db_engine(self.database) with engine.connect() as conn: df = pd.read_sql(query, conn, params=params) # type: ignore if df.empty: logger.debug(f"No klines found: {symbol}_{period}") return None # 转换时间列并设置索引 df["timestamp"] = pd.to_datetime(df["timestamp"]) df.set_index("timestamp", inplace=True) # 为兼容性保留timestamp列 df["timestamp"] = df.index logger.debug(f"Loaded {len(df)} klines: {symbol}_{period}") return df except Exception as e: logger.error(f"Failed to load klines {symbol}_{period}: {e}") return None def load_indicators( self, symbol: str, period: str, indicator_name: str, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, ) -> Optional[pd.DataFrame]: """ 从MySQL加载技术指标数据 整合自IndicatorReader.read() """ try: table_name = get_indicator_table_name(indicator_name, period) # 构建查询 where_clauses = ["symbol = :symbol"] params = {"symbol": symbol} if start_date: where_clauses.append("timestamp >= :start_date") params["start_date"] = start_date if end_date: where_clauses.append("timestamp <= :end_date") params["end_date"] = end_date where_clause = " AND ".join(where_clauses) query = text( f""" SELECT * FROM {table_name} WHERE {where_clause} ORDER BY timestamp """ ) engine = self.db_manager._create_db_engine(self.database) with engine.connect() as conn: df = pd.read_sql(query, conn, params=params) # type: ignore if df.empty: logger.debug(f"No indicators found: {symbol}_{period}_{indicator_name}") return None # 转换时间列并设置索引 df["timestamp"] = pd.to_datetime(df["timestamp"]) df.set_index("timestamp", inplace=True) # 移除symbol列(如果存在) if "symbol" in df.columns: df = df.drop(columns=["symbol"]) logger.debug( f"Loaded {len(df)} indicator records: {symbol}_{period}_{indicator_name}" ) return df except Exception as e: logger.error( f"Failed to load indicators {symbol}_{period}_{indicator_name}: {e}" ) return None def save_klines( self, symbol: str, period: str, data: pd.DataFrame, ) -> int: """ 保存K线数据到MySQL """ try: table_name = get_kline_table_name(period) # 准备数据 df = data.copy() df["symbol"] = symbol # 确保timestamp列存在 if "timestamp" not in df.columns: df["timestamp"] = df.index # 选择需要的列 columns = ["symbol", "timestamp", "open", "high", "low", "close", "volume"] if "amount" in df.columns: columns.append("amount") df_to_save = df[columns].copy() # 保存到数据库 engine = self.db_manager._create_db_engine(self.database) df_to_save.to_sql( table_name, engine, if_exists="append", index=False, method="multi", ) logger.info(f"Saved {len(df_to_save)} klines: {symbol}_{period}") return len(df_to_save) except Exception as e: logger.error(f"Failed to save klines {symbol}_{period}: {e}") return 0 def save_indicators( self, symbol: str, period: str, indicator_name: str, data: pd.DataFrame, ) -> int: """ 保存技术指标数据到MySQL 整合自IndicatorWriter.save() """ try: table_name = get_indicator_table_name(indicator_name, period) # 准备数据 df = data.copy() df["symbol"] = symbol # 确保timestamp列存在 if "timestamp" not in df.columns: df["timestamp"] = df.index # 移动symbol和timestamp到前面 cols = ["symbol", "timestamp"] + [ col for col in df.columns if col not in ["symbol", "timestamp"] ] df = df[cols] # 保存到数据库 engine = self.db_manager._create_db_engine(self.database) df.to_sql( table_name, engine, if_exists="append", index=False, method="multi", ) logger.info( f"Saved {len(df)} indicator records: {symbol}_{period}_{indicator_name}" ) return len(df) except Exception as e: logger.error( f"Failed to save indicators {symbol}_{period}_{indicator_name}: {e}" ) return 0 def exists( self, symbol: str, period: str, start_date: datetime, end_date: datetime, ) -> bool: """ 检查K线数据是否存在且完整 """ try: df = self.load_klines(symbol, period, start_date, end_date) if df is None or df.empty: return False # 简单检查:是否有数据 # TODO: 可以增强为检查数据完整性(期望的交易日数量) return True except Exception as e: logger.error(f"Failed to check existence {symbol}_{period}: {e}") return False def get_date_range( self, symbol: str, period: str, ) -> Optional[tuple[datetime, datetime]]: """ 获取某个标的的数据时间范围 """ try: table_name = get_kline_table_name(period) query = text( f""" SELECT MIN(timestamp) as min_date, MAX(timestamp) as max_date FROM {table_name} WHERE symbol = :symbol """ ) engine = self.db_manager._create_db_engine(self.database) with engine.connect() as conn: result = conn.execute(query, {"symbol": symbol}).fetchone() if result and result[0] and result[1]: return (result[0], result[1]) return None except Exception as e: logger.error(f"Failed to get date range {symbol}_{period}: {e}") return None def close(self): """关闭数据库连接""" if self.db_manager: self.db_manager.close() logger.debug("MySQLStorage closed")