# 多维共振还是噪音叠加？诺贝尔预测模型的“多周期”实战折戟与深度反思


在[上一篇文章](/posts/nobel-prediction-model/)中，我们致敬了2024年诺贝尔物理学奖，通过模拟神经网络的“记忆与检索”机制，构建了一个基于皮尔逊相关系数的模式识别模型。该模型在捕捉单周期（如4小时）的局部形态上展现了一定的统计优势，但也暴露出在震荡行情中容易被噪音误导的弱点。

在量化交易中，“多周期共振”常被视为过滤噪音、确认趋势的圣杯。本篇研究将尝试把该核心算法推向更高维度：通过同时监控从 15 分钟到日线级别的五个时间周期，构建一套“共识评分系统”。我们试图回答一个核心问题：如果多个时间维度的“记忆”同时告诉我们市场要上涨，胜率是否会产生质的飞跃？

## 1. 多周期共识评分

为了将不同维度的预测逻辑聚合为统一的交易信号，我们设计了一套共识评分算法。其核心逻辑如下：

### 1.1 独立记忆，多维检索
系统为15分钟、30分钟、1小时、四小时图、日图每个周期独立建立模式识别模型。这意味着每个周期都有自己独立的“记忆库”和相似度度量标准。

### 1.2 置信度阈值过滤
并非所有的预测都值得参考。只有当某个周期的预测置信度 `Confidence > 60` 时，其信号才会被纳入统计。
- **看涨信号**：`is_bullish` 为真，评分 +1。
- **看跌信号**：`is_bullish` 为假，评分 -1。

### 1.3 信号合成与进场规则
将五个周期的评分累加，得到最终的 **`consensus_score`**（取值范围 [-5, +5]）：
- **多头进场**：当共识分 ≥ 3（暗示至少 3 个周期同时看涨且信号强烈）。
- **空头进场**：当共识分 ≤ -3。
- **平仓逻辑**：当共识分回归至 0 附近时，认为多空力量平衡，强制平仓。

这种“等权重”分配分数的做法虽然简单，但它能最直观地测试出模式识别算法在不同时间尺度下的通用性。

## 2. 代码实现：Zorro (Lite-C) 

在 Zorro 平台中实现多周期逻辑，难点在于如何优雅地在不同时间周期（TimeFrame）之间切换并保持数据的一致性。以下代码展示了如何利用二维数组管理不同周期的记忆库，并利用 `frameSync` 函数实现精确的信号共振。

```c
// =========================================================
// Nobel Predictor - Multi-Timeframe Implementation
// Timeframes: M15, M30, H1, H4, D1
// =========================================================

// --- 常量定义 ---
#define PATTERN_LEN 10   // 模式长度
#define MAX_PATTERNS 50  // 每个周期的记忆库容量
#define MAX_SIMILAR 10   // 搜索相似模式数量
#define NUM_TFS 5        // 时间周期数量 (M15, M30, H1, H4, D1)

// --- 数据结构 ---

// 模式结构体
typedef struct {
    var values[PATTERN_LEN];  // 归一化形态
    var result;               // 结果 (相对于起点的涨跌幅)
    var time;                 // 发生时间
    int confidence;           // 置信度
    bool validated;           // 验证标记
} Pattern;

// 预测结果结构体
typedef struct {
    var predicted_change_pct; // 预测下一根K线的涨跌幅 (用于显示)
    var raw_weighted_change;  // 结构性趋势强度 (核心指标)
    var predicted_price;      // 预测绝对价格
    var confidence;           // 置信度
    bool is_bullish;          // 结构是否看涨
    int found_count;          // 找到的相似模式数
} PredictionResult;

// --- 全局变量 ---

// 周期定义 (单位: 分钟)
// Base Period 将设为 15 分钟
int g_tfPeriods[NUM_TFS] = {15, 30, 60, 240, 1440};
string g_tfNames[NUM_TFS];

// 记忆库：第一维是周期索引，第二维是模式索引
Pattern g_patterns[NUM_TFS][MAX_PATTERNS];

// 计数器：每个周期独立计数
int g_patternCounts[NUM_TFS];

// 预测结果：每个周期独立的预测
PredictionResult g_predictions[NUM_TFS];

// --- 核心函数 ---

// 提取模式
void extract_pattern(Pattern* p, int offset)
{
    int base_idx = offset + PATTERN_LEN - 1;
    var base_price = priceClose(base_idx);

    if(base_price <= 0) return;

    int i;
    for(i = 0; i < PATTERN_LEN; i++)
    {
        int price_idx = offset + (PATTERN_LEN - 1) - i;
        var current_price = priceClose(price_idx);
        p->values[i] = (current_price - base_price) / base_price * 100.0;
    }
}

// 计算模式相似度
var calculate_similarity(var* p1, var* p2)
{
    var sum1 = 0, sum2 = 0, sumProd = 0;
    var sumSq1 = 0, sumSq2 = 0;
    int i;
    for(i = 0; i < PATTERN_LEN; i++) {
        var v1 = p1[i]; var v2 = p2[i];
        sum1 += v1; sum2 += v2;
        sumSq1 += v1*v1; sumSq2 += v2*v2;
        sumProd += v1*v2;
    }
    var n = (var)PATTERN_LEN;
    var numerator = n * sumProd - sum1 * sum2;
    var denom = sqrt((n * sumSq1 - sum1 * sum1) * (n * sumSq2 - sum2 * sum2));
    if(denom < 0.0001) return 0;
    return (numerator / denom + 1.0) / 2.0;
}

// 清理旧模式，防止内存溢出
void cleanup_patterns(int tf_idx)
{
    int keep_count = MAX_PATTERNS / 2;
    int remove_count = g_patternCounts[tf_idx] - keep_count;
    if(remove_count <= 0) return;

    int i;
    for(i = 0; i < keep_count; i++)
    {
        int src_idx = remove_count + i;
        // 注意：访问二维数组
        if(src_idx < g_patternCounts[tf_idx])
             memcpy(&g_patterns[tf_idx][i], &g_patterns[tf_idx][src_idx], sizeof(Pattern));
    }
    g_patternCounts[tf_idx] = keep_count;
}

// 更新指定周期的模式库
void update_patterns(int tf_idx)
{
    // 访问特定周期的计数器
    if(g_patternCounts[tf_idx] >= MAX_PATTERNS - 5) {
        cleanup_patterns(tf_idx);
    }

    int learn_offset = 1;
    if(LookBack < PATTERN_LEN + learn_offset + 5) return;

    Pattern newPat;
    extract_pattern(&newPat, learn_offset);

    int base_idx = learn_offset + PATTERN_LEN - 1;
    var base_price = priceClose(base_idx);
    var current_close = priceClose(0);

    if(base_price <= 0) return;

    newPat.result = (current_close - base_price) / base_price * 100.0;
    newPat.time = wdate(learn_offset);
    newPat.confidence = 0;
    newPat.validated = false;

    if(g_patternCounts[tf_idx] < MAX_PATTERNS) {
        // 存入二维数组
        memcpy(&g_patterns[tf_idx][g_patternCounts[tf_idx]], &newPat, sizeof(Pattern));
        g_patternCounts[tf_idx]++;
    }
}

// 预测指定周期的下一根K线
void predict_next_bar(int tf_idx)
{
    // 重置当前周期的预测结果
    g_predictions[tf_idx].predicted_change_pct = 0;
    g_predictions[tf_idx].confidence = 0;
    g_predictions[tf_idx].is_bullish = false;
    g_predictions[tf_idx].found_count = 0;
    g_predictions[tf_idx].raw_weighted_change = 0;

    Pattern currentPat;
    extract_pattern(&currentPat, 0);

    int indices[MAX_SIMILAR];
    var similarities[MAX_SIMILAR];
    int foundCount = 0;

    // 遍历当前周期的模式库
    int i;
    for(i = g_patternCounts[tf_idx] - 1; i >= 0; i--)
    {
        if(foundCount >= MAX_SIMILAR) break;
        var sim = calculate_similarity(currentPat.values, g_patterns[tf_idx][i].values);
        if(sim > 0.7) {
            indices[foundCount] = i;
            similarities[foundCount] = sim;
            foundCount++;
        }
    }

    g_predictions[tf_idx].found_count = foundCount;
    if(foundCount < 3) return;

    var totalWeightedChange = 0;
    var totalWeight = 0;
    int countPositive = 0;
    int countNegative = 0;

    for(i = 0; i < foundCount; i++)
    {
        int idx = indices[i];
        var weight = similarities[i];
        var result = g_patterns[tf_idx][idx].result;

        totalWeightedChange += result * weight;
        totalWeight += weight;

        if(result > 0.01) countPositive++;
        else if(result < -0.01) countNegative++;
    }

    if(totalWeight > 0)
        g_predictions[tf_idx].raw_weighted_change = totalWeightedChange / totalWeight;

    g_predictions[tf_idx].is_bullish = (countPositive > countNegative) && (g_predictions[tf_idx].raw_weighted_change > 0.01);

    var consensus = 0;
    int stronger_side = max(countPositive, countNegative);
    if(foundCount > 0) consensus = (var)stronger_side / foundCount * 100.0;
    var coverage = (var)foundCount / MAX_SIMILAR * 100.0;

    g_predictions[tf_idx].confidence = (consensus * 0.7 + coverage * 0.3);

    // 计算隐含的下一根K线涨跌
    var current_base = priceClose(PATTERN_LEN - 1);
    g_predictions[tf_idx].predicted_price = current_base * (1.0 + g_predictions[tf_idx].raw_weighted_change / 100.0);
    var current_price = priceClose(0);
    if(current_price > 0)
        g_predictions[tf_idx].predicted_change_pct = (g_predictions[tf_idx].predicted_price - current_price) / current_price * 100.0;
}

void print_dashboard()
{
    if(!is(LOOKBACK)) {
        print(TO_WINDOW, "\n\n=== NOBEL MULTI-TF DASHBOARD ===");
        print(TO_WINDOW, "\nTF   | DIR  | CONF | STRUCT | NEXT");
        print(TO_WINDOW, "\n-----------------------------------");

        int i;
        for(i=0; i<NUM_TFS; i++) {
            string dir = "---";
            if(g_predictions[i].confidence > 0)
                dir = ifelse(g_predictions[i].is_bullish, "BULL", "BEAR");

            print(TO_WINDOW, "\n%s  | %s | %3.0f%% | %+5.2f%% | %+5.2f%%",
                g_tfNames[i],
                dir,
                g_predictions[i].confidence,
                g_predictions[i].raw_weighted_change,
                g_predictions[i].predicted_change_pct
            );
        }
    }
}

// --------------------------------------------------------- //
// 主程序
// --------------------------------------------------------- //

function run()
{
    // 日志
    set(LOGFILE, PLOTNOW);
    Verbose = 0;
    PlotScale = 8;
    PlotHeight2 = 320;

    // k线生成规则，7*24交易
    resf(BarMode,BR_WEEKEND);
    StartWeek = 0;
    EndWeek = 62359;
    StartMarket = 0;
    EndMarket = 2359;
    BarPeriod = 15;  // 最小周期设为15分钟
    BarZone = UTC;
    BarOffset = 0;
    TickFix = 60000;

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

    // 样本
    StartDate = 20210101;
    EndDate = 20251230;
    LookBack = 5000; // 至少需要2000根15分钟k线才能生成日图信号

    // 设置资产
    asset("BTCUSDT");

    // 初始化设置
    if(is(INITRUN)) {
        g_tfNames[0] = "M15";
        g_tfNames[1] = "M30";
        g_tfNames[2] = "H1";
        g_tfNames[3] = "H4";
        g_tfNames[4] = "D1";
    }

    // --- 多周期循环逻辑 ---

    int i;
    for(i = 0; i < NUM_TFS; i++)
    {
        // 计算当前周期相对于 BarPeriod (15m) 的倍数
        // M15=1, M30=2, H1=4, H4=16, D1=96
        int frame_multiplier = g_tfPeriods[i] / BarPeriod;

        // 切换时间帧
        TimeFrame = frameSync(frame_multiplier);

        // 在当前 TimeFrame 下运行逻辑
        if(TimeFrame) {
            update_patterns(i);
            predict_next_bar(i);
        }
    }

    // 恢复到主周期 (M15)
    TimeFrame = 1;

    // 核心参数
    var score_threshold = 4;

    // 计算共识分
    var consensus_score = 0;
    for(i = 0; i < NUM_TFS; i++) {
        // 过滤掉置信度太低的信号
        if(g_predictions[i].confidence > 70) {
            if(g_predictions[i].is_bullish)
                consensus_score += 1;
            else
                consensus_score -= 1;
        }
    }

    // 信号
    bool LongEntry =  consensus_score >= score_threshold;
    // bool LongEntry = consensus_score >= score_threshold && g_predictions[4].raw_weighted_change > 0;
    bool LongExit = consensus_score <= 0;

    bool ShortEntry = consensus_score <= -score_threshold;
    // bool ShortEntry = consensus_score <= -score_threshold && g_predictions[4].raw_weighted_change < 0;
    bool ShortExit = consensus_score >= 0;

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

    // 绘图
    plot("Score", consensus_score, NEW|BARS, BLUE+TRANSP);
    plot("Score+", score_threshold, 0, GREEN);
    plot("Score-", -score_threshold, 0, RED);
}
```

## 3. 实战回测

我们选择了 BTC/USDT 作为测试标的，时间跨度覆盖了 2021 年至 2025 年（包含大牛市、深熊以及极端的震荡行情）。使用 WFA 进行 10 轮滚动回测，以确保结果不被特定行情误导。

测试结果令人失望。

![image.png](image.png)

- 盈利因子：仅为 **0.72**（理想值应 > 1.5）。
- PRR (Pessimistic Return Ratio)：**0.67**。
- 交易频率：每周约 14 笔交易，平均每天 2 笔。
- 最大连亏：高达 **18 次**。

为什么多周期共振失效了？

1. 交易成本过高：由于我们使用了15分钟图作为基础周期，模型捕获了大量的日内微小波动。即使不计算滑点和佣金，策略也仅能维持盈亏平衡；一旦计入实际交易成本，净值曲线便会迅速崩塌。
2. 震荡行情的持续亏损：模式识别算法对“形态转变点”极度敏感。在窄幅震荡行情中，模型会频繁在各个周期识别出虚假的看涨或看跌模式，导致 `consensus_score` 在阈值附近反复横跳，频繁进场又频繁止损。
3. 等权重分配：模型简单地给15分钟图和日图分配了同样的权重。在实际交易中，小周期的信号往往只是噪音，而大周期的信号才代表真正的趋势方向。这种权重的均等化实际上放大了噪音。

> **风险提示**：本文所有回测结果仅供研究参考，不构成任何投资建议。量化交易具有高风险，请谨慎入市。


---

> 作者: [量化炼金](https://codealchemy.blog.csdn.net/)  
> URL: http://localhost:1313/posts/nobel-prediction-model-part2/  

