QTrade/src/data_storage/mysql_storage.py

398 lines
12 KiB
Python
Raw Normal View History

"""
MySQL存储层实现
整合原KlineReader和IndicatorWriter的逻辑
"""
from datetime import datetime
from typing import Optional, Dict, Any
import pandas as pd
from sqlalchemy import text
from src.data_storage.storage_layer import StorageLayer
from src.database_manager import DatabaseManager
from src.database_manager.table_utils import (
get_kline_table_name,
get_indicator_table_name,
)
from src.core.config import Config
from src.core.logger import Logger
class MySQLStorage(StorageLayer):
"""
MySQL存储实现
整合了原来的KlineReader、IndicatorReader、IndicatorWriter逻辑
"""
def __init__(self, db_manager: Optional[DatabaseManager] = None):
"""
初始化MySQL存储
Args:
db_manager: 数据库管理器实例(可选)
"""
self.db_manager = db_manager if db_manager is not None else DatabaseManager()
# 从Config单例获取数据库名称
self.database = Config.get("database.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 # type: ignore
if end_date:
where_clauses.append("timestamp <= :end_date")
params["end_date"] = end_date # type: ignore
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: Dict[str, Any] = {"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)
batch_size = 100 # 每批100条
total_saved = 0
try:
# 获取要插入的时间范围
min_time = df_to_save["timestamp"].min()
max_time = df_to_save["timestamp"].max()
# 删除该时间范围内的旧数据
with engine.begin() as conn:
delete_sql = text(
f"""
DELETE FROM {table_name}
WHERE symbol = :symbol
AND timestamp >= :min_time
AND timestamp <= :max_time
"""
)
result = conn.execute(
delete_sql,
{"symbol": symbol, "min_time": min_time, "max_time": max_time},
)
deleted_count = result.rowcount
if deleted_count > 0:
Logger.info(
f"Deleted {deleted_count} old records for {symbol}_{period} in range {min_time} ~ {max_time}"
)
# 分批保存新数据
with engine.begin() as conn:
for i in range(0, len(df_to_save), batch_size):
batch = df_to_save.iloc[i : i + batch_size]
batch.to_sql(
table_name,
conn,
if_exists="append",
index=False,
)
total_saved += len(batch)
if len(df_to_save) > batch_size:
Logger.debug(
f"Saved batch {i // batch_size + 1}: {len(batch)} records"
)
finally:
engine.dispose()
Logger.info(f"Saved {total_saved} klines: {symbol}_{period}")
return total_saved
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]
print(f"[DEBUG] 准备保存 {len(df)} 条记录到 {table_name}")
print(
f"[DEBUG] DataFrame shape: {df.shape}, columns: {df.columns.tolist()}"
)
print(f"[DEBUG] 前3行:\n{df.head(3)}")
# 保存到数据库
engine = self.db_manager._create_db_engine(self.database)
try:
with engine.begin() as conn:
result = df.to_sql(
table_name,
conn,
if_exists="append",
index=False,
method="multi",
)
print(f"[DEBUG] to_sql返回值: {result}")
print("[DEBUG] 事务已提交")
finally:
engine.dispose()
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线数据是否存在且完整
检查逻辑:
1. 查询数据库中该标的在指定时间范围内的实际数据范围
2. 如果数据库的时间范围完全覆盖请求的时间范围,则认为数据存在
3. 否则认为数据不存在或不完整,需要下载
"""
try:
# 获取数据库中实际的数据时间范围
date_range = self.get_date_range(symbol, period)
if date_range is None:
# 数据库中没有任何数据
Logger.debug(f"No data in DB for {symbol}_{period}")
return False
db_start, db_end = date_range
# 检查数据库的时间范围是否覆盖请求的时间范围
if db_start <= start_date and db_end >= end_date:
Logger.debug(
f"Data exists: {symbol}_{period} DB[{db_start.date()}~{db_end.date()}] "
f"covers requested[{start_date.date()}~{end_date.date()}]"
)
return True
else:
Logger.debug(
f"Data incomplete: {symbol}_{period} DB[{db_start.date()}~{db_end.date()}] "
f"does not cover requested[{start_date.date()}~{end_date.date()}]"
)
return False
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")