190 lines
6.9 KiB
Python
190 lines
6.9 KiB
Python
|
|
"""
|
|||
|
|
股票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(index=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="记录更新时间")
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
# 设置时间戳字段为主键(确保每个时间点只有一条记录)
|
|||
|
|
primary_key = False
|
|||
|
|
|
|||
|
|
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(),
|
|||
|
|
'primary_key': False
|
|||
|
|
}),
|
|||
|
|
'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:
|
|||
|
|
# 准备批量插入的数据
|
|||
|
|
batch_data = []
|
|||
|
|
|
|||
|
|
for timestamp, row in df.iterrows():
|
|||
|
|
record = {
|
|||
|
|
'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')
|
|||
|
|
}
|
|||
|
|
batch_data.append(record)
|
|||
|
|
|
|||
|
|
# 当达到批量大小时执行插入
|
|||
|
|
if len(batch_data) >= batch_size:
|
|||
|
|
stock_model.insert_many(batch_data).execute()
|
|||
|
|
batch_data = []
|
|||
|
|
|
|||
|
|
# 插入剩余数据
|
|||
|
|
if batch_data:
|
|||
|
|
stock_model.insert_many(batch_data).execute()
|
|||
|
|
|
|||
|
|
total_records = len(df)
|
|||
|
|
logger.info(f"✅ 成功保存 {total_records} 条K线数据到数据库")
|
|||
|
|
return total_records
|
|||
|
|
|
|||
|
|
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
|