# 常量定义使用指南 ## 概述 为了避免在代码中使用魔法字符串(magic strings),我们集中定义了所有常用的字符串常量。这样可以: 1. ✅ **避免拼写错误** - IDE可以提供代码补全 2. ✅ **统一管理** - 修改常量只需在一处更改 3. ✅ **类型安全** - 减少运行时错误 4. ✅ **易于维护** - 代码更清晰,易于理解 ## 常量类 ### Period - 周期常量 定义了所有支持的K线周期: ```python from src.core.constants import Period # 日线 Period.DAY_1 # "1d" Period.DAY_3 # "3d" Period.DAY_5 # "5d" # 周线/月线 Period.WEEK_1 # "1w" Period.MONTH_1 # "1M" # 小时线 Period.HOUR_1 # "1h" Period.HOUR_2 # "2h" Period.HOUR_4 # "4h" # 分钟线 Period.MIN_1 # "1m" Period.MIN_5 # "5m" Period.MIN_15 # "15m" Period.MIN_30 # "30m" ``` **常用方法**: ```python # 检查周期是否有效 if Period.is_valid("1d"): print("有效的周期") # 获取所有周期 all_periods = Period.get_all() print(all_periods) # ['1d', '3d', '5d', ...] ``` ### Indicator - 技术指标常量 定义了所有支持的技术指标: ```python from src.core.constants import Indicator # 趋势类指标 Indicator.MACD # "MACD" Indicator.MA # "MA" Indicator.EMA # "EMA" Indicator.BOLL # "BOLL" # 震荡类指标 Indicator.KDJ # "KDJ" Indicator.RSI # "RSI" Indicator.CCI # "CCI" # 量能类指标 Indicator.VOL # "VOL" Indicator.OBV # "OBV" # 波动类指标 Indicator.ATR # "ATR" ``` **常用方法**: ```python # 检查指标是否有效 if Indicator.is_valid("MACD"): print("有效的指标") # 获取所有指标 all_indicators = Indicator.get_all() print(all_indicators) # ['MACD', 'MA', 'EMA', ...] ``` ### CacheKey - 缓存键名常量 定义了缓存数据结构中使用的键名: ```python from src.core.constants import CacheKey CacheKey.KLINES # "klines" CacheKey.META # "meta" CacheKey.TIME_RANGE # "time_range" CacheKey.INDICATORS # "indicators" ``` ### ConfigKey - 配置键名常量 定义了配置文件中使用的键名: ```python from src.core.constants import ConfigKey # 缓存配置 ConfigKey.CACHE_ENABLED # "cache_enabled" ConfigKey.CACHE_MAX_MEMORY_MB # "cache_max_memory_mb" # 数据库配置 ConfigKey.DB_TYPE # "db_type" ConfigKey.DB_PATH # "db_path" ``` ## 使用示例 ### ❌ 不推荐的写法(使用魔法字符串) ```python # 容易拼写错误,IDE无法提供补全 klines = service.get_klines("000001", "1d", start, end) macd = service.get_indicator("000001", "1d", "MACD") # 如果拼错了,只能在运行时才能发现错误 klines = service.get_klines("000001", "1dd", start, end) # 拼写错误! ``` ### ✅ 推荐的写法(使用常量) ```python from src.core.constants import Period, Indicator # 使用常量,IDE可以提供代码补全 klines = service.get_klines("000001", Period.DAY_1, start, end) macd = service.get_indicator("000001", Period.DAY_1, Indicator.MACD) # 如果拼错常量名,IDE会立即提示错误 klines = service.get_klines("000001", Period.DAY_11, start, end) # IDE会提示错误! ``` ## 实际应用场景 ### 场景1: 数据获取 ```python from src.core.constants import Period from src.data_service.data_service import DataService from datetime import datetime service = DataService.from_config(config) start = datetime(2024, 1, 1) end = datetime(2024, 12, 31) # 获取不同周期的数据 daily = service.get_klines("000001", Period.DAY_1, start, end) hourly = service.get_klines("000001", Period.HOUR_1, start, end) minute = service.get_klines("000001", Period.MIN_5, start, end) ``` ### 场景2: 指标计算 ```python from src.core.constants import Period, Indicator # 获取多个指标 macd = service.get_indicator("000001", Period.DAY_1, Indicator.MACD) kdj = service.get_indicator("000001", Period.DAY_1, Indicator.KDJ) rsi = service.get_indicator("000001", Period.DAY_1, Indicator.RSI) ``` ### 场景3: 用户输入验证 ```python from src.core.constants import Period def get_klines_safe(service, symbol, period_str, start, end): """安全地获取K线数据,验证周期""" if not Period.is_valid(period_str): raise ValueError( f"无效的周期: {period_str}\n" f"支持的周期: {', '.join(Period.get_all())}" ) return service.get_klines(symbol, period_str, start, end) # 使用 try: klines = get_klines_safe(service, "000001", "1d", start, end) # 成功 klines = get_klines_safe(service, "000001", "2d", start, end) # 抛出异常 except ValueError as e: print(f"错误: {e}") ``` ### 场景4: 批量操作 ```python from src.core.constants import Period # 下载多个周期的数据 periods_to_download = [ Period.DAY_1, Period.HOUR_1, Period.MIN_5, ] for period in periods_to_download: service.download_klines( symbols=["000001", "600000"], start_date=start, end_date=end, periods=[period] ) ``` ### 场景5: 动态筛选 ```python from src.core.constants import Period # 只处理分钟级别的数据 minute_periods = [p for p in Period.get_all() if p.endswith('m')] print(f"分钟级周期: {minute_periods}") # 输出: ['1m', '5m', '15m', '30m', '60m'] # 只处理日线级别的数据 day_periods = [p for p in Period.get_all() if p.endswith('d')] print(f"日线级周期: {day_periods}") # 输出: ['1d', '3d', '5d'] ``` ## 迁移指南 如果你的代码中已经使用了字符串,可以按以下步骤迁移: ### 步骤1: 导入常量 ```python # 在文件顶部添加导入 from src.core.constants import Period, Indicator ``` ### 步骤2: 替换字符串 ```python # 查找所有 "1d" 并替换为 Period.DAY_1 # 查找所有 "1h" 并替换为 Period.HOUR_1 # 查找所有 "MACD" 并替换为 Indicator.MACD ``` ### 步骤3: 测试 ```python # 运行测试确保一切正常 python -m pytest tests/ ``` ## 注意事项 1. **向后兼容性**:常量的值保持不变,所以现有代码不会受影响 2. **逐步迁移**:可以逐步替换,不需要一次性全部改完 3. **字符串仍可用**:如果某些地方确实需要使用字符串(如配置文件),仍然可以使用 4. **验证函数**:使用 `is_valid()` 方法验证用户输入或外部数据 ## 扩展常量 如果需要添加新的周期或指标: ```python # 在 src/core/constants.py 中添加 class Period: # ... 现有常量 ... # 添加新周期 MIN_3 = "3m" # 3分钟线 # 记得更新 ALL 列表 ALL = [ # ... 现有周期 ... MIN_3, ] ``` ## 完整示例 查看 `examples/constants_usage_example.py` 获取完整的使用示例。 运行示例: ```bash python examples/constants_usage_example.py ``` ## 总结 使用常量定义是一个简单但有效的最佳实践,可以显著提高代码质量和可维护性。建议在所有新代码中使用常量,并逐步迁移旧代码。