""" 验证工具模块 提供各种数据验证功能 """ import re from typing import Optional def validate_stock_code(code: str) -> bool: """ 验证股票代码格式 A股代码格式: - 上海:6开头,6位数字 - 深圳:0/3开头,6位数字 - 创业板:3开头,6位数字 - 科创板:688开头,6位数字 Args: code: 股票代码 Returns: 是否有效 """ if not code: return False # 移除可能的后缀(如.SH, .SZ) code = code.split('.')[0] # 检查是否为6位数字 if not re.match(r'^\d{6}$', code): return False # 检查首位数字 first_digit = code[0] if first_digit in ['0', '3', '6']: return True # 检查科创板 if code.startswith('688'): return True return False def normalize_stock_code(code: str) -> Optional[str]: """ 标准化股票代码,添加市场后缀 Args: code: 股票代码 Returns: 标准化后的代码(如600000.SH)或None """ if not validate_stock_code(code): return None # 移除已有后缀 code = code.split('.')[0] # 添加市场后缀 if code.startswith('6'): return f"{code}.SH" # 上海 elif code.startswith(('0', '3')): return f"{code}.SZ" # 深圳 elif code.startswith('688'): return f"{code}.SH" # 科创板 return None def validate_date_format(date_str: str) -> bool: """ 验证日期格式(YYYYMMDD) Args: date_str: 日期字符串 Returns: 是否有效 """ if not date_str: return False # 检查格式 if not re.match(r'^\d{8}$', date_str): return False # 简单的日期范围检查 year = int(date_str[:4]) month = int(date_str[4:6]) day = int(date_str[6:8]) if year < 1990 or year > 2100: return False if month < 1 or month > 12: return False if day < 1 or day > 31: return False return True