""" 股票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="成交额") # 创建和更新时间 created_at = DateTimeField(default=datetime.now, help_text="记录创建时间") updated_at = DateTimeField(default=datetime.now, 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 Args: stock_code (str): 股票代码,如 "601658.SH", "000001.SZ" period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d" Returns: type: 动态创建的股票K线模型类 """ # 清理股票代码和周期,生成合法的表名 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 get_stock_kline_data(stock_model, start_time=None, end_time=None, limit=None): """ 从数据库查询股票K线数据 Args: stock_model: 股票K线数据模型类 start_time (datetime, optional): 开始时间 end_time (datetime, optional): 结束时间 limit (int, optional): 限制返回记录数 Returns: list: K线数据记录列表 """ try: query = stock_model.select().order_by(stock_model.timestamp) # 添加时间范围过滤 if start_time: query = query.where(stock_model.timestamp >= start_time) if end_time: query = query.where(stock_model.timestamp <= end_time) if limit: query = query.limit(limit) results = list(query) logger.info(f"📊 查询到 {len(results)} 条K线数据") return results 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 def clear_all_stock_tables(stock_models): """ 批量清空多个股票K线数据表 Args: stock_models (dict): 股票代码到模型的映射字典 {stock_code: model} Returns: dict: 每个股票的删除记录数 {stock_code: deleted_count} """ results = {} try: logger.info(f"🧹 开始批量清空 {len(stock_models)} 个股票表...") for stock_code, stock_model in stock_models.items(): try: deleted_count = clear_stock_table(stock_model) results[stock_code] = deleted_count except Exception as e: logger.error(f"❌ 清空 {stock_code} 表失败: {e}") results[stock_code] = 0 total_deleted = sum(results.values()) logger.info(f"✅ 批量清空完成,总共删除 {total_deleted} 条记录") return results except Exception as e: logger.error(f"❌ 批量清空表失败: {e}") raise