2025-07-31 18:30:12 +08:00
|
|
|
|
"""
|
|
|
|
|
|
数据处理模型公共配置文件 (common.py)
|
|
|
|
|
|
类似于C++中的common.h头文件,定义所有模块共同遵守的数据结构、约定和常量
|
|
|
|
|
|
|
|
|
|
|
|
本文件包含:
|
|
|
|
|
|
- 股票数据结构定义
|
|
|
|
|
|
- 数据库表结构约定
|
|
|
|
|
|
- 时间格式标准
|
|
|
|
|
|
- 字段命名约定
|
|
|
|
|
|
- 数据验证规则
|
|
|
|
|
|
- 常用枚举和常量
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
from typing import List, Dict, Any, Optional, Union
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
from enum import Enum
|
|
|
|
|
|
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 基础常量定义 =============================
|
|
|
|
|
|
|
|
|
|
|
|
# 支持的股票市场
|
|
|
|
|
|
class StockMarket(Enum):
|
|
|
|
|
|
"""股票市场枚举"""
|
|
|
|
|
|
SH = "SH" # 上海证券交易所
|
|
|
|
|
|
SZ = "SZ" # 深圳证券交易所
|
|
|
|
|
|
|
|
|
|
|
|
# 支持的时间周期
|
|
|
|
|
|
class TimeFrame(Enum):
|
|
|
|
|
|
"""时间周期枚举"""
|
|
|
|
|
|
MINUTE_1 = "1m" # 1分钟
|
|
|
|
|
|
MINUTE_5 = "5m" # 5分钟
|
|
|
|
|
|
MINUTE_15 = "15m" # 15分钟
|
|
|
|
|
|
MINUTE_30 = "30m" # 30分钟
|
2025-08-05 16:01:38 +08:00
|
|
|
|
MINUTE_60 = "60m" # 60分钟 (1小时)
|
2025-07-31 18:30:12 +08:00
|
|
|
|
DAILY = "1d" # 日线
|
|
|
|
|
|
WEEKLY = "1w" # 周线
|
|
|
|
|
|
MONTHLY = "1M" # 月线
|
|
|
|
|
|
|
|
|
|
|
|
# 数据来源
|
|
|
|
|
|
class DataSource(Enum):
|
|
|
|
|
|
"""数据来源枚举"""
|
|
|
|
|
|
DATABASE = "database" # 数据库原始数据
|
|
|
|
|
|
EXTERNAL = "external" # 外部添加数据
|
|
|
|
|
|
CALCULATED = "calculated" # 计算生成数据
|
|
|
|
|
|
REALTIME = "realtime" # 实时数据
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 数据结构约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
# 标准K线数据字段名约定
|
|
|
|
|
|
KLINE_COLUMNS = {
|
|
|
|
|
|
'timestamp': 'timestamp', # 时间戳 (datetime类型)
|
|
|
|
|
|
'open': 'open', # 开盘价 (float)
|
|
|
|
|
|
'high': 'high', # 最高价 (float)
|
|
|
|
|
|
'low': 'low', # 最低价 (float)
|
|
|
|
|
|
'close': 'close', # 收盘价 (float)
|
|
|
|
|
|
'volume': 'volume', # 成交量 (int)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 标准K线数据字段类型约定
|
|
|
|
|
|
KLINE_DTYPES = {
|
|
|
|
|
|
'timestamp': 'datetime64[ns]',
|
|
|
|
|
|
'open': 'float64',
|
|
|
|
|
|
'high': 'float64',
|
|
|
|
|
|
'low': 'float64',
|
|
|
|
|
|
'close': 'float64',
|
|
|
|
|
|
'volume': 'int64'
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 技术指标字段命名约定
|
|
|
|
|
|
INDICATOR_COLUMNS = {
|
|
|
|
|
|
# 移动平均线
|
|
|
|
|
|
'ma5': 'ma5', 'ma10': 'ma10', 'ma20': 'ma20', 'ma60': 'ma60',
|
|
|
|
|
|
'ema5': 'ema5', 'ema10': 'ema10', 'ema20': 'ema20', 'ema60': 'ema60',
|
|
|
|
|
|
|
|
|
|
|
|
# MACD指标
|
|
|
|
|
|
'macd': 'macd', # MACD线
|
|
|
|
|
|
'macd_signal': 'signal', # 信号线
|
|
|
|
|
|
'macd_hist': 'histogram', # 柱状图
|
|
|
|
|
|
|
|
|
|
|
|
# RSI指标
|
|
|
|
|
|
'rsi': 'rsi',
|
|
|
|
|
|
'rsi_14': 'rsi_14',
|
|
|
|
|
|
|
|
|
|
|
|
# 布林带
|
|
|
|
|
|
'bb_upper': 'bb_upper', # 上轨
|
|
|
|
|
|
'bb_middle': 'bb_middle', # 中轨
|
|
|
|
|
|
'bb_lower': 'bb_lower', # 下轨
|
|
|
|
|
|
|
|
|
|
|
|
# KDJ指标
|
|
|
|
|
|
'kdj_k': 'k',
|
|
|
|
|
|
'kdj_d': 'd',
|
|
|
|
|
|
'kdj_j': 'j'
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 股票代码处理约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
# 股票代码识别规则
|
|
|
|
|
|
STOCK_CODE_PATTERNS = {
|
|
|
|
|
|
# 上海市场
|
|
|
|
|
|
'SH_PATTERNS': [
|
|
|
|
|
|
r'^60[0-9]{4}$', # 主板: 600xxx, 601xxx, 603xxx, 605xxx
|
|
|
|
|
|
r'^68[0-9]{4}$', # 科创板: 688xxx
|
|
|
|
|
|
r'^51[0-9]{4}$', # ETF: 510xxx, 511xxx, 512xxx, 513xxx, 515xxx, 516xxx, 518xxx
|
|
|
|
|
|
r'^50[0-9]{4}$', # 其他: 500xxx
|
|
|
|
|
|
],
|
|
|
|
|
|
# 深圳市场
|
|
|
|
|
|
'SZ_PATTERNS': [
|
|
|
|
|
|
r'^00[0-9]{4}$', # 主板: 000xxx, 001xxx, 002xxx, 003xxx
|
|
|
|
|
|
r'^30[0-9]{4}$', # 创业板: 300xxx, 301xxx
|
|
|
|
|
|
r'^15[0-9]{4}$', # ETF: 150xxx, 159xxx
|
|
|
|
|
|
r'^16[0-9]{4}$', # 可转债等: 160xxx
|
|
|
|
|
|
]
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def normalize_stock_code(stock_code: str) -> str:
|
|
|
|
|
|
"""
|
|
|
|
|
|
标准化股票代码格式
|
|
|
|
|
|
|
|
|
|
|
|
规则:
|
|
|
|
|
|
- 输入: "601658" -> 输出: "601658.SH"
|
|
|
|
|
|
- 输入: "000001" -> 输出: "000001.SZ"
|
|
|
|
|
|
- 输入: "601658.SH" -> 输出: "601658.SH"
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 原始股票代码
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
str: 标准化后的股票代码
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not stock_code:
|
|
|
|
|
|
return stock_code
|
|
|
|
|
|
|
|
|
|
|
|
# 如果已经包含市场后缀,直接返回大写格式
|
|
|
|
|
|
if '.' in stock_code:
|
|
|
|
|
|
return stock_code.upper()
|
|
|
|
|
|
|
|
|
|
|
|
# 导入re用于模式匹配
|
|
|
|
|
|
import re
|
|
|
|
|
|
|
|
|
|
|
|
# 检查是否匹配上海市场
|
|
|
|
|
|
for pattern in STOCK_CODE_PATTERNS['SH_PATTERNS']:
|
|
|
|
|
|
if re.match(pattern, stock_code):
|
|
|
|
|
|
return f"{stock_code}.SH"
|
|
|
|
|
|
|
|
|
|
|
|
# 检查是否匹配深圳市场
|
|
|
|
|
|
for pattern in STOCK_CODE_PATTERNS['SZ_PATTERNS']:
|
|
|
|
|
|
if re.match(pattern, stock_code):
|
|
|
|
|
|
return f"{stock_code}.SZ"
|
|
|
|
|
|
|
|
|
|
|
|
# 默认为上海市场
|
|
|
|
|
|
return f"{stock_code}.SH"
|
|
|
|
|
|
|
|
|
|
|
|
def get_table_name(stock_code: str, period: str) -> str:
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取数据库表名
|
|
|
|
|
|
|
|
|
|
|
|
约定:kline_{stock_code}_{period}
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 股票代码 (如: "601658.SH")
|
|
|
|
|
|
period (str): 时间周期 (如: "1m", "1d")
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
str: 数据库表名 (如: "kline_601658_sh_1m")
|
|
|
|
|
|
"""
|
|
|
|
|
|
# 标准化股票代码
|
|
|
|
|
|
normalized_code = normalize_stock_code(stock_code)
|
|
|
|
|
|
|
|
|
|
|
|
# 转换为表名格式: 601658.SH -> 601658_sh
|
|
|
|
|
|
code_part = normalized_code.lower().replace('.', '_')
|
|
|
|
|
|
|
|
|
|
|
|
return f"kline_{code_part}_{period}"
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 时间格式约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
# 标准时间格式
|
|
|
|
|
|
TIME_FORMATS = {
|
|
|
|
|
|
'STANDARD': '%Y-%m-%d %H:%M:%S', # 2024-07-22 09:30:00
|
|
|
|
|
|
'DATE_ONLY': '%Y-%m-%d', # 2024-07-22
|
|
|
|
|
|
'TIME_ONLY': '%H:%M:%S', # 09:30:00
|
|
|
|
|
|
'ISO_FORMAT': '%Y-%m-%dT%H:%M:%S', # 2024-07-22T09:30:00
|
|
|
|
|
|
'COMPACT': '%Y%m%d_%H%M%S', # 20240722_093000
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def standardize_timestamp(timestamp: Union[str, datetime, pd.Timestamp]) -> pd.Timestamp:
|
|
|
|
|
|
"""
|
|
|
|
|
|
标准化时间戳格式
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
timestamp: 时间戳,支持多种格式
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
pd.Timestamp: 标准化后的时间戳
|
|
|
|
|
|
"""
|
|
|
|
|
|
if isinstance(timestamp, str):
|
|
|
|
|
|
return pd.to_datetime(timestamp)
|
|
|
|
|
|
elif isinstance(timestamp, datetime):
|
|
|
|
|
|
return pd.Timestamp(timestamp)
|
|
|
|
|
|
elif isinstance(timestamp, pd.Timestamp):
|
|
|
|
|
|
return timestamp
|
|
|
|
|
|
else:
|
|
|
|
|
|
raise ValueError(f"不支持的时间戳类型: {type(timestamp)}")
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 数据验证规则 =============================
|
|
|
|
|
|
|
|
|
|
|
|
def validate_kline_data(df: pd.DataFrame) -> Dict[str, Any]:
|
|
|
|
|
|
"""
|
|
|
|
|
|
验证K线数据格式是否符合约定
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
df (pd.DataFrame): K线数据
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
Dict[str, Any]: 验证结果
|
|
|
|
|
|
"""
|
|
|
|
|
|
result = {
|
|
|
|
|
|
'valid': True,
|
|
|
|
|
|
'errors': [],
|
|
|
|
|
|
'warnings': [],
|
|
|
|
|
|
'info': {}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 检查必需的列
|
|
|
|
|
|
required_columns = set(KLINE_COLUMNS.values())
|
|
|
|
|
|
actual_columns = set(df.columns)
|
|
|
|
|
|
|
|
|
|
|
|
missing_columns = required_columns - actual_columns
|
|
|
|
|
|
if missing_columns:
|
|
|
|
|
|
result['valid'] = False
|
|
|
|
|
|
result['errors'].append(f"缺少必需的列: {missing_columns}")
|
|
|
|
|
|
|
|
|
|
|
|
# 检查数据类型
|
|
|
|
|
|
if result['valid']:
|
|
|
|
|
|
for col in KLINE_COLUMNS.values():
|
|
|
|
|
|
if col in df.columns:
|
|
|
|
|
|
expected_dtype = KLINE_DTYPES[col]
|
|
|
|
|
|
actual_dtype = str(df[col].dtype)
|
|
|
|
|
|
|
|
|
|
|
|
if col == 'timestamp':
|
|
|
|
|
|
if not pd.api.types.is_datetime64_any_dtype(df[col]):
|
|
|
|
|
|
result['warnings'].append(f"时间列 '{col}' 类型不是datetime: {actual_dtype}")
|
|
|
|
|
|
elif col in ['open', 'high', 'low', 'close']:
|
|
|
|
|
|
if not pd.api.types.is_numeric_dtype(df[col]):
|
|
|
|
|
|
result['errors'].append(f"价格列 '{col}' 类型不是数值型: {actual_dtype}")
|
|
|
|
|
|
result['valid'] = False
|
|
|
|
|
|
elif col == 'volume':
|
|
|
|
|
|
if not pd.api.types.is_integer_dtype(df[col]) and not pd.api.types.is_numeric_dtype(df[col]):
|
|
|
|
|
|
result['warnings'].append(f"成交量列 '{col}' 类型不是整型: {actual_dtype}")
|
|
|
|
|
|
|
|
|
|
|
|
# 检查数据逻辑性
|
|
|
|
|
|
if result['valid'] and len(df) > 0:
|
|
|
|
|
|
# 检查价格逻辑 (high >= max(open, close), low <= min(open, close))
|
|
|
|
|
|
price_logic_error = (
|
|
|
|
|
|
(df['high'] < df[['open', 'close']].max(axis=1)) |
|
|
|
|
|
|
(df['low'] > df[['open', 'close']].min(axis=1))
|
|
|
|
|
|
).any()
|
|
|
|
|
|
|
|
|
|
|
|
if price_logic_error:
|
|
|
|
|
|
result['warnings'].append("存在价格逻辑错误的记录 (high < max(open,close) 或 low > min(open,close))")
|
|
|
|
|
|
|
|
|
|
|
|
# 检查成交量为负
|
|
|
|
|
|
if (df['volume'] < 0).any():
|
|
|
|
|
|
result['warnings'].append("存在负成交量的记录")
|
|
|
|
|
|
|
|
|
|
|
|
# 统计信息
|
|
|
|
|
|
result['info'] = {
|
|
|
|
|
|
'total_records': len(df),
|
|
|
|
|
|
'columns': list(df.columns),
|
|
|
|
|
|
'date_range': None
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if 'timestamp' in df.columns and len(df) > 0:
|
|
|
|
|
|
result['info']['date_range'] = {
|
|
|
|
|
|
'start': df['timestamp'].min(),
|
|
|
|
|
|
'end': df['timestamp'].max()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 缓存键约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
def get_cache_key(stock_code: str, period: str) -> str:
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取缓存键名
|
|
|
|
|
|
|
|
|
|
|
|
约定:{stock_code}_{period}
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
stock_code (str): 标准化后的股票代码
|
|
|
|
|
|
period (str): 时间周期
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
str: 缓存键名
|
|
|
|
|
|
"""
|
|
|
|
|
|
normalized_code = normalize_stock_code(stock_code)
|
|
|
|
|
|
return f"{normalized_code}_{period}"
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 内存管理约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
# 内存缓存配置
|
|
|
|
|
|
MEMORY_CONFIG = {
|
|
|
|
|
|
'MAX_CACHE_SIZE_MB': 1024, # 最大缓存大小(MB)
|
|
|
|
|
|
'MAX_RECORDS_PER_CACHE': 10000, # 每个缓存最大记录数
|
|
|
|
|
|
'CLEANUP_THRESHOLD': 0.8, # 清理阈值(80%)
|
|
|
|
|
|
'DEFAULT_LIMIT': 1000, # 默认查询限制
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 共享内存配置
|
|
|
|
|
|
SHARED_MEMORY_CONFIG = {
|
|
|
|
|
|
'CACHE_NAME': 'qtrade_kline_cache',
|
|
|
|
|
|
'DEFAULT_SIZE_MB': 100,
|
|
|
|
|
|
'CLEANUP_INTERVAL_SECONDS': 300, # 5分钟清理一次
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 数据库约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
# 数据库表前缀
|
|
|
|
|
|
TABLE_PREFIXES = {
|
|
|
|
|
|
'KLINE': 'kline_', # K线数据表
|
|
|
|
|
|
'INDICATOR': 'indicator_', # 技术指标表
|
|
|
|
|
|
'TEST': 'test_', # 测试表
|
|
|
|
|
|
'TEMP': 'temp_', # 临时表
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# 数据库字段长度限制
|
|
|
|
|
|
FIELD_LIMITS = {
|
|
|
|
|
|
'STOCK_CODE': 20, # 股票代码字段长度
|
|
|
|
|
|
'PERIOD': 10, # 周期字段长度
|
|
|
|
|
|
'SOURCE': 50, # 数据源字段长度
|
|
|
|
|
|
'COMMENT': 255, # 注释字段长度
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 日志约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
# 日志前缀约定
|
|
|
|
|
|
LOG_PREFIXES = {
|
|
|
|
|
|
'SUCCESS': '✅', # 成功操作
|
|
|
|
|
|
'ERROR': '❌', # 错误
|
|
|
|
|
|
'WARNING': '⚠️', # 警告
|
|
|
|
|
|
'INFO': 'ℹ️', # 信息
|
|
|
|
|
|
'DEBUG': '🔍', # 调试
|
|
|
|
|
|
'DATABASE': '📊', # 数据库操作
|
|
|
|
|
|
'CACHE': '🗄️', # 缓存操作
|
|
|
|
|
|
'NETWORK': '🌐', # 网络操作
|
|
|
|
|
|
'FILE': '📁', # 文件操作
|
|
|
|
|
|
'MEMORY': '💾', # 内存操作
|
|
|
|
|
|
'TIME': '⏰', # 时间相关
|
|
|
|
|
|
'CALCULATION': '🧮', # 计算相关
|
|
|
|
|
|
'ANALYSIS': '📈', # 技术分析
|
|
|
|
|
|
'TOOL': '🔧', # 工具相关
|
|
|
|
|
|
'CLEANING': '🧹', # 清理操作
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 导出所有公共约定 =============================
|
|
|
|
|
|
|
|
|
|
|
|
__all__ = [
|
|
|
|
|
|
# 枚举类
|
|
|
|
|
|
'StockMarket', 'TimeFrame', 'DataSource',
|
|
|
|
|
|
|
|
|
|
|
|
# 常量
|
|
|
|
|
|
'KLINE_COLUMNS', 'KLINE_DTYPES', 'INDICATOR_COLUMNS',
|
|
|
|
|
|
'STOCK_CODE_PATTERNS', 'TIME_FORMATS', 'MEMORY_CONFIG',
|
|
|
|
|
|
'SHARED_MEMORY_CONFIG', 'TABLE_PREFIXES', 'FIELD_LIMITS',
|
|
|
|
|
|
'LOG_PREFIXES',
|
|
|
|
|
|
|
|
|
|
|
|
# 函数
|
|
|
|
|
|
'normalize_stock_code', 'get_table_name', 'standardize_timestamp',
|
|
|
|
|
|
'validate_kline_data', 'get_cache_key',
|
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
# ============================= 版本信息 =============================
|
|
|
|
|
|
|
|
|
|
|
|
__version__ = "1.0.0"
|
|
|
|
|
|
__author__ = "QTrade Team"
|
|
|
|
|
|
__description__ = "数据处理模型公共配置和约定"
|