market_regime_hmm.py 14 KB

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