market_regime_hmm.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 市场环境识别器 (Market Regime Identifier)
  5. 基于HMM隐马尔可夫模型的市场状态识别系统
  6. 状态定义:
  7. - 状态0(震荡):价格波动大但无明显方向,Hurst指数≈0.5,自相关性低
  8. - 状态1(趋势):价格持续单向运动,Hurst指数>0.6,高自相关
  9. - 状态2(反转):超买/超卖后的V型反转,RSI极端值后的快速回归
  10. 作者: OpenClaw
  11. 日期: 2026-03-06
  12. """
  13. import numpy as np
  14. import pandas as pd
  15. from hmmlearn.hmm import GaussianHMM
  16. from scipy import stats
  17. import warnings
  18. warnings.filterwarnings('ignore')
  19. # ==================== 特征工程 ====================
  20. def calculate_hurst(prices, max_lag=100):
  21. """
  22. 计算Hurst指数
  23. H ≈ 0.5: 随机游走(震荡)
  24. H > 0.6: 趋势性
  25. H < 0.4: 均值回归
  26. """
  27. lags = range(2, min(max_lag, len(prices)//4))
  28. tau = [np.std(np.subtract(prices[lag:], prices[:-lag])) for lag in lags]
  29. if len(tau) < 2 or any(t <= 0 for t in tau):
  30. return 0.5
  31. reg = np.polyfit(np.log(lags), np.log(tau), 1)
  32. return reg[0]
  33. def calculate_rsi(prices, period=14):
  34. """计算RSI指标(标准 Wilder 方法)"""
  35. prices = pd.Series(prices)
  36. delta = prices.diff()
  37. gain = delta.clip(lower=0)
  38. loss = (-delta).clip(lower=0)
  39. avg_gain = gain.ewm(alpha=1/period, adjust=False, min_periods=period).mean()
  40. avg_loss = loss.ewm(alpha=1/period, adjust=False, min_periods=period).mean()
  41. rs = avg_gain / (avg_loss + 1e-10)
  42. rsi = 100 - (100 / (1 + rs))
  43. return rsi.fillna(50).to_numpy()
  44. def extract_features(df):
  45. """
  46. 提取特征向量 X_t
  47. X_t = [收益率标准差(5日), 价格动量(10日), 波动率比率(短/长), 成交量变化率, 日内趋势强度]
  48. """
  49. features = pd.DataFrame(index=df.index)
  50. # 1. 收益率标准差(5日)
  51. returns = df['close'].pct_change()
  52. features['ret_std_5'] = returns.rolling(5).std() * np.sqrt(252)
  53. # 2. 价格动量(10日)
  54. features['momentum_10'] = (df['close'] / df['close'].shift(10) - 1) * 100
  55. # 3. 波动率比率(短/长)
  56. vol_short = returns.rolling(5).std()
  57. vol_long = returns.rolling(20).std()
  58. features['vol_ratio'] = vol_short / (vol_long + 1e-10)
  59. # 4. 成交量变化率
  60. features['volume_change'] = df['volume'].pct_change() * 100
  61. # 5. 日内趋势强度
  62. features['intraday_trend'] = ((df['close'] - df['open']) / (df['high'] - df['low'] + 1e-10)) * 100
  63. # 6. Hurst指数(额外特征)
  64. features['hurst'] = df['close'].rolling(100).apply(calculate_hurst, raw=True)
  65. # 7. RSI
  66. features['rsi'] = calculate_rsi(df['close'].values)
  67. # 8. 自相关性
  68. features['autocorr'] = returns.rolling(20).apply(lambda x: x.autocorr(lag=1) if len(x) > 1 else 0)
  69. # 填充缺失值
  70. features = features.ffill().fillna(0)
  71. return features
  72. # ==================== HMM模型 ====================
  73. class MarketRegimeHMM:
  74. """市场环境HMM模型"""
  75. # 状态名称
  76. STATE_NAMES = {
  77. 0: '震荡',
  78. 1: '趋势',
  79. 2: '反转'
  80. }
  81. def __init__(self, n_components=3, n_iter=100):
  82. # 先验转移概率矩阵
  83. self.PRIOR_TRANSITION = np.array([
  84. [0.85, 0.10, 0.05], # 震荡 -> 震荡/趋势/反转
  85. [0.15, 0.80, 0.05], # 趋势 -> 震荡/趋势/反转
  86. [0.20, 0.10, 0.70] # 反转 -> 震荡/趋势/反转
  87. ])
  88. self.model = GaussianHMM(
  89. n_components=n_components,
  90. covariance_type='full',
  91. n_iter=n_iter,
  92. random_state=42,
  93. init_params='mc' # 只初始化均值和协方差,不初始化转移矩阵
  94. )
  95. self.is_fitted = False
  96. def fit(self, features):
  97. """训练HMM模型"""
  98. print("训练HMM模型...")
  99. X = features.values
  100. # 先验状态分布(均匀分布)
  101. self.model.startprob_ = np.array([1/3, 1/3, 1/3])
  102. # 使用先验转移概率初始化
  103. self.model.transmat_ = self.PRIOR_TRANSITION.copy()
  104. # 拟合模型
  105. self.model.fit(X)
  106. self.is_fitted = True
  107. print(f"模型收敛: {self.model.monitor_.converged}")
  108. print(f"迭代次数: {self.model.n_iter}")
  109. print("\n学习到的转移概率矩阵:")
  110. print(self.model.transmat_.round(3))
  111. return self
  112. def predict(self, features):
  113. """预测状态序列"""
  114. if not self.is_fitted:
  115. raise ValueError("模型尚未训练,请先调用fit()")
  116. X = features.values
  117. states = self.model.predict(X)
  118. # 计算状态概率
  119. state_probs = self.model.predict_proba(X)
  120. return states, state_probs
  121. def get_current_regime(self, features):
  122. """获取当前市场状态"""
  123. states, probs = self.predict(features)
  124. current_state = states[-1]
  125. current_prob = probs[-1]
  126. return {
  127. 'state': current_state,
  128. 'state_name': self.STATE_NAMES[current_state],
  129. 'probabilities': {
  130. self.STATE_NAMES[i]: current_prob[i]
  131. for i in range(len(self.STATE_NAMES))
  132. },
  133. 'confidence': current_prob[current_state]
  134. }
  135. # ==================== 策略切换逻辑 ====================
  136. class StrategySelector:
  137. """基于市场状态的策略选择器"""
  138. STRATEGY_CONFIG = {
  139. 0: { # 震荡
  140. 'name': '均值回归',
  141. 'action': 'RSI超买超卖交易',
  142. 'position_size': 0.5, # 降低仓位
  143. 'stop_loss': '2N',
  144. 'description': '关闭趋势策略,使用RSI超买(>70)超卖(<30)信号'
  145. },
  146. 1: { # 趋势
  147. 'name': '海龟趋势',
  148. 'action': '全速运行',
  149. 'position_size': 1.0, # 全仓位
  150. 'stop_loss': '2N',
  151. 'description': '增加仓位,突破20日高低点交易'
  152. },
  153. 2: { # 反转
  154. 'name': '反向/观望',
  155. 'action': '反向信号或空仓',
  156. 'position_size': 0.3, # 最小仓位
  157. 'stop_loss': '1N', # 收紧止损
  158. 'description': '反向信号或观望,收紧止损'
  159. }
  160. }
  161. @classmethod
  162. def get_strategy(cls, state):
  163. """根据状态获取策略配置"""
  164. return cls.STRATEGY_CONFIG.get(state, cls.STRATEGY_CONFIG[0])
  165. @classmethod
  166. def generate_signal(cls, state, rsi_value, price, ma20):
  167. """生成交易信号"""
  168. strategy = cls.get_strategy(state)
  169. signal = {
  170. 'state': state,
  171. 'strategy': strategy['name'],
  172. 'position_size': strategy['position_size'],
  173. 'action': 'HOLD'
  174. }
  175. if state == 0: # 震荡 - RSI均值回归
  176. if rsi_value < 30:
  177. signal['action'] = 'BUY'
  178. signal['reason'] = 'RSI超卖'
  179. elif rsi_value > 70:
  180. signal['action'] = 'SELL'
  181. signal['reason'] = 'RSI超买'
  182. elif state == 1: # 趋势 - 突破系统
  183. if price > ma20 * 1.02:
  184. signal['action'] = 'BUY'
  185. signal['reason'] = '突破20日均线2%'
  186. elif price < ma20 * 0.98:
  187. signal['action'] = 'SELL'
  188. signal['reason'] = '跌破20日均线2%'
  189. elif state == 2: # 反转 - 反向或观望
  190. if rsi_value > 70:
  191. signal['action'] = 'SELL'
  192. signal['reason'] = '超买后反转'
  193. elif rsi_value < 30:
  194. signal['action'] = 'BUY'
  195. signal['reason'] = '超卖后反转'
  196. else:
  197. signal['action'] = 'HOLD'
  198. signal['reason'] = '观望'
  199. return signal
  200. # ==================== 模型评估 ====================
  201. def evaluate_model(hmm, features, true_states=None):
  202. """
  203. 评估模型性能
  204. 由于真实状态未知,使用以下指标:
  205. 1. 对数似然值
  206. 2. AIC/BIC
  207. 3. 状态持续时间合理性
  208. 4. 状态与价格行为的对应关系
  209. """
  210. X = features.values
  211. # 计算对数似然
  212. log_likelihood = hmm.model.score(X)
  213. # 计算AIC和BIC
  214. n_params = hmm.model.n_components * (hmm.model.n_features + hmm.model.n_features * (hmm.model.n_features + 1) / 2) + hmm.model.n_components * hmm.model.n_components
  215. n_samples = len(X)
  216. aic = -2 * log_likelihood + 2 * n_params
  217. bic = -2 * log_likelihood + n_params * np.log(n_samples)
  218. print(f"\n模型评估指标:")
  219. print(f"对数似然: {log_likelihood:.2f}")
  220. print(f"AIC: {aic:.2f}")
  221. print(f"BIC: {bic:.2f}")
  222. # 预测状态
  223. states, probs = hmm.predict(features)
  224. # 统计状态分布
  225. state_counts = pd.Series(states).value_counts().sort_index()
  226. state_pct = (state_counts / len(states) * 100).round(2)
  227. print(f"\n状态分布:")
  228. for state_id, state_name in hmm.STATE_NAMES.items():
  229. count = state_counts.get(state_id, 0)
  230. pct = state_pct.get(state_id, 0)
  231. print(f" {state_name}: {count}天 ({pct}%)")
  232. # 计算平均状态持续时间
  233. state_durations = []
  234. current_state = states[0]
  235. duration = 1
  236. for s in states[1:]:
  237. if s == current_state:
  238. duration += 1
  239. else:
  240. state_durations.append((current_state, duration))
  241. current_state = s
  242. duration = 1
  243. state_durations.append((current_state, duration))
  244. print(f"\n平均状态持续时间:")
  245. for state_id in range(3):
  246. durations = [d for s, d in state_durations if s == state_id]
  247. if durations:
  248. avg_duration = np.mean(durations)
  249. print(f" {hmm.STATE_NAMES[state_id]}: {avg_duration:.1f}天")
  250. return {
  251. 'log_likelihood': log_likelihood,
  252. 'aic': aic,
  253. 'bic': bic,
  254. 'state_distribution': state_counts.to_dict(),
  255. 'states': states,
  256. 'state_probs': probs
  257. }
  258. # ==================== 主程序 ====================
  259. def main():
  260. """主程序"""
  261. print("="*70)
  262. print("市场环境识别器 (Market Regime Identifier)")
  263. print("基于HMM隐马尔可夫模型")
  264. print("="*70)
  265. # 示例:使用随机数据演示
  266. print("\n注意:这是演示版本,请使用真实数据运行")
  267. print("数据格式要求:DataFrame包含 'open', 'high', 'low', 'close', 'volume' 列")
  268. # 生成示例数据
  269. np.random.seed(42)
  270. n_days = 500
  271. dates = pd.date_range('2023-01-01', periods=n_days, freq='B')
  272. # 模拟价格走势(包含趋势、震荡、反转三种状态)
  273. price = 100
  274. prices = []
  275. for i in range(n_days):
  276. # 模拟不同状态
  277. if i < 150: # 趋势
  278. price *= (1 + np.random.normal(0.001, 0.01))
  279. elif i < 300: # 震荡
  280. price *= (1 + np.random.normal(0, 0.015))
  281. else: # 反转
  282. if i < 375:
  283. price *= (1 + np.random.normal(-0.002, 0.012))
  284. else:
  285. price *= (1 + np.random.normal(0.002, 0.012))
  286. prices.append(price)
  287. df = pd.DataFrame({
  288. 'open': prices + np.random.normal(0, 0.5, n_days),
  289. 'high': np.array(prices) + np.abs(np.random.normal(1, 0.5, n_days)),
  290. 'low': np.array(prices) - np.abs(np.random.normal(1, 0.5, n_days)),
  291. 'close': prices,
  292. 'volume': np.random.randint(1000000, 5000000, n_days)
  293. }, index=dates)
  294. print(f"\n示例数据: {len(df)}天")
  295. print(f"日期范围: {df.index[0].date()} ~ {df.index[-1].date()}")
  296. # 特征提取
  297. print("\n提取特征...")
  298. features = extract_features(df)
  299. # 选择训练特征(核心5个)
  300. feature_cols = ['ret_std_5', 'momentum_10', 'vol_ratio', 'volume_change', 'intraday_trend']
  301. X_train = features[feature_cols].dropna()
  302. print(f"特征矩阵: {X_train.shape}")
  303. # 训练HMM模型
  304. hmm = MarketRegimeHMM(n_components=3, n_iter=100)
  305. hmm.fit(X_train)
  306. # 预测状态
  307. states, probs = hmm.predict(X_train)
  308. # 评估模型
  309. eval_results = evaluate_model(hmm, X_train)
  310. # 获取当前状态
  311. current_regime = hmm.get_current_regime(X_train)
  312. print("\n" + "="*70)
  313. print("当前市场状态识别")
  314. print("="*70)
  315. print(f"状态: {current_regime['state_name']} (状态{current_regime['state']})")
  316. print(f"置信度: {current_regime['confidence']:.2%}")
  317. print("\n状态概率分布:")
  318. for name, prob in current_regime['probabilities'].items():
  319. bar = '#' * int(prob * 20)
  320. print(f" {name:6s}: {prob:.2%} {bar}")
  321. # 策略建议
  322. strategy = StrategySelector.get_strategy(current_regime['state'])
  323. current_rsi = features['rsi'].iloc[-1]
  324. current_price = df['close'].iloc[-1]
  325. current_ma20 = df['close'].rolling(20).mean().iloc[-1]
  326. signal = StrategySelector.generate_signal(
  327. current_regime['state'],
  328. current_rsi,
  329. current_price,
  330. current_ma20
  331. )
  332. print("\n" + "="*70)
  333. print("策略建议")
  334. print("="*70)
  335. print(f"推荐策略: {strategy['name']}")
  336. print(f"操作策略: {strategy['action']}")
  337. print(f"仓位建议: {strategy['position_size']*100:.0f}%")
  338. print(f"止损设置: {strategy['stop_loss']}")
  339. print(f"描述: {strategy['description']}")
  340. print("\n交易信号:")
  341. print(f" 动作: {signal['action']}")
  342. if 'reason' in signal:
  343. print(f" 原因: {signal['reason']}")
  344. print("\n" + "="*70)
  345. print("使用说明:")
  346. print("="*70)
  347. print("1. 准备真实市场数据(2017-2025年)")
  348. print("2. 调用 extract_features(df) 提取特征")
  349. print("3. 使用 MarketRegimeHMM 训练模型")
  350. print("4. 根据 get_current_regime() 结果切换策略")
  351. print("\n验证要求: 状态识别准确率 > 72%")
  352. print("="*70)
  353. if __name__ == "__main__":
  354. main()