# 基于低通滤波器与模糊逻辑的4小时趋势跟随策略


如何从杂乱的价格波动中提取真实趋势，并建立一套具备鲁棒性的交易系统，是每一位研究者面临的终极课题。本文将深入剖析一种基于低通滤波器（Low-Pass Filter）与模糊逻辑（Fuzzy Logic）的4小时图交易策略。通过多轮迭代优化，我们不仅成功捕捉到了比特币与以太坊的中期大行情，更通过波动率过滤与非对称平仓机制，显著提升了策略在震荡市中的盈利能力。

## 1. 回测环境设置

我们使用 zorro 进行回溯检验，回溯设置如下。

| Asset | BTCUSDT, ETHUSDT |
| --- | --- |
| BarPeriod | 240 (4小时) |
| StartDate | 20170101 |
| EndDate | 20251230 |
| Lookback | 1000 |
| Leverage | 10 |
| Commission | -0.1 |
| Slippage | 5 |
| NumWFOCycles | 10 |
| DataSplit | 85 |
| FixedCapital | 10000 |

## 2. 迭代优化

本策略的核心理念是利用**低通滤波器**过滤高频噪音，并结合**模糊逻辑**来量化当前市场结构的“看涨/看跌概率”。

### 2.1 基础策略
**逻辑设定**：
- **低通滤波器回溯期**：200
- **模糊因子**：0.1
- **进场概率阈值**：0.6

当上涨概率突破0.6时做多，趋势线出现筑顶迹象时平仓；反之则做空。

**回测表现**：
基础策略表现出极佳的趋势捕捉能力，盈利因子达到 **1.76**，年化夏普比率为 **1.09**。然而，通过对净值曲线和交易细节的观察，我们发现了两个致命弱点：
1. 在趋势转换阶段，指标失效，产生连续亏损。
2. 在缺乏持续性中长期趋势的情况下，原本可观的浮盈往往因平仓过晚而回吐甚至转为亏损。

![image.png](image.png)

### 2.2 优化趋势线
为了适应市场变异，我们对趋势线的回溯期进行了参数优化（区间100-400，步长20）。

**核心发现**：
- 参数平稳区：BTC的最佳区间在300-400，而ETH则在180-260。
- 扫描上限设定为400（约66天），旨在捕捉持续数周的中期趋势。
- 结果：交易次数减少，最长连续亏损从19次降至14次，策略的**鲁棒性**初步增强。

![image.png](image_1.png)
![image.png](image_2.png)

### 2.3 引入波动性滤波器
趋势策略最怕的是“窄幅震荡”。我们引入了基于ATR标准化的**价格偏离度**作为过滤器。

**逻辑描述**：
只有当价格偏离趋势线的程度超过一定阈值（即波动率足够大）时才允许进场，目的是过滤那些无法形成突破的噪音。

**测试结果**：
虽然在样本外表现提升有限，但波动性滤波器显著降低了最长回撤周数（降至11周），并有效减少了震荡市中的无谓磨损。考虑到其对风险控制的正面作用，我们决定保留该机制。

![image.png](image_3.png)
![image.png](image_4.png)

### 2.4 风险控制：固定止损与盈亏平衡
**固定止损**：使用 `k * ATR(100)` 设定宽止损。实验证明，2-5倍的ATR乘数能有效防止在震荡中被扫单。
**盈亏平衡（Breakeven）**：当浮盈达到一定倍数的ATR后，将止损移至成本价。

**改进效果**：
盈亏平衡机制将胜率拉升至 50%，最长连续亏损从17笔骤降至10笔。这种机制极大地优化了交易者的心理持有成本，是策略从“能盈利”转向“可实盘”的关键。

![image.png](image_5.png)
![image.png](image_6.png)
![image.png](image_7.png)

### 2.5 优化空头平仓
加密货币市场多空特征明显不对称：**空头行情通常暴烈且短暂**。

**优化逻辑**：
针对空头交易增加“分段平仓”机制。当标准化浮盈达到阈值时，先行平仓50%锁定利润，剩余头寸再根据趋势反转信号离场。

**回测结果**：
该改进进一步提升了年化收益和夏普比率。空头分段平仓虽然在极端的单边熊市中会牺牲部分利润，但在更常见的“宽幅震荡下行”中表现更为优越。

![image.png](image_8.png)
![image.png](image_9.png)

### 2.6 资金管理：固定风险头寸法
最终，我们采用**固定风险头寸法**（每笔交易承担2%的净值风险）。

**最终表现**：
最大回撤控制在 **7.7%**，PRR达到 **2.0**，年化夏普比率稳步提升至 **1.30**。这标志着该策略已具备优秀的风险调整后收益能力。

![image.png](image_10.png)

## 3. 测试结果汇总

以下是策略在各迭代阶段的详细业绩指标对比：

| 业绩指标 | 基础策略 | 优化趋势线| 波动性滤波器| 固定止损| 盈亏平衡| 优化空头平仓| 资金管理|
| --- | --- | --- | --- | --- | --- | --- | --- |
| 最大回撤 | 7.8% | 10.1% | 8.5% | 7.7% | 7.3% | 6.5% | 7.7% |
| MAE | 14.1% | 22.5% | 22.5% | 22.2% | 22.7% | 21.6% | 12.7% |
| 最长回撤周数 | 12 | 33 | 11 | 21 | 20 | 13 | 22 |
| 交易次数 | 443 | 353 | 301 | 317 | 425 | 657 | 657 |
| 每周交易 | 2 | 1 | 1 | 1 | 1 | 2 | 2 |
| 胜率 | 26.4% | 26.3% | 29% | 27.4% | 50.1% | 49.6% | 49.6% |
| 最长连续亏损 | 19 | 14 | 16 | 17 | 10 | 16 | 16 |
| 年收益率 | 216% | 178% | 198% | 210% | 213% | 232% | 48% |
| 盈利因子 | 1.76 | 1.83 | 1.86 | 1.85 | 1.77 | 1.82 | 2.20 |
| PRR | 1.51 | 1.55 | 1.56 | 1.55 | 1.54 | 1.63 | 1.97 |
| 夏普比率 | 1.09 | 1.02 | 1.02 | 1.01 | 0.97 | 1.05 | 1.30 |
| R2 | 44% | 56% | 65% | 56% | 66% | 76% | 94% |
| 平均回撤 | 4.7% | 6.8% | 6.4% | 6.6% | 7.0% | 6.2% | 4.8% |
| BTC PF | 1.51 | 1.77 | 1.82 | 1.82 | 1.94 | 1.99 | 2.72 |
| ETH PF | 1.99 | 1.88 | 1.89 | 1.87 | 1.66 | 1.72 | 1.88 |

## 4. 稳健性检验 (WFO)

为了验证策略的鲁棒性，我们进行策略表现对WFO参数的敏感性分析，训练集比例保持在85%。

- **固定资金测试**：WFO周期在14-24之间时，PRR稳定在1.6-1.8的高位。
- **固定风险测试**：WFO周期在10-22之间时，PRR进一步提升至1.8-2.0。

结论：**策略通过了稳健性检验**。建议每5个月重新训练一次，WFO周期数设为15。

![image.png](image_11.png)
![image.png](image_12.png)

## 5. 总结

**研究结论**：
1. **低通滤波器 + 模糊逻辑** 是划分趋势与震荡的强大工具。
2. **非对称平仓** 与 **盈亏平衡机制** 是提升策略胜率和生存率的核心要素。
3. 波动性滤波器在抑制噪音方面表现出色，有效缩短了回撤周期。

**改进方向**：策略在面对“短期剧烈波动但无长期趋势”的行情时无法盈利。未来的优化方向将聚焦于**短期趋势的平仓时机优化**，以及引入更多元的相关性滤波器来应对极端的黑天鹅事件。

## 附录：Zorro 源代码

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

function tradeStrategy() {
    // ---------------------------------------------------------
    // 参数设置
    // ---------------------------------------------------------
    int TrendPeriod = round(optimize(200,100,400,20));
    var FuzzyFactor = 0.1;
    var EntryProbThreshold = 0.6;
    var VolaThreshold = optimize(0,0,2,0.2);
    var AtrStopFactor = optimize(0,1,5,0.5);
    var AtrTrailFactor = optimize(0,1,5,0.5);
    var ShortProfitThreshold = optimize(0,3,15,1);
    var FixedCapital = 0;
    var FixedRisk = 0.02;

    // ---------------------------------------------------------
    // 指标计算
    // ---------------------------------------------------------
    vars Prices = series(price());
    vars Trends = series(LowPass(Prices, TrendPeriod));
    vars Cycles = series(fisherTransform(Prices, 10));
    var ATR100 = ATR(100);
    var Deviation = abs(Prices[0] - Trends[0]) / ATR100;

    var LongNormalizedProfit = getLongNormalizedProfit(ATR100);
    var ShortNormalizedProfit = getShortNormalizedProfit(ATR100);

    // ---------------------------------------------------------
    // 交易信号
    // ---------------------------------------------------------
    FuzzyRange = FuzzyFactor*ATR100;
    var RisingProb = risingF(Trends);
    var FallingProb = fallingF(Trends);

    bool LongConditionBase = RisingProb >= EntryProbThreshold;
    bool LongMomentumRising = Cycles[0] < 4. && rising(Cycles);
    bool LongEntry = LongConditionBase && LongMomentumRising;
    bool LongExit = peak(Trends);

    bool ShortConditionBase = FallingProb >= EntryProbThreshold;
    bool ShortMomentumRising = Cycles[0] > -4. && falling(Cycles);
    bool ShortEntry = ShortConditionBase && ShortMomentumRising;
    bool ShortExit = valley(Trends);

    if(VolaThreshold > 0) {
        LongEntry = LongEntry && Deviation >= VolaThreshold;
        ShortEntry = ShortEntry && Deviation >= VolaThreshold;
    }

    // ---------------------------------------------------------
    // 状态管理：再进场限制 (AlgoVar[0])
    // ---------------------------------------------------------

    // 触发部分止盈后，开始跟踪跟踪剩余头寸，并进入观望期
    if(AlgoVar[0] == 1) {
        // 限制进场
        ShortEntry = false;

        // 管理剩余持仓：锁定 10% 利润
        for(current_trades) {
            if(TradeIsOpen && TradeIsShort) {
                TradeTrailLock = 0.1;
            }
        }

        // 解锁条件：空仓且趋势反转
        if(NumOpenShort == 0) {
            if(peak(Trends) || valley(Trends)) {
                AlgoVar[0] = 0; // 允许下一波行情进场
            }
        }
    }

    // ---------------------------------------------------------
    // 风控
    // ---------------------------------------------------------
    Stop = AtrStopFactor*ATR100;
    Trail = AtrTrailFactor*ATR100;
    TrailLock = 10;
    TrailSlope = 0;

    // ---------------------------------------------------------
    // 资金管理
    // ---------------------------------------------------------
    Lots = 100;
    var MinLots = getMinLots();
    if(!Train && FixedCapital > 0)
        Lots = floor(FixedCapital/priceC()/LotAmount);
    if(!Train && Capital > 0 && FixedRisk > 0 && AtrStopFactor > 0)
        Lots = fixedRiskLots(FixedRisk);
    if(Lots < MinLots) Lots = MinLots;

    // ---------------------------------------------------------
    // 订单管理
    // ---------------------------------------------------------
    if(NumOpenLong > 0 && LongExit)
        exitLong();
    if(NumOpenShort > 0 && ShortExit)
        exitShort();
    if(NumOpenLong == 0 && LongEntry)
        enterLong();
    if(NumOpenShort == 0 && ShortEntry) {
        if(ShortProfitThreshold > 0)
            enterShortMultipleOrders(2, MinLots);
        else
            enterShort();
    }

    // 空头部分止盈逻辑
    if(ShortProfitThreshold > 0 && NumOpenShort > 0 && AlgoVar[0] == 0) {
        if(ShortNormalizedProfit >= ShortProfitThreshold) {
            // 平仓50%
            exitProfitShortOrders(1);
            // 标记进入剩余头寸管理模式
            AlgoVar[0] = 1;
        }
    }

    // ---------------------------------------------------------
    // 绘图
    // ---------------------------------------------------------
    if((Test && !is(LOOKBACK)) || Live) {
        plot2("Trend", Trends[0], MAIN, rising(Trends), GREEN, RED);

        var BullishState = ifelse(LongConditionBase, 1, 0);
        var BearishState = ifelse(ShortConditionBase, 1, 0);
        plot("BullishState", BullishState, NEW|BARS, GREEN+TRANSP);
        plot("BearishState", BearishState, 0|BARS, RED+TRANSP);
        plot("RisingProb", RisingProb, 0|LINE, BLUE);
        plot("BullT", EntryProbThreshold, 0, GREY);
        plot("BearT", 1-EntryProbThreshold, 0, GREY);

        plot("Cycle", Cycles, NEW, RED);
        plot("Cycle0", 0, 0, GREY);
        plot("Cycle+", 2, 0, GREY);
        plot("Cycle-", -2, 0, GREY);
        plot("Cycle++", 4, 0, GREY);
        plot("Cycle--", -4, 0, GREY);

        if(VolaThreshold > 0) {
            var HighVolaBar = ifelse(Deviation >= VolaThreshold, Deviation, 0);
            var LowVolaBar = ifelse(Deviation < VolaThreshold, Deviation, 0);
            plot("HighVola", HighVolaBar, NEW|BARS, BLUE);
            plot("LowVola", LowVolaBar, 0|BARS, BLUE+TRANSP);
            plot("VolaThreshold", VolaThreshold, 0, GREY);
        }

        if(ShortProfitThreshold > 0) {
            plot("LongProfit", LongNormalizedProfit, NEW|BARS, GREEN+TRANSP);
            plot("ShortProfit", ShortNormalizedProfit, 0|BARS, RED+TRANSP);
            plot("ShortProfitT", ShortProfitThreshold, 0, RED);
        }

        if(AtrStopFactor > 0 && NumOpenTotal > 0) {
            var CurrentStop = 0;
            for(current_trades) {
                CurrentStop = (var)TradeStopLimit;
                break_trades;
            }
            if(CurrentStop > 0) plot("Stop", CurrentStop, MAIN|DOT, LIGHTBLUE);
        }
    }
}

function run() {
    // --------------------------------------------------------- //
    // Zorro 设置
    // --------------------------------------------------------- //

    // 日志
    set(LOGFILE);
    Verbose = 3;

    // 图表
    set(PLOTNOW);
    setf(PlotMode,PL_DIFF);
    PlotScale = 8;
    PlotHeight2 = 320;

    // 训练
    set(PARAMETERS);
    setf(TrainMode,TRADES);
    DataSplit = 85;
    NumWFOCycles = 15;
    NumCores = 4;

    // k线生成规则，7*24交易
    resf(BarMode,BR_WEEKEND);
    StartWeek = 0;
    EndWeek = 62359;
    StartMarket = 0;
    EndMarket = 2359;
    BarPeriod = 240;
    BarZone = UTC;
    BarOffset = 0;
    TickFix = 60000;
	  if(Live) TickFix = 0;

    // 测试样本
    StartDate = 20170101;
    EndDate = 20251230;
    LookBack = 1000;

    // 初始资本
    if(Train) Capital = 0;
    if(Test) Capital = 10000;
    if(Live) Capital = 0;

    // 下一根k线开盘时进场/平仓
    Fill = 3;

    // --------------------------------------------------------- //
    // 交易策略
    // --------------------------------------------------------- //

    while(asset(loop("BTCUSDT","ETHUSDT"))) {
        Leverage = 10;
        MarginCost = priceClose()*LotAmount/Leverage;
        tradeStrategy();
    }
}
```


---

> 作者: [量化炼金](https://codealchemy.blog.csdn.net/)  
> URL: http://localhost:1313/posts/lowpass-4h-strategy/  

