QTrade/src/data_process_model/stock_models.py

196 lines
7.3 KiB
Python
Raw Normal View History

"""
股票K线数据模型
使用peewee ORM定义股票K线数据表结构
"""
from peewee import DateTimeField, DecimalField, BigIntegerField
from database_config import BaseModel, get_database
import logging
from decimal import Decimal
from datetime import datetime
logger = logging.getLogger(__name__)
class StockKlineBase(BaseModel):
"""
股票K线数据基础模型
这是所有股票K线表的基础模型,定义了通用字段
"""
# 时间戳字段 - 设置为主键确保唯一性
timestamp = DateTimeField(primary_key=True, help_text="K线时间戳")
# OHLCV数据 - 使用Decimal确保精度
open_price = DecimalField(max_digits=10, decimal_places=3, help_text="开盘价")
high_price = DecimalField(max_digits=10, decimal_places=3, help_text="最高价")
low_price = DecimalField(max_digits=10, decimal_places=3, help_text="最低价")
close_price = DecimalField(max_digits=10, decimal_places=3, help_text="收盘价")
volume = BigIntegerField(help_text="成交量")
amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额")
def create_stock_kline_model(stock_code: str, period: str = "1d"):
"""
动态创建股票K线数据表模型
为每个股票代码和周期创建独立的数据表,表名格式严格规范化:
kline_{clean_stock_code}_{period}
表名转换规则:
- "601658.SH" + "1d" -> kline_601658_sh_1d
- "000001.SZ" + "5m" -> kline_000001_sz_5m
- "510310.SH" + "15m" -> kline_510310_sh_15m
注意:股票代码必须包含市场后缀(.SH/.SZ)以确保表名唯一性
Args:
stock_code (str): 股票代码,必须包含市场后缀,如 "601658.SH", "000001.SZ"
period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d"
Returns:
type: 动态创建的股票K线模型类
Raises:
ValueError: 当股票代码格式不正确时
"""
# 验证股票代码格式
if not stock_code or '.' not in stock_code:
raise ValueError(f"股票代码格式错误,必须包含市场后缀: {stock_code}")
# 清理股票代码和周期,生成合法的表名
clean_code = stock_code.replace(".", "_").replace("/", "_").replace("-", "_").lower()
clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower()
table_name = f"kline_{clean_code}_{clean_period}"
class_name = f"StockKline_{clean_code}_{clean_period}"
# 动态创建模型类
model_class = type(class_name, (StockKlineBase,), {
'__module__': __name__,
'Meta': type('Meta', (), {
'table_name': table_name,
'database': get_database()
}),
'stock_code': stock_code, # 保存原始股票代码
})
logger.info(f"📊 创建股票K线模型: {class_name} -> {table_name}")
return model_class
def create_tables_for_stocks(stock_codes: list, period: str = "1d"):
"""
为股票代码列表创建对应的数据表
Args:
stock_codes (list): 股票代码列表,如 ["601658.SH", "000001.SZ"]
period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d"
Returns:
dict: 股票代码到模型类的映射字典
"""
stock_models = {}
try:
for stock_code in stock_codes:
# 创建模型类
model_class = create_stock_kline_model(stock_code, period)
# 尝试创建数据表,如果失败则跳过
try:
model_class.create_table(safe=True) # safe=True 表示如果表已存在则跳过
logger.info(f"✅ 创建股票表成功: {stock_code} ({period})")
except Exception as table_error:
# 如果是表已存在相关的错误,仍然可以使用现有表
if "already exists" in str(table_error) or "Duplicate" in str(table_error):
logger.warning(f"⚠️ 表已存在,使用现有表: {stock_code} ({period})")
else:
logger.error(f"❌ 创建表失败: {stock_code} ({period}) - {table_error}")
continue
stock_models[stock_code] = model_class
except Exception as e:
logger.error(f"❌ 创建股票表失败: {e}")
# 不再抛出异常,返回已成功创建的模型
return stock_models
def save_dataframe_to_mysql(df, stock_model, batch_size=1000):
"""
将pandas DataFrame保存到MySQL数据库中
Args:
df (pd.DataFrame): 包含K线数据的DataFrame,需要有时间索引
stock_model: 股票K线数据模型类
batch_size (int): 批量插入的大小,默认1000条
Returns:
int: 成功插入的记录数量
"""
if df.empty:
logger.warning("⚠️ DataFrame为空,跳过保存")
return 0
try:
# 由于timestamp现在是主键,我们需要逐条插入,忽略重复记录
success_count = 0
for timestamp, row in df.iterrows():
try:
# 尝试插入记录,如果timestamp重复则跳过
stock_model.insert(
timestamp=timestamp,
open_price=Decimal(str(row['open'])),
high_price=Decimal(str(row['high'])),
low_price=Decimal(str(row['low'])),
close_price=Decimal(str(row['close'])),
volume=int(row['volume']),
amount=Decimal(str(row['amount'])) if 'amount' in row else Decimal('0')
).execute()
success_count += 1
except Exception as e:
# 如果是重复键错误,说明主键约束生效,静默跳过
if "Duplicate entry" in str(e) or "PRIMARY" in str(e):
continue # 静默跳过重复的timestamp
else:
logger.warning(f"⚠️ 插入记录失败 {timestamp}: {e}")
continue
total_records = len(df)
logger.info(f"✅ 成功保存 {success_count}/{total_records} 条K线数据到数据库")
return success_count
except Exception as e:
logger.error(f"❌ 保存K线数据到数据库失败: {e}")
raise
def clear_stock_table(stock_model):
"""
清空股票K线数据表
Args:
stock_model: 股票K线数据模型类
Returns:
int: 删除的记录数量
"""
try:
# 获取表名用于日志显示
table_name = stock_model._meta.table_name
# 先查询记录数量
count_before = stock_model.select().count()
if count_before > 0:
logger.info(f"🧹 正在清空表 {table_name},当前记录数: {count_before}")
# 删除所有记录
deleted_count = stock_model.delete().execute()
logger.info(f"✅ 成功清空表 {table_name},删除了 {deleted_count} 条记录")
return deleted_count
else:
logger.info(f"ℹ️ 表 {table_name} 已经是空的,无需清空")
return 0
except Exception as e:
logger.error(f"❌ 清空表失败: {e}")
raise