QTrade/src/data_process_model/stockdata_manager.py
cuizhan 6bb33b3720 优化时间格式配置和枚举命名
- 修改 TimeFrame 枚举:HOUR_1 -> MINUTE_60,保持命名一致性
- 更新时间格式支持 xtquant API 要求的 YYYYMMDDhhmmss 格式
- 添加时间格式化工具函数 format_time_for_xtquant()
- 完善实时行情订阅功能
- 更新所有相关引用和配置
2025-08-05 16:01:38 +08:00

475 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
股票数据管理器 - DataFrame ↔ 数据库转换层
负责将数据库中的数据转换为DataFrame格式,以及将DataFrame数据写入数据库
调用 database_manager.py 提供的底层功能
"""
import pandas as pd
import logging
from typing import Dict, List, Optional, Any
from decimal import Decimal
from datetime import datetime
# 导入底层依赖
from database_manager import get_database_manager
from stock_models import create_stock_kline_model
# 导入公共配置
from common import (
normalize_stock_code, get_table_name,
validate_kline_data, LOG_PREFIXES
)
logger = logging.getLogger(__name__)
class StockDataManager:
"""
股票数据管理器
职责:
1. 从数据库读取K线数据并转换为DataFrame
2. 将DataFrame格式的K线数据写入数据库
3. 提供数据查询、过滤、聚合等功能
4. 管理股票表的创建和维护
"""
def __init__(self):
"""初始化股票数据管理器"""
self.db_manager = get_database_manager()
self.model_cache = {} # 缓存已创建的模型类
# 确保数据库连接
if not self.db_manager.is_connected():
self.db_manager.connect()
logger.info(f"{LOG_PREFIXES['SUCCESS']} 股票数据管理器初始化完成")
# ================================ 模型管理 ================================
def get_stock_model(self, stock_code: str, period: str = "1d"):
"""
获取或创建股票K线模型类
Args:
stock_code: 股票代码
period: 时间周期
Returns:
股票K线模型类
"""
# 标准化股票代码
normalized_code = normalize_stock_code(stock_code)
model_key = f"{normalized_code}_{period}"
# 从缓存获取
if model_key in self.model_cache:
return self.model_cache[model_key]
# 创建新模型
model_class = create_stock_kline_model(normalized_code, period)
self.model_cache[model_key] = model_class
return model_class
def create_table(self, stock_code: str, period: str = "1d") -> bool:
"""
创建股票K线数据表
Args:
stock_code: 股票代码
period: 时间周期
Returns:
bool: 创建成功返回True
"""
try:
model_class = self.get_stock_model(stock_code, period)
success = self.db_manager.create_table(model_class, safe=True)
if success:
table_name = get_table_name(normalize_stock_code(stock_code), period)
logger.info(f"{LOG_PREFIXES['SUCCESS']} 创建表成功: {table_name}")
return success
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败: {stock_code} ({period}) - {e}")
return False
def create_tables_for_stocks(self, stock_codes: List[str], period: str = "1d") -> Dict[str, bool]:
"""
批量创建股票表
Args:
stock_codes: 股票代码列表
period: 时间周期
Returns:
Dict[str, bool]: 创建结果 {stock_code: success}
"""
results = {}
logger.info(f"{LOG_PREFIXES['DATABASE']} 开始批量创建 {len(stock_codes)} 个股票表...")
for stock_code in stock_codes:
results[stock_code] = self.create_table(stock_code, period)
success_count = sum(results.values())
logger.info(f"{LOG_PREFIXES['SUCCESS']} 批量创建完成: {success_count}/{len(stock_codes)} 个表创建成功")
return results
# ================================ 数据读取 ================================
def read_stock_data(self,
stock_code: str,
period: str = "1d",
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
limit: Optional[int] = None) -> pd.DataFrame:
"""
从数据库读取股票K线数据并转换为DataFrame
Args:
stock_code: 股票代码
period: 时间周期
start_date: 开始日期
end_date: 结束日期
limit: 限制返回记录数
Returns:
pd.DataFrame: K线数据DataFrame,以timestamp为索引
"""
try:
# 获取模型类
model_class = self.get_stock_model(stock_code, period)
# 构建查询
query = model_class.select()
# 添加时间范围过滤
if start_date:
query = query.where(model_class.timestamp >= start_date)
if end_date:
query = query.where(model_class.timestamp <= end_date)
# 按时间排序
query = query.order_by(model_class.timestamp)
# 添加限制
if limit:
query = query.limit(limit)
# 执行查询
records = list(query)
if not records:
logger.warning(f"{LOG_PREFIXES['WARNING']} 未找到数据: {stock_code} ({period})")
return pd.DataFrame()
# 转换为DataFrame
data = []
for record in records:
data.append({
'timestamp': record.timestamp,
'open': float(record.open),
'high': float(record.high),
'low': float(record.low),
'close': float(record.close),
'volume': record.volume,
'amount': float(record.amount) if record.amount else 0.0
})
df = pd.DataFrame(data)
df.set_index('timestamp', inplace=True)
logger.info(f"{LOG_PREFIXES['SUCCESS']} 成功读取 {len(df)} 条K线数据: {stock_code} ({period})")
return df
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 读取股票数据失败: {stock_code} ({period}) - {e}")
return pd.DataFrame()
def get_existing_timestamps(self, stock_code: str, period: str = "1d",
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None) -> set:
"""
获取数据库中已存在的时间戳集合
Args:
stock_code: 股票代码
period: 时间周期
start_date: 开始日期
end_date: 结束日期
Returns:
set: 时间戳集合
"""
try:
model_class = self.get_stock_model(stock_code, period)
query = model_class.select(model_class.timestamp)
if start_date:
query = query.where(model_class.timestamp >= start_date)
if end_date:
query = query.where(model_class.timestamp <= end_date)
timestamps = {record.timestamp for record in query}
logger.debug(f"{LOG_PREFIXES['DATABASE']} 查询到 {len(timestamps)} 个已存在时间戳")
return timestamps
except Exception as e:
logger.warning(f"{LOG_PREFIXES['WARNING']} 查询已存在时间戳失败: {e}")
return set()
# ================================ 数据写入 ================================
def save_dataframe(self, df: pd.DataFrame, stock_code: str, period: str = "1d",
mode: str = "append", batch_size: int = 1000) -> int:
"""
将DataFrame保存到数据库
Args:
df: K线数据DataFrame
stock_code: 股票代码
period: 时间周期
mode: 保存模式 ("append" 增量追加, "replace" 替换模式)
batch_size: 批量大小
Returns:
int: 成功插入的记录数
"""
# 数据验证
if not validate_kline_data(df):
logger.error(f"{LOG_PREFIXES['ERROR']} DataFrame数据验证失败")
return 0
# 确保表存在
if not self.create_table(stock_code, period):
logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败,无法保存数据")
return 0
# 获取模型类
model_class = self.get_stock_model(stock_code, period)
if mode == "replace":
return self._save_replace_mode(df, model_class, batch_size)
else:
return self._save_append_mode(df, model_class, batch_size)
def _save_append_mode(self, df: pd.DataFrame, model_class, batch_size: int) -> int:
"""增量追加模式保存"""
try:
# 查询已存在的时间戳
min_time = df.index.min()
max_time = df.index.max()
# 获取表名进行查询(通过模型实例获取)
instance = model_class()
existing_timestamps = self.get_existing_timestamps(
instance.stock_code, instance.period, min_time, max_time
)
# 过滤出新数据
new_data = []
for timestamp, row in df.iterrows():
# 确保timestamp是datetime类型
if isinstance(timestamp, pd.Timestamp):
timestamp = timestamp.to_pydatetime()
if timestamp not in existing_timestamps:
new_data.append(self._row_to_dict(timestamp, row))
if not new_data:
logger.info(f"{LOG_PREFIXES['INFO']} 没有新数据需要插入")
return 0
# 批量插入
success_count = self.db_manager.batch_insert(model_class, new_data, batch_size)
total_records = len(df)
skipped_records = total_records - len(new_data)
logger.info(f"{LOG_PREFIXES['SUCCESS']} 增量保存完成: 新增 {success_count}/{len(new_data)} 条,跳过重复 {skipped_records} 条")
return success_count
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 增量保存失败: {e}")
raise
def _save_replace_mode(self, df: pd.DataFrame, model_class, batch_size: int) -> int:
"""替换模式保存"""
try:
# 清空表
self.db_manager.clear_table(model_class)
# 准备所有数据
all_data = []
for timestamp, row in df.iterrows():
# 确保timestamp是datetime类型
if isinstance(timestamp, pd.Timestamp):
timestamp = timestamp.to_pydatetime()
all_data.append(self._row_to_dict(timestamp, row))
# 批量插入
success_count = self.db_manager.batch_insert(model_class, all_data, batch_size)
logger.info(f"{LOG_PREFIXES['SUCCESS']} 替换模式保存完成: 插入 {success_count}/{len(all_data)} 条记录")
return success_count
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 替换模式保存失败: {e}")
raise
def _row_to_dict(self, timestamp, row: pd.Series) -> Dict[str, Any]:
"""将DataFrame行转换为字典"""
# 确保timestamp是datetime类型
if isinstance(timestamp, pd.Timestamp):
timestamp = timestamp.to_pydatetime()
return {
'timestamp': timestamp,
'open': Decimal(str(row['open'])),
'high': Decimal(str(row['high'])),
'low': Decimal(str(row['low'])),
'close': Decimal(str(row['close'])),
'volume': int(row['volume']),
'amount': Decimal(str(row['amount'])) if 'amount' in row and pd.notna(row['amount']) else Decimal('0')
}
# ================================ 数据查询和分析 ================================
def get_latest_data(self, stock_code: str, period: str = "1d", count: int = 1) -> pd.DataFrame:
"""获取最新的K线数据"""
try:
model_class = self.get_stock_model(stock_code, period)
records = list(
model_class.select()
.order_by(model_class.timestamp.desc())
.limit(count)
)
if not records:
return pd.DataFrame()
# 转换为DataFrame并按时间正序排列
data = []
for record in reversed(records): # 反转以获得正序
data.append({
'timestamp': record.timestamp,
'open': float(record.open),
'high': float(record.high),
'low': float(record.low),
'close': float(record.close),
'volume': record.volume,
'amount': float(record.amount) if record.amount else 0.0
})
df = pd.DataFrame(data)
df.set_index('timestamp', inplace=True)
return df
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 获取最新数据失败: {e}")
return pd.DataFrame()
def get_data_range(self, stock_code: str, period: str = "1d") -> Dict[str, Any]:
"""获取数据的时间范围和统计信息"""
try:
model_class = self.get_stock_model(stock_code, period)
# 使用peewee的聚合函数获取时间范围
from peewee import fn
min_time_query = model_class.select(fn.MIN(model_class.timestamp)).scalar()
max_time_query = model_class.select(fn.MAX(model_class.timestamp)).scalar()
count = model_class.select().count()
# 获取表名
table_name = get_table_name(normalize_stock_code(stock_code), period)
return {
'stock_code': stock_code,
'period': period,
'start_date': min_time_query,
'end_date': max_time_query,
'record_count': count,
'table_name': table_name
}
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 获取数据范围失败: {e}")
return {}
# ================================ 表维护 ================================
def clear_table(self, stock_code: str, period: str = "1d") -> int:
"""清空股票表数据"""
try:
model_class = self.get_stock_model(stock_code, period)
return self.db_manager.clear_table(model_class)
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 清空表失败: {e}")
return 0
def drop_table(self, stock_code: str, period: str = "1d") -> bool:
"""删除股票表"""
try:
model_class = self.get_stock_model(stock_code, period)
success = self.db_manager.drop_table(model_class, safe=True)
# 从缓存中移除
model_key = f"{normalize_stock_code(stock_code)}_{period}"
if model_key in self.model_cache:
del self.model_cache[model_key]
return success
except Exception as e:
logger.error(f"{LOG_PREFIXES['ERROR']} 删除表失败: {e}")
return False
def get_available_stocks(self) -> List[str]:
"""获取可用的股票代码列表"""
# TODO: 实现从数据库获取所有表名并解析股票代码
logger.warning(f"{LOG_PREFIXES['WARNING']} get_available_stocks() 方法待实现")
return []
def get_available_periods(self, stock_code: str) -> List[str]:
"""获取指定股票的可用时间周期"""
# TODO: 实现从数据库获取指定股票的所有时间周期
logger.warning(f"{LOG_PREFIXES['WARNING']} get_available_periods() 方法待实现")
return []
def close(self):
"""关闭数据管理器"""
self.db_manager.disconnect()
logger.info(f"{LOG_PREFIXES['DATABASE']} 股票数据管理器已关闭")
# ================================ 便捷函数 ================================
def get_stock_data_manager():
"""获取股票数据管理器实例"""
return StockDataManager()
if __name__ == "__main__":
# 测试股票数据管理器
print(f"{LOG_PREFIXES['DATABASE']} 测试股票数据管理器...")
manager = StockDataManager()
# 测试创建表
success = manager.create_table("000001.SZ", "1d")
print(f"{LOG_PREFIXES['SUCCESS'] if success else LOG_PREFIXES['ERROR']} 创建表测试: {'成功' if success else '失败'}")
# 测试数据范围查询
data_range = manager.get_data_range("000001.SZ", "1d")
if data_range:
print(f"{LOG_PREFIXES['SUCCESS']} 数据范围查询成功: {data_range}")
manager.close()