""" 股票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: # 策略1: 查询已存在的时间戳,只插入新数据 (增量插入) existing_timestamps = set() try: # 查询数据库中已存在的时间范围 min_time = df.index.min() max_time = df.index.max() existing_records = stock_model.select(stock_model.timestamp).where( (stock_model.timestamp >= min_time) & (stock_model.timestamp <= max_time) ) existing_timestamps = {record.timestamp for record in existing_records} logger.info(f"📊 数据库中已有 {len(existing_timestamps)} 条记录在时间范围内") except Exception as e: logger.warning(f"⚠️ 查询已存在记录失败,将尝试全量插入: {e}") # 过滤出需要插入的新数据 new_data = [] for timestamp, row in df.iterrows(): if timestamp not in existing_timestamps: new_data.append({ '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') }) if not new_data: logger.info("ℹ️ 没有新数据需要插入") return 0 logger.info(f"📥 准备插入 {len(new_data)} 条新记录") # 策略2: 批量插入新记录 success_count = 0 total_batches = (len(new_data) + batch_size - 1) // batch_size for i in range(0, len(new_data), batch_size): batch = new_data[i:i + batch_size] batch_num = i // batch_size + 1 try: # peewee批量插入 with stock_model._meta.database.atomic(): stock_model.insert_many(batch).execute() success_count += len(batch) logger.info(f"✅ 批次 {batch_num}/{total_batches}: 插入 {len(batch)} 条记录") except Exception as e: # 如果批量插入失败,尝试逐条插入这个批次 logger.warning(f"⚠️ 批次 {batch_num} 批量插入失败,尝试逐条插入: {e}") for record in batch: try: with stock_model._meta.database.atomic(): stock_model.insert(**record).execute() success_count += 1 except Exception as single_error: if "Duplicate entry" in str(single_error) or "PRIMARY" in str(single_error): continue # 跳过重复记录 else: logger.warning(f"⚠️ 单条插入失败 {record['timestamp']}: {single_error}") total_records = len(df) new_records = len(new_data) skipped_records = total_records - new_records logger.info(f"✅ 插入完成: 新增 {success_count}/{new_records} 条,跳过重复 {skipped_records} 条") return success_count except Exception as e: logger.error(f"❌ 保存K线数据到数据库失败: {e}") raise def save_dataframe_to_mysql_replace_mode(df, stock_model, batch_size=1000): """ 替换模式保存 - 清空表后重新插入所有数据 适用于需要完整替换数据的场景 Args: df (pd.DataFrame): 包含K线数据的DataFrame stock_model: 股票K线数据模型类 batch_size (int): 批量插入的大小 Returns: int: 成功插入的记录数量 """ if df.empty: logger.warning("⚠️ DataFrame为空,跳过保存") return 0 try: # 清空表 clear_stock_table(stock_model) # 准备所有数据 all_data = [] for timestamp, row in df.iterrows(): all_data.append({ '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') }) # 批量插入 success_count = 0 total_batches = (len(all_data) + batch_size - 1) // batch_size for i in range(0, len(all_data), batch_size): batch = all_data[i:i + batch_size] batch_num = i // batch_size + 1 try: with stock_model._meta.database.atomic(): stock_model.insert_many(batch).execute() success_count += len(batch) logger.info(f"✅ 批次 {batch_num}/{total_batches}: 插入 {len(batch)} 条记录") except Exception as e: logger.error(f"❌ 批次 {batch_num} 插入失败: {e}") raise logger.info(f"✅ 替换模式完成: 插入 {success_count}/{len(all_data)} 条记录") return success_count except Exception as e: logger.error(f"❌ 替换模式保存失败: {e}") raise def clear_all_tables_for_period(stock_codes, period): """ 清空指定周期的所有股票表 - 维护工具函数 Args: stock_codes (list): 股票代码列表 period (str): 数据周期 Returns: dict: 清空结果 {stock_code: deleted_count} """ results = {} logger.info(f"🧹 开始清空 {period} 周期的所有股票表...") for stock_code in stock_codes: try: model_class = create_stock_kline_model(stock_code, period) deleted_count = clear_stock_table(model_class) results[stock_code] = deleted_count except Exception as e: logger.error(f"❌ 清空 {stock_code} ({period}) 表失败: {e}") results[stock_code] = 0 total_deleted = sum(results.values()) logger.info(f"✅ 清空完成,共删除 {total_deleted} 条记录") return results 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