""" 股票K线数据模型 - 纯粹的 ORM 模型定义 只负责数据模型的定义与约束,不包含数据库操作逻辑 """ from peewee import DateTimeField, DecimalField, BigIntegerField from database_manager import BaseModel, get_database # 导入公共配置 from common import ( normalize_stock_code, get_table_name, LOG_PREFIXES ) import logging from datetime import datetime 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) def create_stock_kline_model(stock_code: str, period: str = "1d"): """ 动态创建股票K线数据表模型 使用公共配置的标准化函数确保表名一致性 Args: stock_code (str): 股票代码,如 "601658.SH", "000001.SZ" period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d" Returns: type: 动态创建的股票K线模型类 Raises: ValueError: 当股票代码格式不正确时 """ # 使用公共配置标准化股票代码 normalized_code = normalize_stock_code(stock_code) # 使用公共配置生成表名 table_name = get_table_name(normalized_code, period) # 生成类名 clean_code = normalized_code.lower().replace(".", "_") clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower() 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': normalized_code, # 保存标准化后的股票代码 'period': period, # 保存时间周期 }) logger.info(f"{LOG_PREFIXES['DATABASE']} 创建股票K线模型: {class_name} -> {table_name}") return model_class # 其他可能的模型类可以在这里定义 # class StockInfo(BaseModel): # """股票基本信息模型""" # pass # # class TradingCalendar(BaseModel): # """交易日历模型""" # pass