# 使用隐马尔可夫模型（HMM）识别市场结构：第五部分


在前四部分的研究中，我们完成了从特征提取、状态数选择到模型语义自动化解读的完整链路。现在，到了检验成果的时刻：将 HMM 生成的样本外预测信号转化为实际交易逻辑，并进行回溯检验。

为了客观评估 HMM 模型的价值，我们设定了一个**基准策略（低通滤波器趋势跟随）**与 **HMM 信号策略**进行对比。我们将重点观察 HMM 是否能有效过滤趋势末期的噪音，以及它在复杂震荡行情中的真实表现。结果显示，HMM 策略在显著降低回撤的同时，大幅提升了夏普比率，展现出强大的中长期趋势识别能力。

## 数据导入与市场结构量化

为了在 Zorro 中进行回测，我们首先将 Python 导出的 CSV 样本外预测结果（包含预测状态及其概率）导入系统。

![样本外预测](image.png)

在代码层面，我们将字符串形式的市场状态映射为数值，以便于逻辑判断和可视化展示：
*   **0**：高分歧震荡 (`high_vol_chop`)
*   **1**：上涨动能不足 (`bull_pause`)
*   **2**：强势上涨趋势 (`bull_trend`)
*   **-1**：下跌动能不足 (`bear_pause`)
*   **-2**：强势下跌趋势 (`bear_trend`)

![用折线图显示市场结构](image_1.png)

## 第二部分：策略逻辑与回测设置

### 1. 基准策略：低通滤波器趋势线

基准策略使用典型的趋势指标——**低通滤波器（LowPass Filter）**作为趋势识别工具（回溯期 = 200，与特征生成时的设置保持一致）。
*   做多/做空：根据 Trends 序列的上升/下降（`rising`/`falling`）判断。
*   平仓：当趋势出现拐点（`peak`/`valley`）时平仓。

```c
function tradeBenchmark() {
    vars Prices = series(price());
    vars Trends = series(LowPass(Prices,200));

    bool LongEntry = rising(Trends);
    bool LongExit = peak(Trends);
    bool ShortEntry = falling(Trends);
    bool ShortExit = valley(Trends);

    Lots = 100;
    if(NumOpenLong > 0 && LongExit) exitLong();
    if(NumOpenShort > 0 && ShortExit) exitShort();
    if(NumOpenLong == 0 && LongEntry) enterLong();
    if(NumOpenShort == 0 && ShortEntry) enterShort();

    plot("Trend", Trends, MAIN, BLUE);
}
```

### 2. 测试策略：HMM 状态信号

测试策略直接读取 HMM 预测的历史状态数据进行操作。
*   做多信号：当状态为 `bull_trend` 或 `bull_pause` (Signal >= 1) 时进场。
*   做空信号：当状态为 `bear_trend` 或 `bear_pause` (Signal <= -1) 时进场。
*   平仓信号：当市场进入“高波动震荡”（Signal == 0）时，退出所有仓位。

```c
function tradeHMM() {
    // 加载样本外预测
    if(Init) {
        int Rows = dataParse(1,"+%Y-%m-%d %H:%M:%S,sss,f,f,f,f,f,i",InputPath);
        if(!Rows) printf("\nFailed to read csv!");
    }
    int Row = dataFind(1,wdate(0));  // 位移为0，杜绝前视偏差
    string HmmState = dataStr(1,Row,1);

    int Signal = 0;
    if(HmmState == "bull_trend") Signal = 2;
    else if(HmmState == "bull_pause") Signal = 1;
    else if(HmmState == "bear_pause") Signal = -1;
    else if(HmmState == "bear_trend") Signal = -2;

    bool LongEntry = Signal >= 1;
    bool LongExit = Signal == 0;
    bool ShortEntry = Signal <= -1;
    bool ShortExit = Signal == 0;

    Lots = 100;
    if(NumOpenLong > 0 && LongExit) exitLong();
    if(NumOpenShort > 0 && ShortExit) exitShort();
    if(NumOpenLong == 0 && LongEntry) enterLong();
    if(NumOpenShort == 0 && ShortEntry) enterShort();

    plot("Signal", Signal, NEW|LINE, RED);
    vars Trends = series(LowPass(series(price()),200));
    plot2("Trend", Trends[0], MAIN, rising(Trends), GREEN, RED);
}
```

## 第三部分：回测结果对比分析

通过下表数据的对比，HMM 策略的优势一目了然：

| 业绩指标 | 基准策略 (LowPass) | **测试策略 (HMM)** |
| :--- | :--- | :--- |
| **最大回撤** | 91.2% | **18.2%** |
| **胜率** | 20% | **37.7%** |
| **年收益率** | 10% | **31%** |
| **夏普比率** | 0.28 | **0.83** |
| **盈利因子 (Profit Factor)** | 1.18 | **1.67** |
| **PRR (Pessimistic Return Ratio)** | 0.97 | **1.37** |
| **多头盈利因子** | 1.45 | **3.38** |
| **交易次数** | 331 | 220 |

### 核心结论与逻辑解析

1.  风险控制能力显著提高：HMM 策略将最大回撤从恐怖的 91% 压缩到了 18%。这主要归功于 HMM 对“高波动震荡”状态的识别，能让策略在行情不明朗时主动空仓。
2.  过滤趋势末期的噪音：传统趋势线在趋势后期（价格围绕均线横盘）会频繁触发反转信号，产生大量亏损。HMM 表现卓越之处在于：它能识别出虽然上涨动能下降（`bull_pause`），但大方向未变的特征，从而坚定持仓，直到趋势彻底反转。这种“定力”让其多头盈利因子达到了惊人的 3.38。
3.  多强空弱的局限性：数据显示，HMM 对上涨趋势的捕捉远好于下跌趋势。空头盈利因子（0.91）仍不理想，这反映了加密货币市场“牛长熊急”的特征对模型特征提取提出了更高的要求。

### 细节观察：识别能力的盲点

2024年的高效捕捉：在 2024 年的行情中，HMM 成功区分了强势上涨与波动整理，有效过滤了小幅回调。

![测试组2024年表现](image_4.png)

2025年的震荡泥潭：当市场缺乏明确的中期趋势（如 2025 年 1 月，3月，9-10月），HMM 模型表现出脆弱性。它在多个状态间快速切换产生高频亏损，这说明模型目前的“震荡过滤”逻辑仍需通过特征工程进一步强化。

![测试策略2025年表现](image_5.png)

## 总结

本系列量化研究至此告一段落。我们得出的结论是：**HMM 模型在识别中长期市场结构方面显著优于传统的移动平均或趋势线类指标。** 它不是简单的“金叉买死叉卖”，而是通过对多种市场统计特征的深度融合，实现了对“市场环境”的诊断。

优化方向：

- 特征工程强化：引入成交量、订单流或市场情绪的指标，以提升对“震荡状态”的识别精度。
- 概率化交易：目前的策略是基于确定性的标签进行交易，未来可尝试基于“状态概率”进行仓位动态管理（如 $P(Bull) > 0.8$ 时满仓，$P(Bull) \approx 0.5$ 时半仓）。
- 多头/空头不对称信号：针对上涨和下跌行情分别训练特征和模型，以解决空头表现疲软的问题。

### 附录：Zorro 回测完整代码

> [代码块内容已包含在上述 tradeHMM 和 tradeBenchmark 函数中，并在 run 函数配置了相关环境设置（如资产 BTCUSDT、4H 周期、WFO 路径等）。]

```c
/*
使用 hmm 模型生成的样本外预测值，创建交易策略并回溯检验。
*/

#include <profile.c>
#include <utils.c>

string InputPath = "C:\\Users\\scofield\\zorro-data\\hmm_predictions_oos.csv";

function tradeBenchmark() {
    vars Prices = series(price());
    vars Trends = series(LowPass(Prices,200));

    bool LongEntry = rising(Trends);
    bool LongExit = peak(Trends);
    bool ShortEntry = falling(Trends);
    bool ShortExit = valley(Trends);

    Lots = 100;
    if(NumOpenLong > 0 && LongExit) exitLong();
    if(NumOpenShort > 0 && ShortExit) exitShort();
    if(NumOpenLong == 0 && LongEntry) enterLong();
    if(NumOpenShort == 0 && ShortEntry) enterShort();

    plot("Trend", Trends, MAIN, BLUE);
}

function tradeHMM() {
    // 加载样本外预测
    if(Init) {
        int Rows = dataParse(1,"+%Y-%m-%d %H:%M:%S,sss,f,f,f,f,f,i",InputPath);
        if(!Rows) printf("\nFailed to read csv!");
    }
    int Row = dataFind(1,wdate(0));  // 位移为0，不会产生前视偏误
    string HmmState = dataStr(1,Row,1);  // 若row=-1,返回最早的记录

    // 将市场状态映射为数字
    int Signal = 0;
    if(HmmState == "bull_trend") Signal = 2;
    else if(HmmState == "bull_pause") Signal = 1;
    else if(HmmState == "bear_pause") Signal = -1;
    else if(HmmState == "bear_trend") Signal = -2;

    bool LongEntry = Signal >= 1;
    bool LongExit = Signal == 0;
    bool ShortEntry = Signal <= -1;
    bool ShortExit = Signal == 0;

    Lots = 100;
    if(NumOpenLong > 0 && LongExit) exitLong();
    if(NumOpenShort > 0 && ShortExit) exitShort();
    if(NumOpenLong == 0 && LongEntry) enterLong();
    if(NumOpenShort == 0 && ShortEntry) enterShort();

    plot("Signal", Signal, NEW|LINE, RED);

    // 创建趋势线作为辅助参考
    vars Trends = series(LowPass(series(price()),200));
    plot2("Trend", Trends[0], MAIN, rising(Trends), GREEN, RED);
}

function run() {
    set(LOGFILE,PLOTNOW);

    resf(BarMode,BR_WEEKEND);
    StartWeek = 0;
    EndWeek = 62359;
    StartMarket = 0;
    EndMarket = 2359;
    BarPeriod = 240;
    BarZone = UTC;
    BarOffset = 0;
    TickFix = 60000;

    StartDate = 20200624;
    EndDate = 20251230;
    LookBack = 500;

    asset("BTCUSDT");

    // tradeBenchmark();
    tradeHMM();
}
```


---

> 作者: [量化炼金](https://codealchemy.blog.csdn.net/)  
> URL: http://localhost:1313/posts/hmm-market-regime-part5/  

