QTrade/src/data_process_model/stock_models.py

122 lines
4.1 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.

"""
股票K线数据模型 - 纯粹的 ORM 模型定义
只负责数据模型的定义与约束,不包含数据库操作逻辑
"""
from typing import Dict
from peewee import DateTimeField, DecimalField, BigIntegerField
# 导入数据库配置
try:
from .database_config import BaseModel, get_database
except ImportError:
from database_config import BaseModel, get_database
# 导入公共配置
try:
from .common import (
normalize_stock_code, get_table_name, LOG_PREFIXES
)
except ImportError:
from common import (
normalize_stock_code, get_table_name, LOG_PREFIXES
)
import logging
logger = logging.getLogger(__name__)
class StockKlineBase(BaseModel):
"""
股票K线数据基础模型
遵循公共配置的字段命名约定和数据类型定义
"""
# 时间戳字段 - 使用公共配置的列名
timestamp = DateTimeField(primary_key=True, help_text="K线时间戳")
# OHLCV数据 - 使用Decimal确保精度,遵循公共配置的字段名称
open = DecimalField(max_digits=10, decimal_places=3, help_text="开盘价")
high = DecimalField(max_digits=10, decimal_places=3, help_text="最高价")
low = DecimalField(max_digits=10, decimal_places=3, help_text="最低价")
close = DecimalField(max_digits=10, decimal_places=3, help_text="收盘价")
volume = BigIntegerField(help_text="成交量")
amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额", null=True)
# 支持的K线周期常量
SUPPORTED_PERIODS = ['1m', '15m', '30m', '60m', '1d'] # 添加1d用于回测数据
def create_stock_kline_model(stock_code: str, period: str):
"""
动态创建股票K线数据表模型
专门用于创建1分钟、15分钟、30分钟、60分钟周期的K线数据模型
Args:
stock_code (str): 股票代码,如 "601398.SH", "000001.SZ"
period (str): 数据周期,支持 "1m", "15m", "30m", "60m"
Returns:
type: 动态创建的股票K线模型类
Raises:
ValueError: 当股票代码格式不正确或周期不支持时
"""
# 验证周期参数
if period not in SUPPORTED_PERIODS:
raise ValueError(f"不支持的周期: {period},支持的周期为: {SUPPORTED_PERIODS}")
# 使用公共配置标准化股票代码
normalized_code = normalize_stock_code(stock_code)
# 生成表名:kline_{股票代码}_{周期}
# 例如:601398.SH + 15m -> kline_601398_sh_15m
code_part = normalized_code.lower().replace('.', '_') # 601398.SH -> 601398_sh
table_name = f"kline_{code_part}_{period}"
# 生成类名
clean_code = normalized_code.lower().replace(".", "_")
class_name = f"StockKline_{clean_code}_{period}"
# 动态创建模型类
model_class = type(class_name, (StockKlineBase,), {
'__module__': __name__,
'Meta': type('Meta', (), {
'table_name': table_name,
'database': get_database()
}),
'stock_code': normalized_code, # 保存标准化后的股票代码
'period': period, # 保存时间周期
})
logger.info(f"{LOG_PREFIXES['DATABASE']} 创建股票K线模型: {class_name} -> {table_name}")
return model_class
def create_all_timeframe_models(stock_code: str) -> Dict[str, type]:
"""
为指定股票创建所有时间周期的K线模型
Args:
stock_code (str): 股票代码,如 "601398.SH"
Returns:
Dict[str, type]: 时间周期到模型类的映射字典
"""
models = {}
for period in SUPPORTED_PERIODS:
try:
models[period] = create_stock_kline_model(stock_code, period)
logger.info(f"{LOG_PREFIXES['DATABASE']} 成功创建 {stock_code} {period} 模型")
except Exception as e:
logger.error(f"{LOG_PREFIXES['DATABASE']} 创建 {stock_code} {period} 模型失败: {e}")
return models
# 其他可能的模型类可以在这里定义
# class StockInfo(BaseModel):
# """股票基本信息模型"""
# pass
#
# class TradingCalendar(BaseModel):
# """交易日历模型"""
# pass