# 致敬2024诺贝尔物理学奖：构建具有“市场记忆”的量化预测模型


## 基于模式识别与多周期共振的交易策略研究

### 1. 当金融市场拥有“记忆”

2024年诺贝尔物理学奖授予了在人工神经网络和机器学习领域做出奠基性贡献的科学家。其核心思想之一是系统如何通过存储和检索模式来表现出“记忆”。在量化交易领域，我们长期存在一个核心假设：**历史会重演**。

如果金融市场不仅是随机游走，而是一个具有记忆的复杂动力学系统，那么当前的价格走势（Pattern）如果在历史上曾多次出现，其后的演化路径是否也具有统计上的相似性？本文将复现一种受此启发的“诺贝尔预测模型”，利用皮尔逊相关系数（Pearson Correlation）和动态模式库，构建一个不依赖传统参数训练、具备自我演化能力的交易系统。

### 2. 核心算法逻辑：模式的检索与共识
该系统的核心逻辑可以拆解为以下四个步骤：

1.  **形态提取与归一化**：提取最近10根K线的价格走势。为了消除绝对价格的影响，我们以窗口内最旧的价格为基准进行百分比归一化处理。
2.  **相似度计算**：利用**皮尔逊相关系数**对比当前形态与历史存储的50个模式。相关系数越高，代表两者的走势形状越接近。
3.  **模式记忆库**：系统并非静态，它会自动保存新发生的模式，并动态淘汰旧模式。这种机制确保了模型能够捕捉到市场最新的特征。
4.  **多周期共识预测**：在多个时间周期（如5分钟, 15分钟, 1小时, 4小时）独立进行模式识别。当多个周期同时发出强烈的方向信号时，预测的置信度最高。

**架构优势**：
*   **拒绝过拟合**：系统不进行权重训练，只存储真实发生的历史轨迹。
*   **动态适应**：根据预测表现动态调整模式的置信度评分，自动“学习”哪些历史模式在当前环境下更有效。

### 3. 代码实现：基于 Zorro (Lite-C) 的复现

我们使用 Zorro 平台进行策略复现。首先，定义存储模式和预测结果的核心数据结构。

#### 3.1 定义数据结构
```c
// 参数常量
#define PATTERN_LEN 10   // 模式长度：过去10跟k线
#define MAX_PATTERNS 50  // 记忆库容量：最多存50个模式

// 定义模式结构体
typedef struct {
    var values[PATTERN_LEN];  // 存储归一化价格形态
    var result;               // 结果：该模式发生后下一根k线的涨跌幅（%）
    var time;                 // 时间戳：记录该模式发生的具体时间
    int confidence;           // 置信度：预测正确与否的评分
    bool validated;           // 标记：是否已经经过验证
} Pattern;

// 定义预测结果结构体
typedef struct {
    var predicted_change_pct; // 相对于当前价格的预测涨跌幅
    var raw_weighted_change;  // 加权结果 (相对于模式起点)
    var predicted_price;      // 预测的绝对价格
    var confidence;           // 置信度（0-100）
    bool is_bullish;          // 是否看涨
    int found_count;          // 找到了多少个相似模式
} PredictionResult;

// 全局变量
Pattern g_patterns[MAX_PATTERNS];   // 全局数组存储历史模式结构体
int g_patternCount = 0;             // 目前记录的历史模式数量
PredictionResult g_lastPrediction;  // 预测结果
```

#### 3.2 价格归一化处理
为了让不同时期的价格具有可比性，我们需要将 10 根 K 线的收盘价映射为相对于起始点的百分比变化。
```c
/**
 * 从价格序列中提取模式并归一化
 * @param p      指向目标 Pattern 结构体的指针
 * @param offset 偏移量
 *               offset = 0 -> 提取 [LookBack-9] ... [LookBack] (包含 priceClose(0))
 *               offset = 1 -> 提取 [LookBack-10] ... [LookBack-1] (包含 priceClose(1))
 */
void extract_pattern(Pattern* p, int offset)
{
    // 确定基准价格 (Base Price)
    // 模式中最旧的一根K线作为基准
    // 如果 offset=0 (最新模式: 0..9), 基准是 priceClose(9)
    int base_idx = offset + PATTERN_LEN - 1;
    var base_price = priceClose(base_idx);

    int i;
    for(i = 0; i < PATTERN_LEN; i++)
    {
        // i=0 (最旧) -> price_idx = offset + 9
        // i=9 (最新) -> price_idx = offset + 0
        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;
    }
}
```

#### 3.3 相似度度量：皮尔逊相关系数
我们使用皮尔逊相关系数来衡量形态的相似性，并将其结果映射到 `[0, 1]` 区间，方便后续计算加权权重。
```c
/**
 * 计算皮尔逊相关系数
 */
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;

    var correlation = numerator / denom;
    return (correlation + 1.0) / 2.0; // 映射到 0-1
}
```

#### 3.4 模式库的更新与预测
系统在每一根 K 线收盘时，都会学习刚完成的模式（Bar 1 -> Bar 0 的演化），并利用当前形态（Bar 0）去匹配历史，预测下一根 K 线（Bar -1）。

```c
/**
 * 更新模式库
 * 在 Bar 0 收盘时调用。
 * 我们学习的是：Bar 1 的形态 -> 导致了 Bar 0 的结果。
 */
void update_patterns()
{
    // 清理旧模式
    if(g_patternCount >= MAX_PATTERNS - 5) {
        cleanup_patterns();
    }

    // 设置学习偏移量
    // 我们需要提取截止到 priceClose(1) 的模式
    int learn_offset = 1;

    // 安全检查
    if(LookBack < PATTERN_LEN + learn_offset + 5) return;

    Pattern newPat;

    // 提取形态 (priceClose(10) ... priceClose(1))
    extract_pattern(&newPat, learn_offset);

    // 计算结果
    // 结果：priceClose(0) 相对于 模式基准价(priceClose(10)) 的涨跌幅
    // 这样保持了与 extract_pattern 中归一化逻辑的一致性

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

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

    // 保存到全局记忆库
    if(g_patternCount < MAX_PATTERNS) {
        memcpy(&g_patterns[g_patternCount], &newPat, sizeof(Pattern));
        g_patternCount++;
    }
}

/**
 * 预测下一根 K 线
 * 基于当前 Bar 0 的形态，预测 Bar -1
 */
void predict_next_bar()
{
    g_lastPrediction.predicted_change_pct = 0;
    g_lastPrediction.confidence = 0;
    g_lastPrediction.is_bullish = false;
    g_lastPrediction.found_count = 0;

    // 提取当前形态 (priceClose(9) ... priceClose(0))
    Pattern currentPat;
    extract_pattern(&currentPat, 0);

    // 搜索相似模式
    int indices[MAX_SIMILAR];
    var similarities[MAX_SIMILAR];
    int foundCount = 0;

    int i;
    for(i = g_patternCount - 1; i >= 0; i--)
    {
        if(foundCount >= MAX_SIMILAR) break;

        var sim = calculate_similarity(currentPat.values, g_patterns[i].values);

        if(sim > 0.7) {
            indices[foundCount] = i;
            similarities[foundCount] = sim;
            foundCount++;
        }
    }

    g_lastPrediction.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[idx].result; // 这是相对于 Base 的结果

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

        // 只要最终价格高于 Base (0.01%)，就算 Positive
        // 即使下一根K线是跌的，只要还在 Base 之上，这里也会 +1
        if(result > 0.01) countPositive++;
        else if(result < -0.01) countNegative++;
    }

    // 计算原始加权结果 (相对于 Base)
    if(totalWeight > 0)
        g_lastPrediction.raw_weighted_change = totalWeightedChange / totalWeight;
    else
        g_lastPrediction.raw_weighted_change = 0;

    // 确定方向
    // 当大多数相似模式都保持在 Base 之上，且加权平均值也 > 0.01% 时，看涨
    g_lastPrediction.is_bullish = (countPositive > countNegative) && (g_lastPrediction.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_lastPrediction.confidence = (consensus * 0.7 + coverage * 0.3);

    // 预测的绝对价格
    // Base 是当前模式的起点 (priceClose(9))
    var current_base = priceClose(PATTERN_LEN - 1);
    g_lastPrediction.predicted_price = current_base * (1.0 + g_lastPrediction.raw_weighted_change / 100.0);

    // 计算相对于当前价格 (priceClose(0)) 的涨跌幅
    var current_price = priceClose(0);
    if(current_price > 0)
        g_lastPrediction.predicted_change_pct = (g_lastPrediction.predicted_price - current_price) / current_price * 100.0;
}
```

### 4. 如何量化“置信度”？
在量化模型中，单一的预测结果往往是不够的，我们需要知道模型对这个结果有多大的把握。本模型通过两个维度来构建置信度评分（0-100）：

1.  **共识分 (Consensus, 权重 70%)**：
    在所有搜寻到的相似历史模式中，意见的一致程度。例如，找到了 10 个相似模式，如果 8 个都看涨，共识分为 80%。
2.  **覆盖分 (Coverage, 权重 30%)**：
    匹配到的模式数量占预设上限（10个）的比例。如果只找到了 2 个相似模式，即使它们意见一致，其覆盖分也较低（20%），暗示该形态在历史上较为罕见，参考价值有限。

**综合置信度计算公式**：
> `Confidence = (共识分 * 0.7) + (覆盖分 * 0.3)`


### 5. 回测表现分析：BTC/USDT 4小时图

我们选取了 BTCUSDT 交易对在 4 小时周期上的表现进行观察。测试样本选择2018-2025年，滚动划分10轮训练集/测试集，训练集比例是85%。

#### 5.1 信号观察

如下图所示，系统生成的预测信号分为看涨（绿色圆点）和看跌（红色圆点）。

![image.png](image.png)

*   **趋势追踪能力**：在强趋势行情中，置信度通常会大幅提升，信号表现出较强的持续性。
*   **震荡噪音**：在窄幅横盘或震荡行情中，模型容易出现频繁切换方向的情况，这是所有模式匹配类算法的固有弱点。
*   **预测矛盾**：有时看涨方向与下一根 K 线的预测涨跌幅看似矛盾。这源于算法的设计逻辑：它预测的是相对于模式起点（10 根 K 线前）的结构性位置，而非仅仅下一根 K 线的简单跳动。

#### 5.2 策略初步测试

我们设计了一个简单的基于置信度的交易策略：
*   **做多**：置信度 > 70 且看涨。
*   **做空**：置信度 > 70 且看跌。
*   **风险管理**：使用 ATR 动态止损止盈。

![image.png](image_1.png)

回测结论：
1.  盈亏平衡：初步测试显示单周期策略尚未实现盈利，但它表现出了优秀的趋势捕捉潜力。
2.  震荡市亏损：在横盘期间，尤其是窄幅盘整阶段，模型会失效，经常出现连续亏损。
3.  参数稳定性：置信度阈值在 70-80 之间表现稳健，这印证了该模型在高质量信号识别上的有效性。

### 6. 总结与优化方向

本研究复现了基于物理系统“存储与检索”思想的量化预测模型。通过核心算法的实现，我们验证了：**历史形态确实具有一定的统计预测力**。

未来的优化方向：
1.  **多周期共振**：目前仅在 4H 周期运行。若能将 15M、1H 和 1D 的信号进行加权汇总，当大小周期同时发出“共鸣”时，胜率有望大幅提升。
2.  **波动性滤波器**：引入 ATR 或布林带宽度作为前置条件，在低波动震荡行情中自动“过滤”掉不可信的模式。
3.  **模式多样化**：扩大记忆库容量，并引入衰减机制，赋予更近期的模式更高的权重。

### 附录：完整 Zorro 代码 (Lite-C)
```c
// =========================================================
// Nobel Predictor
// =========================================================

// 参数常量
#define PATTERN_LEN 10   // 模式长度：过去10跟k线
#define MAX_PATTERNS 50  // 记忆库容量：最多存50个模式
#define MAX_SIMILAR 10   // 最多搜索10个相似模式

// 定义模式结构体
typedef struct {
    var values[PATTERN_LEN];  // 存储归一化价格形态
    var result;               // 结果：该模式发生后下一根k线的涨跌幅（%）
    var time;                 // 时间戳：记录该模式发生的具体时间
    int confidence;           // 置信度：预测正确与否的评分
    bool validated;           // 标记：是否已经经过验证
} Pattern;

// 定义预测结果结构体
typedef struct {
    var predicted_change_pct; // 相对于当前价格的预测涨跌幅
    var raw_weighted_change;  // 加权结果 (相对于模式起点)
    var predicted_price;      // 预测的绝对价格
    var confidence;           // 置信度（0-100）
    bool is_bullish;          // 是否看涨
    int found_count;          // 找到了多少个相似模式
} PredictionResult;

// 全局变量
Pattern g_patterns[MAX_PATTERNS];   // 全局数组存储历史模式结构体
int g_patternCount = 0;             // 目前记录的历史模式数量
PredictionResult g_lastPrediction;  // 预测结果

// --------------------------------------------------------- //
// 核心函数实现
// --------------------------------------------------------- //

/**
 * 从价格序列中提取模式并归一化
 * @param p      指向目标 Pattern 结构体的指针
 * @param offset 偏移量
 *               offset = 0 -> 提取 [LookBack-9] ... [LookBack] (包含 priceClose(0))
 *               offset = 1 -> 提取 [LookBack-10] ... [LookBack-1] (包含 priceClose(1))
 */
void extract_pattern(Pattern* p, int offset)
{
    // 确定基准价格 (Base Price)
    // 模式中最旧的一根K线作为基准
    // 如果 offset=0 (最新模式: 0..9), 基准是 priceClose(9)
    int base_idx = offset + PATTERN_LEN - 1;
    var base_price = priceClose(base_idx);

    int i;
    for(i = 0; i < PATTERN_LEN; i++)
    {
        // i=0 (最旧) -> price_idx = offset + 9
        // i=9 (最新) -> price_idx = offset + 0
        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;

    var correlation = numerator / denom;
    return (correlation + 1.0) / 2.0; // 映射到 0-1
}

/**
 * 清理旧模式 (保留最新的 25 个)
 */
void cleanup_patterns()
{
    int keep_count = MAX_PATTERNS / 2;
    int remove_count = g_patternCount - 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_patternCount) {
             memcpy(&g_patterns[i], &g_patterns[src_idx], sizeof(Pattern));
        }
    }
    g_patternCount = keep_count;
}

/**
 * 更新模式库
 * 在 Bar 0 收盘时调用。
 * 我们学习的是：Bar 1 的形态 -> 导致了 Bar 0 的结果。
 */
void update_patterns()
{
    // 清理旧模式
    if(g_patternCount >= MAX_PATTERNS - 5) {
        cleanup_patterns();
    }

    // 设置学习偏移量
    // 我们需要提取截止到 priceClose(1) 的模式
    int learn_offset = 1;

    // 安全检查
    if(LookBack < PATTERN_LEN + learn_offset + 5) return;

    Pattern newPat;

    // 提取形态 (priceClose(10) ... priceClose(1))
    extract_pattern(&newPat, learn_offset);

    // 计算结果
    // 结果：priceClose(0) 相对于 模式基准价(priceClose(10)) 的涨跌幅
    // 这样保持了与 extract_pattern 中归一化逻辑的一致性

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

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

    // 保存到全局记忆库
    if(g_patternCount < MAX_PATTERNS) {
        memcpy(&g_patterns[g_patternCount], &newPat, sizeof(Pattern));
        g_patternCount++;
    }
}

/**
 * 预测下一根 K 线
 * 基于当前 Bar 0 的形态，预测 Bar -1
 */
void predict_next_bar()
{
    g_lastPrediction.predicted_change_pct = 0;
    g_lastPrediction.confidence = 0;
    g_lastPrediction.is_bullish = false;
    g_lastPrediction.found_count = 0;

    // 提取当前形态 (priceClose(9) ... priceClose(0))
    Pattern currentPat;
    extract_pattern(&currentPat, 0);

    // 搜索相似模式
    int indices[MAX_SIMILAR];
    var similarities[MAX_SIMILAR];
    int foundCount = 0;

    int i;
    for(i = g_patternCount - 1; i >= 0; i--)
    {
        if(foundCount >= MAX_SIMILAR) break;

        var sim = calculate_similarity(currentPat.values, g_patterns[i].values);

        if(sim > 0.7) {
            indices[foundCount] = i;
            similarities[foundCount] = sim;
            foundCount++;
        }
    }

    g_lastPrediction.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[idx].result; // 这是相对于 Base 的结果

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

        // 只要最终价格高于 Base (0.01%)，就算 Positive
        // 即使下一根K线是跌的，只要还在 Base 之上，这里也会 +1
        if(result > 0.01) countPositive++;
        else if(result < -0.01) countNegative++;
    }

    // 计算原始加权结果 (相对于 Base)
    if(totalWeight > 0)
        g_lastPrediction.raw_weighted_change = totalWeightedChange / totalWeight;
    else
        g_lastPrediction.raw_weighted_change = 0;

    // 确定方向
    // 当大多数相似模式都保持在 Base 之上，且加权平均值也 > 0.01% 时，看涨
    g_lastPrediction.is_bullish = (countPositive > countNegative) && (g_lastPrediction.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_lastPrediction.confidence = (consensus * 0.7 + coverage * 0.3);

    // 预测的绝对价格
    // Base 是当前模式的起点 (priceClose(9))
    var current_base = priceClose(PATTERN_LEN - 1);
    g_lastPrediction.predicted_price = current_base * (1.0 + g_lastPrediction.raw_weighted_change / 100.0);

    // 计算相对于当前价格 (priceClose(0)) 的涨跌幅
    var current_price = priceClose(0);
    if(current_price > 0)
        g_lastPrediction.predicted_change_pct = (g_lastPrediction.predicted_price - current_price) / current_price * 100.0;
}

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

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

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

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

    // 测试样本
    StartDate = 20180101;
    EndDate = 20251230;
    LookBack = 100;

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

    // 选择交易对
    asset("BTCUSDT");

    // --------------------------------------------------------- //
    // 策略逻辑
    // --------------------------------------------------------- //

    // 参数
    var confidence_threshold = 60;
    var atr_stop_factor = 0;
    var atr_profit_factor = 0;

    // 学习刚刚完成的模式 (Bar 1 -> Bar 0)
    update_patterns();

    // 预测未来 (Bar 0 -> Bar -1)
    predict_next_bar();

    var atr20 = ATR(20);
    Stop = atr_stop_factor * atr20;
    TakeProfit = atr_profit_factor * atr20;

    // 信号
    bool long_entry = g_lastPrediction.confidence >= confidence_threshold && g_lastPrediction.is_bullish;
    bool long_exit = !g_lastPrediction.is_bullish;
    bool short_entry = g_lastPrediction.confidence >= confidence_threshold && !g_lastPrediction.is_bullish;
    bool short_exit = g_lastPrediction.is_bullish;

    // 订单
    Lots = 100;
    if(NumOpenLong > 0 && long_exit)
        exitLong();
    if(NumOpenShort > 0 && short_exit)
        exitShort();
    if(NumOpenLong == 0 && long_entry)
        enterLong();
    if(NumOpenShort == 0 && short_entry)
        enterShort();

    // 绘图
    var high_conf_bar = ifelse(g_lastPrediction.confidence >= 60, g_lastPrediction.confidence, 0);
    var low_conf_bar = ifelse(g_lastPrediction.confidence < 60, g_lastPrediction.confidence, 0);
    plot("HighConf", high_conf_bar, NEW|BARS, GREEN+TRANSP);
    plot("LowConf", low_conf_bar, 0|BARS, RED+TRANSP);
    plot("Confidence+", 60, 0, GREY);

    plot("WeightedChange", g_lastPrediction.raw_weighted_change, NEW|BARS, BLUE+TRANSP);
}
```


---

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

