English Русский Español Deutsch 日本語 Português
preview
MetaTrader 5 机器学习蓝图(第二部分):为机器学习标注金融数据

MetaTrader 5 机器学习蓝图(第二部分):为机器学习标注金融数据

MetaTrader 5 — 交易 |
38 2
Patrick Murimi Njoroge
Patrick Murimi Njoroge

目录


引言

想象一下:你正在接受训练,成为一名精英狙击手。你是更愿意在纸上练习射击完美的圆圈,还是更愿意使用模拟真实战斗场景的人形轮廓靶进行训练?答案显而易见 — 你需要的是能反映你将面对的真实情况的靶子。

同样的原理也适用于金融领域的机器学习。大多数学术研究采用所谓的“固定时间范围标记”方法,这相当于向那些完美的圆圈射击。这种方法提出了一个简单的问题:“X天后价格会更高还是更低?”但问题在于:真正的交易者并不只关心价格的最终走向。他们关心的是交易过程,即当止损被触发时,何时应该获利了结,以及价格在交易过程中的走势。

欢迎回到我们的 MetaTrader 5 机器学习蓝图系列。在第一部分中,我们解决了关键的“时间戳陷阱”问题,该陷阱会悄无声息地破坏大多数交易算法。现在,我们正在应对一个同样重要的挑战:如何创建真正反映你在现实世界中交易方式的标签。

这样想:如果你正在构建一个模型来预测某人是否会心脏病发作,你不会只关注他们在恰好 365 天后是生是死。你会想知道与医疗决策相关的预警信号、早期干预措施以及事件发生的顺序。金融市场也是同样的道理。

本文假设您已经熟悉 Python,并且对机器学习概念有基本的了解。我们将深入探讨您可以立即实现的实用代码和实际应用。

第一部分回顾:数据泄露和时间戳修复

在本系列的第一篇文章中,我们讨论了一个关键但常被忽视的问题,该问题可能会悄无声息地破坏金融市场中的机器学习模型:MetaTrader 5 默认数据结构中固有的“时间戳陷阱”和数据泄露问题。我们通过解决数据完整性问题,为构建可靠金融机器学习模型奠定了至关重要的基础,强调了从原始 tick 数据中构建干净、无偏的 K 线数据的必要性。这一基础对于开发可靠的金融机器学习模型来说至关重要,不容忽视。如果您尚未阅读第一部分,我们强烈建议您在继续阅读之前先完成这部分内容。

那里奠定的基础确保了:

  1. 数据完整性: 所有时间戳都反映了信息实际可用的时间。
  2. 统计合理性:活动驱动的 K 线为机器学习模型提供了更好的统计特性。
  3. 现实世界的一致性:K 线的构建符合实际市场信息流。

在解决了这些基本的数据质量问题后,我们现在拥有了干净、无偏差的数据集,为机器学习流程中的下一个关键步骤 — 即真正捕捉市场动态的标注技术 — 做好了准备。


标注方法概述

金融领域的大多数机器学习模型之所以失败,原因出奇地平凡 — 并非因为算法不佳或计算能力不足,而是因为标签质量太差。当我开始构建交易模型时,我花费数月时间优化特征并尝试不同的神经网络架构,结果却发现我的标注方案存在根本性缺陷。我实际上是在教我的模型去击中靶心,而真正需要它的是在飓风中击中移动的目标。

金融市场总是噪音不断。每一个 tick 都包含着真实信息和随机混乱的混合体,而我们的工作就是提取出信号,同时认识到大多数价格变动只是市场参与者改变主意或算法对微秒级波动的反应。好的标签不仅告诉我们发生了什么,还能帮助我们了解对实际交易决策至关重要的因素。

最简单的方法,也是大多数人开始采用的方法,是固定时间范围标注。你选择一个时间段 — 比如五天 — 然后判断在该时间段结束时价格是上涨还是下跌。如果苹果公司周一收于 150 美元,而周五达到 155 美元,那么周一就被标注为“买入”信号。这种方法简单直观,但与真实交易的方式有着根本性的区别。你上一次购买股票时,是否想过“无论发生什么,我都会在整整五天后再回来查看”?如果周二股票暴跌 20%,你就不会等到周五再重新评估。如果周三股价上涨 15%,你可能会立即获利了结。

这就引出了三重屏障方法,它改变了严肃的从业者对金融机器学习的看法。与任意的时间范围不同,你像专业交易员一样,在每笔潜在交易周围设置三重屏障。首先是你的盈利目标 — 可能比入场价高出 5%。其次是你的止损点 — 可能比你买入价低 3%。最后是时间限制,因为你不想永远持有亏损的仓位。你的标签取决于哪个屏障先被触及。突然之间,你的模型不是在学习抽象的价格变动,而是在学习特定的交易设置是否可能在触及止损点之前达到盈利目标。

这种方法的美妙之处在于,它反映了真实的交易心理。真正的交易者并不关心一只股票最终是否上涨,如果它首先下跌到足以触发他们的风险管理规则,他们并不在意。路径与目的地同样重要,而三重屏障法自然地捕捉到了这种路径依赖性。你甚至可以使障碍具有动态性 — 在波动期间设置更宽的止损,而在市场平静时设置更窄的止损。

对于趋势长度变化显著的市场,趋势扫描方法提供了一种优雅的解决方案。这些算法不是强加一个固定的时间周期,而是测试多个前瞻性时段,并识别出统计上最显著的趋势。或许 5 天趋势较弱,10 天趋势较强,15 天趋势中等。该方法会选择最强的信号并相应地标记。这就像让算法本身为每种市场条件确定最佳预测范围。

接下来是元标注,它解决的是一个完全不同的问题。它不是预测市场方向,而是问:“我应该在何时信任我的其他预测?”想象一下,你已经有一个能生成买入和卖出信号的交易策略。元标注会构建第二个模型,用于评估每个信号是否可能盈利。你的主要策略可能会说“买入”,但元模型会考虑其他因素 — 近期表现、市场波动性、自上次重大新闻事件以来的时间 — 并输出一个置信度评分。高置信度意味着你可以大胆建仓。低置信度意味着你可以放弃或小仓位交易。

这种方法体现了一个至关重要的见解:知道你何时可能正确往往比试图更频繁地正确更有价值。这正是优秀预测者和盈利交易者之间的区别。许多策略失败并非因为它们的方向预测不好,而是因为它们在高置信度信号和低置信度信号上投入了相同的资金。

每种标注方法都会给你的模型传授不同的知识。固定时间范围的方法侧重于纯粹的价格方向。三重屏障法结合了风险管理和路径依赖。趋势扫描法适应不断变化的市场条件。元标注法优化了信念和仓位规模。你所选择的方法从根本上决定了你的模型所学内容以及它在实时交易中的表现。

处理金融数据时需要考虑的关键因素

  • 避免后见之明偏差: 确保你的标签仅基于决策时点的可用信息。例如,在为“今天”的数据点标注时,你只能使用“今天”或更早的信息来确定特征,而使用“未来”(相对于“今天”)的信息来确定标签。
  • 平衡你的类别:如果你在标注“买入”、“卖出”和“持有”时,可能会发现“持有”信号(或小幅波动)出现的频率要高得多。高度不平衡的类别会使机器学习模型更难学习少数类别。有一些技术可以处理这种情况(例如,过采样、欠采样或使用适当的评估指标)。
  • 波动性是关键:金融市场的波动性不断变化。在平静的市场中,2% 的价格波动可能非常巨大,但在波动时期则微不足道。考虑对标签使用波动性调整阈值(如三重屏障法)。
  • 平稳性:金融时间序列往往是非平稳的(其统计特性,如均值和方差,会随时间变化)。虽然标注本身并不能直接使数据变得平稳,但标注的选择(例如,标注收益率,它通常比价格更平稳)以及随后的特征工程至关重要。
  • 迭代和改进:你最初的标注方法可能不是最佳方案。准备好尝试不同的方法、预测时域和阈值,以找出最适合你的特定目标和所分析资产的方法。


实现:三重屏障标记法

设置动态屏障

如前一节所述,在实践中,我们希望根据交易所涉及的风险来设定获利了结和止损限额。否则,考虑到当前的波动性,我们有时会目标过高(𝜏 ≫ 𝜎 ti,0 ),有时会目标过低(𝜏 ≪ 𝜎 ti,0 )。

下面的代码计算日内估计点的每日波动率,将回溯天数应用于指数加权移动标准差。这种波动性将被用来设定止盈和止损位。

def get_daily_vol(close, lookback=100):
    """
    Advances in Financial Machine Learning, Snippet 3.1, page 44.

    Daily Volatility Estimates

    Computes the daily volatility at intraday estimation points.

    In practice we want to set profit taking and stop-loss limits that are a function of the risks involved
    in a bet. Otherwise, sometimes we will be aiming too high (tao ≫ sigma_t_i,0), and sometimes too low
    (tao ≪ sigma_t_i,0), considering the prevailing volatility. Snippet 3.1 computes the daily volatility
    at intraday estimation points, applying a span of lookback days to an exponentially weighted moving
    standard deviation.

    See the pandas documentation for details on the pandas.Series.ewm function.
    Note: This function is used to compute dynamic thresholds for profit taking and stop loss limits.

    :param close: (pd.Series) Closing prices
    :param lookback: (int) Lookback period to compute volatility
    :return: (pd.Series) Daily volatility value
    """
    # Find previous valid trading day for each date
    prev_idx = close.index.searchsorted(close.index - pd.Timedelta(days=1))
    prev_idx = prev_idx[prev_idx > 0]  # Drop indices before the start

    # Align current and previous closes
    curr_idx = close.index[close.shape[0] - prev_idx.shape[0] :]
    prev_close = close.iloc[prev_idx - 1].values  # Previous day's close
    ret = close.loc[curr_idx] / prev_close - 1
    vol = ret.ewm(span=lookback).std()
    return vol

设置垂直屏障

要设置垂直屏障,我们使用以下函数。当使用活动驱动型 K 线时,根据剩余 K 线的数量而不是固定的时间段来设置屏障更有意义,因为在一个时间范围内可能会出现极大的变化。

# Snippet 3.4 page 49, Adding a Vertical Barrier
def add_vertical_barrier(t_events, close, num_bars=0, **time_delta_kwargs):
    """
    Advances in Financial Machine Learning, Enhanced Implementation.

    Adding a Vertical Barrier

    For each event in t_events, finds the timestamp of the next price bar at or immediately after:
    - A fixed number of bars (for activity-based sampling), OR
    - A time delta (for time-based sampling)

    This function creates a series of vertical barrier timestamps aligned with the original events index.
    Out-of-bound barriers are marked with NaT for downstream handling.

    :param t_events: (pd.Series) Series of event timestamps (e.g., from symmetric CUSUM filter)
    :param close: (pd.Series) Close price series with DateTimeIndex
    :param num_bars: (int) Number of bars for vertical barrier (activity-based mode). 
                     Takes precedence over time delta parameters when > 0.
    :param time_delta_kwargs: Time components for time-based barrier (mutually exclusive with num_bars):
        :param days: (int) Number of days
        :param hours: (int) Number of hours
        :param minutes: (int) Number of minutes
        :param seconds: (int) Number of seconds
    :return: (pd.Series) Vertical barrier timestamps with same index as t_events. 
             Out-of-bound events return pd.NaT.

    Example:
        # Activity-bar mode (tick/volume/dollar bars)
        vertical_barriers = add_vertical_barrier(t_events, close, num_bars=10)
        
        # Time-based mode
        vertical_barriers = add_vertical_barrier(t_events, close, days=1, hours=3)
    """
    # Validate inputs
    if num_bars and time_delta_kwargs:
        raise ValueError("Use either num_bars OR time deltas, not both")

    # BAR-BASED VERTICAL BARRIERS
    if num_bars > 0:
        indices = close.index.get_indexer(t_events, method="nearest")
        t1 = []
        for i in indices:
            if i == -1:  # Event not found
                t1.append(pd.NaT)
            else:
                end_loc = i + num_bars
                t1.append(close.index[end_loc] if end_loc < len(close) else pd.NaT)
        return pd.Series(t1, index=t_events)

    # TIME-BASED VERTICAL BARRIERS
    td = pd.Timedelta(**time_delta_kwargs) if time_delta_kwargs else pd.Timedelta(0)
    barrier_times = t_events + td

    # Find next index positions
    t1_indices = np.searchsorted(close.index, barrier_times, side="left")
    t1 = []
    for idx in t1_indices:
        if idx < len(close):
            t1.append(close.index[idx])
        else:
            t1.append(pd.NaT)  # Mark out-of-bound for downstream

    return pd.Series(t1, index=t_events)

应用三重屏障标注

三重屏障法本质上是路径依赖的,这意味着我们不能仅仅通过最终价格来确定我们的标签。相反,我们需要跟踪从建仓到平仓的整个价格走势,无论是达到盈利目标、止损还是时间限制而平仓。

当我们应用三重屏障法时,我们本质上是在问:“从时间 t i,0 开始,随着时间推移,首先会发生什么?”该过程持续进行,直到我们到达 t i,1 时刻,这表示触碰到第一个屏障的时刻。这可以是我们的利润目标、止损位或最长持有期(在 t i,0 + h 处设置的垂直屏障)。我们用于标注的回报是从我们的入场点 t i,0 到第一次接触时间 t i,1 计算出来的。

函数 apply_pt_sl_on_t1() 实现了这一逻辑,并且需要多个输入才能正常工作。首先,它需要 close 价格序列,以便跟踪实际价格走势。events 数据帧包含每笔潜在交易的基本信息:t1 列指定每笔交易应何时到期(垂直屏障),而 trgt 列定义我们的水平屏障应有多宽。

pt_sl  参数尤其重要。这是一个包含两个元素的列表,用于控制屏障宽度。第一个元素( pt_sl [0])设置止盈屏障使用的目标宽度的倍数,而第二个元素( pt_sl [1])对止损屏障执行相同的操作。如果其中任何一个值为零,则该特定屏障将被禁用。这种灵活性使您可以创建不对称的风险/回报设置。例如,你可以设置一个严格的止损位,但允许利润继续增长。

该函数系统地处理这些屏障,逐根 K 线跟踪价格走势,直到突破其中一个屏障,从而为我们提供准确标注所需的精确时间和回报信息。

# Snippet 3.2, page 45, Triple Barrier Labeling Method
def apply_pt_sl_on_t1(close, events, pt_sl, molecule):
    """
    Advances in Financial Machine Learning, Snippet 3.2, page 45.

    Triple Barrier Labeling Method

    This function applies the triple-barrier labeling method. It works on a set of
    datetime index values (molecule). This allows the program to parallelize the processing.

    Mainly it returns a DataFrame of timestamps regarding the time when the first barriers were reached.

    :param close: (pd.Series) Close prices
    :param events: (pd.Series) Indices that signify "events" (see cusum_filter function for more details)
    :param pt_sl: (np.array) Element 0, indicates the profit taking level; Element 1 is stop loss level
    :param molecule: (an array) A set of datetime index values for processing
    :return: (pd.DataFrame) Timestamps of when first barrier was touched
    """
    # Apply stop loss/profit taking, if it takes place before t1 (end of event)
    events = events.loc[molecule].copy()
    out = events[["t1"]].copy(deep=True)

    profit_taking_multiple = pt_sl[0]
    stop_loss_multiple = pt_sl[1]

    # Profit taking active
    if profit_taking_multiple > 0:
        profit_taking = np.log(1 + profit_taking_multiple * events["trgt"])
    else:
        profit_taking = pd.Series(index=events.index)  # NaNs

    # Stop loss active
    if stop_loss_multiple > 0:
        stop_loss = np.log(1 - stop_loss_multiple * events["trgt"])
    else:
        stop_loss = pd.Series(index=events.index)  # NaNs

    # Use dictionary to collect barrier hit times
    barrier_dict = {"sl": {}, "pt": {}}

    # Get events
    for loc, vertical_barrier in events["t1"].fillna(close.index[-1]).items():
        closing_prices = close[loc:vertical_barrier]  # Path prices for a given trade
        cum_returns = np.log(closing_prices / close[loc]) * events.at[loc, "side"]  # Path returns
        barrier_dict["sl"][loc] = cum_returns[
            cum_returns < stop_loss[loc]
        ].index.min()  # Earliest stop loss date
        barrier_dict["pt"][loc] = cum_returns[
            cum_returns > profit_taking[loc]
        ].index.min()  # Earliest profit taking date

    # Convert dictionary to DataFrame and join to `out`
    barrier_df = pd.DataFrame(barrier_dict)
    out = out.join(barrier_df)  # Join on index (loc)

    return out

三重屏障法提供了八种可能的配置,具体取决于你激活哪些屏障。将每个设置视为 [profit_target, stop_loss, time_limit](利润目标,止损,时间限制),其中 1 表示启用,0 表示禁用。

  • 大多数实用的交易策略都采用以下三种配置之一:
    • [1,1,1] - 完整设置:三重屏障均已激活。你在追求利润的同时,还要管理下行风险和持有期。这反映了大多数专业交易者的实际操作方式。
    • [0,1,1] - 让利润奔跑:没有盈利目标;若止损未先触发,则在 X 个周期后退出。非常适合想要顺势而为的动量策略。
    • [1,1,0] - 无时间压力:已设定盈利目标和止损点,但没有时间限制。你将一直持有,直到触及某个价格屏障,无论需要多长时间。
  • 三种技术上可行但不太现实的方案:
    • [0,0,1] - 固定时间范围:仅提供限时出场。这本质上是一种固定时间范围的标签法,尽管它也可以用于活动驱动的 K 线。
    • [1,0,1] - 忽略损失:坚持到盈利或时间耗尽,无论中间出现何种亏损。对风险管理而言是危险的。
    • [1,0,0] - 永远持有:无止损或时间限制。持续亏损仓位,直到它们最终盈利 — 这是毁灭投资组合的秘诀。
  • 两种基本无用的配置:
    • [0,1,0] - 预期失败:持仓直至触发止损。为什么有人会抱着只会亏损的预期进行交易呢?
    • [0,0,0] - 无出场:所有屏障均已移除。仓位永不平仓,也不会生成标签。

以下是三重屏障法的两种可能配置。

方向和大小的学习

本节中的函数采用三重屏障方法,当 side_prediction 为 None 时,在 get_events() 中学习方向 {1, 0, -1},或者当方向已知时,从元标记数据中学习大小。学习交易的方向意味着没有水平屏障,或者水平屏障是对称的。这是因为我们目前无法区分获利和止损屏障。一旦确定了方向,我们就可以优化屏障,找到能够产生性能最佳模型的组合。我们通过运行 get_events() 获取第一次触及屏障的日期。

# Snippet 3.3 -> 3.6 page 50, Getting the Time of the First Touch, with Meta Labels
def get_events(close, t_events, pt_sl, target, min_ret, num_threads, vertical_barrier_times=False,
               side_prediction=None, verbose=True):
    """
    Advances in Financial Machine Learning, Snippet 3.6 page 50.

    Getting the Time of the First Touch, with Meta Labels

    This function is orchestrator to meta-label the data, in conjunction with the Triple Barrier Method.

    :param close: (pd.Series) Close prices
    :param t_events: (pd.Series) of t_events. These are timestamps that will seed every triple barrier.
        These are the timestamps selected by the sampling procedures discussed in Chapter 2, Section 2.5.
        E.g.: CUSUM Filter
    :param pt_sl: (list) Element 0, indicates the profit taking level; Element 1 is stop loss level.
        A non-negative float that sets the width of the two barriers. A 0 value means that the respective
        horizontal barrier (profit taking and/or stop loss) will be disabled.
    :param target: (pd.Series) of values that are used (in conjunction with pt_sl) to determine the width
        of the barrier. In this program this is daily volatility series.
    :param min_ret: (float) The minimum target return required for running a triple barrier search.
    :param num_threads: (int) The number of threads concurrently used by the function.
    :param vertical_barrier_times: (pd.Series) A pandas series with the timestamps of the vertical barriers.
        We pass a False when we want to disable vertical barriers.
    :param side_prediction: (pd.Series) Side of the bet (long/short) as decided by the primary model
    :param verbose: (bool) Flag to report progress on asynch jobs
    :return: (pd.DataFrame) Events
            -events.index is event's starttime
            -events['t1'] is event's endtime
            -events['trgt'] is event's target
            -events['side'] (optional) implies the algo's position side
            -events['pt'] is profit taking multiple
            -events['sl']  is stop loss multiple
    """

    # 1) Get target
    target = target.reindex(t_events)
    target = target[target > min_ret]  # min_ret

    # 2) Get vertical barrier (max holding period)
    if vertical_barrier_times is False:
        vertical_barrier_times = pd.Series(pd.NaT, index=t_events, dtype=t_events.dtype)

    # 3) Form events object, apply stop loss on vertical barrier
    if side_prediction is None:
        side_ = pd.Series(1.0, index=target.index)
        pt_sl_ = [pt_sl[0], pt_sl[0]]
    else:
        side_ = side_prediction.reindex(target.index)  # Subset side_prediction on target index.
        pt_sl_ = pt_sl[:2]

    # Create a new df with [v_barrier, target, side] and drop rows that are NA in target
    events = pd.concat({'t1': vertical_barrier_times, 'trgt': target, 'side': side_}, axis=1)
    events = events.dropna(subset=['trgt'])

    # Apply Triple Barrier
    first_touch_dates = mp_pandas_obj(func=apply_pt_sl_on_t1,
                                      pd_obj=('molecule', events.index),
                                      num_threads=num_threads,
                                      close=close,
                                      events=events,
                                      pt_sl=pt_sl_,
                                      verbose=verbose)

    for ind in events.index:
        events.at[ind, 't1'] = first_touch_dates.loc[ind, :].dropna().min()

    if side_prediction is None:
        events = events.drop('side', axis=1)

    # Add profit taking and stop loss multiples for vertical barrier calculations
    events['pt'] = pt_sl[0]
    events['sl'] = pt_sl[1]

    return events

我们使用 get_bins() 函数返回一个数据帧 events,其中:

  • events.index 是事件的开始时间
  • events['t1'] 是事件的结束时间
  • events['trgt'] 是事件的目标
  • events['side'](可选)表示策略的仓位方向
标注行为取决于 “side” 是否存在:
  • 案例一:如果 “side” 不在事件列表中 → bin ∈ {-1, 1}(按价格走势的标签)
  • 案例二:如果存在 “side”→ bin ∈ {0, 1}(通过 PnL 的标签 — 元标注)
# Snippet 3.4 -> 3.7, page 51, Labeling for Side & Size with Meta Labels
def get_bins(triple_barrier_events, close, vertical_barrier_zero=False, pt_sl=[1, 1]):
    """
    Advances in Financial Machine Learning, Snippet 3.7, page 51.

    Labeling for Side & Size with Meta Labels

    Compute event's outcome (including side information, if provided).
    events is a DataFrame where:

    Now the possible values for labels in out['bin'] are {0,1}, as opposed to whether to take the bet or pass,
    a purely binary prediction. When the predicted label the previous feasible values {−1,0,1}.
    The ML algorithm will be trained to decide is 1, we can use the probability of this secondary prediction
    to derive the size of the bet, where the side (sign) of the position has been set by the primary model.

    :param triple_barrier_events: (pd.DataFrame) Events DataFrame with the following structure:
    - **index**: pd.DatetimeIndex of event start times
    - **t1**: (pd.Series) Event end times
    - **trgt**: (pd.Series) Target returns
    - **side**: (pd.Series, optional) Algo's position side
      Labeling behavior depends on the presence of 'side':
        - Case 1: If 'side' not in events → `bin ∈ {-1, 1}` (label by price action)
        - Case 2: If 'side' is present    → `bin ∈ {0, 1}`  (label by PnL — meta-labeling)
    :param close: (pd.Series) Close prices
    :param vertical_barrier_zero: (bool) If True, set bin to 0 for events that touch vertical barrier, else bin is the sign of the return.
    :param pt_sl: (list) Take-profit and stop-loss multiples
    :return: (pd.DataFrame) Meta-labeled events
    :returns index: Event start times
    :returns t1: Event end times
    :returns trgt: Target returns
    :returns side: Optional. Algo's position side
    :returns ret: Returns of the event
    :returns bin: Labels for the event, where 1 is a positive return, -1 is a negative return, and 0 is a vertical barrier hit
    """

    # 1. Align prices with their respective events
    events = triple_barrier_events.dropna(subset=["t1"])
    all_dates = events.index.union(other=events["t1"].array).drop_duplicates()
    prices = close.reindex(all_dates, method="bfill")

    # 2. Create out DataFrame
    out_df = events[["t1"]].copy()
    out_df["ret"] = np.log(prices.loc[events["t1"].array].array / prices.loc[events.index])
    out_df["trgt"] = events["trgt"]

    # Meta labeling: Events that were correct will have pos returns
    if "side" in events:
        out_df["ret"] *= events["side"]  # meta-labeling

    if vertical_barrier_zero:
        # Label 0 when vertical barrier reached
        out_df["bin"] = barrier_touched(
            out_df["ret"].values,
            out_df["trgt"].values,
            np.array(pt_sl, dtype=float),
        )
    else:
        # Label is the sign of the return
        out_df["bin"] = np.where(out_df["ret"] > 0, 1, -1).astype("int8")

    # Meta labeling: label incorrect events with a 0
    if "side" in events:
        out_df.loc[out_df["ret"] <= 0, "bin"] = 0

    # Add the side to the output. This is useful for when a meta label model must be fit
    if "side" in triple_barrier_events.columns:
        out_df["side"] = triple_barrier_events["side"].astype("int8")

    out_df["ret"] = np.exp(out_df["ret"]) - 1  # Convert log returns to simple returns
    return out_df

注意:上面使用的 mp_pandas_obj() 是一个辅助函数,用于在处理 pandas 对象时进行并行处理(pandas 始终在单个 CPU 上运行)。附件 multiprocess.py 包含此函数和其他多进程辅助函数。

为了在触碰到垂直屏障时将标签设置为零,我们在 get_bins() 中调用 barrier_touched() 函数。

# Snippet 3.9, page 55, Question 3.3
def barrier_touched(ret, target, pt_sl):
    """
    Advances in Financial Machine Learning, Snippet 3.9, page 55, Question 3.3.

    Adjust the getBins function (Snippet 3.7) to return a 0 whenever the vertical barrier is the one touched first.

    Top horizontal barrier: 1
    Bottom horizontal barrier: -1
    Vertical barrier: 0

    :param ret: (np.array) Log-returns
    :param target: (np.array) Volatility target
    :param pt_sl: (ArrayLike) Take-profit and stop-loss multiples
    :return: (np.array) Labels
    """
    N = ret.shape[0]  # Number of events
    store = np.empty(N, dtype=np.int8)  # Store labels in an array

    profit_taking_multiple = pt_sl[0]
    stop_loss_multiple = pt_sl[1]

    # Iterate through the DataFrame and check if the vertical barrier was reached
    for i in range(N):
        pt_level_reached = ret[i] > np.log(1 + profit_taking_multiple * target[i])
        sl_level_reached = ret[i] < np.log(1 - stop_loss_multiple * target[i])

        if ret[i] > 0.0 and pt_level_reached:
            # Top barrier reached
            store[i] = 1
        elif ret[i] < 0.0 and sl_level_reached:
            # Bottom barrier reached
            store[i] = -1
        else:
            # Vertical barrier reached
            store[i] = 0

    return store

何时标注为零或标注为收益符号

当您希望模型严格关注明确的风险管理结果时,将非触碰事件标记为零是有意义的,,而在时间范围内使用收益的符号可以捕捉所有方向性的漂移,即使未超出风险阈值。

如果符合以下条件,则标注为零: 

  • 你正在构建一个三分类分类器(上升、下降、中性),并希望“中性”在你的风险限制范围内表示“无决定性动作”。 
  • 你更倾向于从训练数据中过滤掉模糊信号 — 即那些从未触及任何屏障的小幅波动。 
  • 你希望仅通过达到预定义的盈利或亏损阈值来衡量事件的成功,而忽略所有其他情况。 

如果符合以下条件,请贴上返回标签:

  • 对于二分类问题,你需要每个样本都携带一个二元方向(上/下),并且希望避免中性标签过多。 
  • 你是在建模动量或时间范围收益,而不是严格的风险控制退出。 
  • 你认为价格变动 — 无论多么微小 — 都是有信息的,并且应该影响你的估价工具。

除了这个选择,还要考虑它如何影响类别平衡和标签噪声。如果你看到太多零,你可能需要对中性样本进行欠采样或提高水平阈值;如果你的收益符号标签噪声太大,你可以在分配 +1/-1 之前应用一个最小返回阈值。

基于事件的采样

作为交易者,我们不会随意决定何时买卖证券。相反,我们会等待市场上发生特定事件后再采取行动。这些“触发事件”可能包括:

  • 当重要的经济数据发布时(例如就业数据或通胀报告)
  • 当市场价格突然变得非常不稳定时
  • 当相关投资之间的价格差异远远偏离正常预期时

一旦发生此类事件,我们就将其视为市场中可能发生重要事件的信号。然后我们可以让机器学习算法来判断在这些情况下是否存在准确的预测函数。

关键在于了解是否存在一种准确的方法来预测这些事件发生时的市场走势。如果算法显示某种类型的事件无法做出准确的预测,那么我们需要改变对重大事件的定义,或者尝试使用不同的特征作为模型的输入。

CUSUM 滤波器

CUSUM 滤波器是一种强大的基于事件的采样技术,它是一种质量控制方法,用于检测测量量平均值的变化。在金融领域,我们可以调整此滤波器,以便在市场变量(如价格)发生显著偏差时对数据点进行采样。CUSUM 滤波器的工作原理是累积与预期值的偏差,并在累积值超过特定阈值时触发采样事件。  

对称 CUSUM 滤波器定义如下:

  • S⁺ = max(0, S⁺ + ΔP)

  • S⁻ = min(0, S⁻ + ΔP)

其中 ΔP 为价格变化。当 S⁺ 超过正阈值 h 或 S⁻ 低于负阈值 -h 时,就会触发事件。当事件触发时,相应的累加器将被重置。这种方法避免了在价格在阈值附近徘徊时触发多个事件,这是布林带等流行市场信号中常见的缺陷。通过使用 CUSUM 滤波器,我们可以创建一个特征矩阵 X,该矩阵在市场活动显著时进行采样,为我们的机器学习(ML)模型提供更多相关数据。

# Snippet 2.4, page 39, The Symmetric CUSUM Filter.
def cusum_filter(raw_time_series, threshold, time_stamps=True):
    """
    Advances in Financial Machine Learning, Snippet 2.4, page 39.

    The Symmetric Dynamic/Fixed CUSUM Filter.

    The CUSUM filter is a quality-control method, designed to detect a shift in the mean value of a measured quantity
    away from a target value. The filter is set up to identify a sequence of upside or downside divergences from any
    reset level zero. We sample a bar t if and only if S_t >= threshold, at which point S_t is reset to 0.

    One practical aspect that makes CUSUM filters appealing is that multiple events are not triggered by raw_time_series
    hovering around a threshold level, which is a flaw suffered by popular market signals such as Bollinger Bands.
    It will require a full run of length threshold for raw_time_series to trigger an event.

    Once we have obtained this subset of event-driven bars, we will let the ML algorithm determine whether the occurrence
    of such events constitutes actionable intelligence. Below is an implementation of the Symmetric CUSUM filter.

    Note: As per the book this filter is applied to closing prices but we extended it to also work on other
    time series such as volatility.

    :param raw_time_series: (pd.Series) Close prices (or other time series, e.g. volatility).
    :param threshold: (float or pd.Series) When the abs(change) is larger than the threshold, the function captures
                      it as an event, can be dynamic if threshold is pd.Series
    :param time_stamps: (bool) Default is to return a DateTimeIndex, change to false to have it return a list.
    :return: (datetime index vector) Vector of datetimes when the events occurred. This is used later to sample.
    """

    t_events = []
    s_pos = 0
    s_neg = 0

    # log returns
    raw_time_series = pd.DataFrame(raw_time_series)  # Convert to DataFrame
    raw_time_series.columns = ['price']
    raw_time_series['log_ret'] = raw_time_series.price.apply(np.log).diff()
    if isinstance(threshold, (float, int)):
        raw_time_series['threshold'] = threshold
    elif isinstance(threshold, pd.Series):
        raw_time_series.loc[threshold.index, 'threshold'] = threshold
    else:
        raise ValueError('threshold is neither float nor pd.Series!')

    raw_time_series = raw_time_series.iloc[1:]  # Drop first na values

    # Get event time stamps for the entire series
    for tup in raw_time_series.itertuples():
        thresh = tup.threshold
        pos = float(s_pos + tup.log_ret)
        neg = float(s_neg + tup.log_ret)
        s_pos = max(0.0, pos)
        s_neg = min(0.0, neg)

        if s_neg < -thresh:
            s_neg = 0
            t_events.append(tup.Index)

        elif s_pos > thresh:
            s_pos = 0
            t_events.append(tup.Index)

    # Return DatetimeIndex or list
    if time_stamps:
        event_timestamps = pd.DatetimeIndex(t_events)
        return event_timestamps

    return t_events

让我们分析一下,当使用未经滤波的入场信号与使用 CUSUM 滤波的入场信号时,均值回归布林带策略的表现如何。 我们将使用 2018 年 1 月 1 日至 2021 年 12 月 31 日的 EURUSD 5 分钟时间 K 线数据进行训练和验证,并使用 2022 年 1 月 1 日至 2024 年 12 月 31 日的数据进行样本外测试。 

为了进行本次演示,我们将使用一个故意敏感的布林带配置(20周期,1.5个标准差)来生成大量的交易信号,供元模型进行评估。虽然这对于独立策略来说噪音过大,但它为我们的标注和过滤流程提供了一个理想的压力测试。

为了确保所有策略的一致性和互操作性,我更喜欢使用 Python 的面向对象设计来构建它们 — 特别是通过共享接口或基类。这种方法允许每个策略都展现相同的核心功能(例如,信号生成、事件过滤),从而更容易在更广泛的工作流程中进行比较、扩展和集成。使用 TA-Lib 和 Pandas TA 来生成常用信号是有益的,因为它实现了行业标准的公式,构建在高度优化的 C 后端之上,使其比等效的 Python 实现快 2-4 倍,并确保输出标准化且边缘情况得到一致处理,从而简化了下游任务,如标注、过滤或可视化。此库的安装有时可能具有挑战性,因此我建议遵循此文章中的说明。 

import pandas as pd
from typing import Tuple, Union
import logging

from abc import ABC, abstractmethod
from typing import Dict, Tuple, Union

import numpy as np
import pandas as pd
import talib
from loguru import logger

class BaseStrategy(ABC):
    """Abstract base class for trading strategies"""

    @abstractmethod
    def generate_signals(self, data: pd.DataFrame) -> pd.Series:
        """Generate trading signals (1 for long, -1 for short, 0 for no position)"""
        pass

    @abstractmethod
    def get_strategy_name(self) -> str:
        """Return strategy name"""
        pass

    @abstractmethod
    def get_objective(self) -> str:
        """Return strategy objective"""
        pass

class BollingerMeanReversionStrategy(BaseStrategy):
    """Bollinger Bands mean reversion strategy"""

    def __init__(self, window: int = 20, num_std: float = 2.0, objective: str = "mean_reversion"):
        self.window = window
        self.num_std = num_std
        self.objective = objective

    def generate_signals(self, data: pd.DataFrame) -> pd.Series:
        """Generate mean-reversion signals using Bollinger Bands"""
        close = data["close"]

        # Calculate Bollinger Bands
        upper_band, _, lower_band = talib.BBANDS(
            close, timeperiod=self.window, nbdevup=self.num_std, nbdevdn=self.num_std
        )

        # Generate signals
        signals = pd.Series(0, index=data.index, dtype="int8", name="side")
        signals[(close >= upper_band)] = -1  # Sell signal (mean reversion)
        signals[(close <= lower_band)] = 1  # Buy signal (mean reversion)
        return signals

    def get_strategy_name(self) -> str:
        return f"Bollinger_w{self.window}_std{self.num_std}"

    def get_objective(self) -> str:
        return self.objective

def get_entries(
    strategy: 'BaseStrategy',
    data: pd.DataFrame,
    filter_events: bool = False,
    filter_threshold: Union[float, pd.Series] = None,
    on_crossover: bool = True,
) -> Tuple[pd.Series, pd.DatetimeIndex]:
    """Get timestamps and position information for entry events.

    This function processes signals from a given `BaseStrategy` to identify trade
    entry points. It can apply a CUSUM filter to isolate significant events or,
    by default, detect entries at signal crossover points.

    Args:
        strategy (BaseStrategy): The trading strategy object that generates the
            primary signals.
        data (pd.DataFrame): A pandas DataFrame containing the input data, expected
            to have a 'close' column if `filter_events` is True.
        filter_events (bool, optional): If True, a CUSUM filter is applied to the
            signals to identify significant events. Defaults to False.
        filter_threshold (Union[float, pd.Series], optional): The threshold for the
            CUSUM filter. Must be a float or a pandas Series. Defaults to None.
        on_crossover (bool, optional): If True, only events where the signal changes
            from the previous period are considered entry points. Defaults to True.

    Raises:
        ValueError: If `filter_events` is True and `filter_threshold` is not a
            `float` or `pd.Series`.
            
    Returns:
        Tuple[pd.Series, pd.DatetimeIndex]: A tuple containing:
            side (pd.Series): A Series with the same index as the input data,
                where each value represents the trading position (-1 for short,
                1 for long, 0 for no position).
            t_events (pd.DatetimeIndex): A DatetimeIndex of the timestamps for
                each detected entry event.
    """
    primary_signals = strategy.generate_signals(data)
    signal_mask = primary_signals != 0

    # Vectorized CUSUM filter application
    if filter_events:
        try:
            close = data.close
        except AttributeError as e:
            logger.error(f"Dataframe must have a 'close' column: {e}")
            raise e

        if not isinstance(filter_threshold, (pd.Series, float)):
            raise ValueError("filter_threshold must be a Series or a float")
        elif isinstance(filter_threshold, pd.Series):
            filter_threshold = filter_threshold.copy().dropna()
            close = close.reindex(filter_threshold.index)

        # Assuming cusum_filter is a function that takes a Series and a threshold
        filtered_events = cusum_filter(close, filter_threshold)
        signal_mask &= primary_signals.index.isin(filtered_events)
    else:
        # Vectorized signal change detection
        if on_crossover:
            signal_mask &= primary_signals != primary_signals.shift()

    t_events = primary_signals.index[signal_mask]

    side = pd.Series(index=data.index, name="side")
    side.loc[t_events] = primary_signals.loc[t_events]
    side = side.ffill().fillna(0).astype("int8")

    if filter_events:
        s = " generated by CUSUM filter"
    elif on_crossover:
        s = " generated by crossover"
    else:
        s = ""

    logger.info(f"Generated {len(t_events):,} trade events{s}.")

    return side, t_events

元标注的特征工程

为了捕捉金融时间序列的细微动态,我们构建了一个丰富的特征集,该集融合了统计严谨性与领域特定洞察。这包括经波动率调整的动量指标、自相关结构以及高阶收益矩(偏度和峰度),此外还有基于布林带(Bollinger)的指标和归一化移动平均差。使用 TA-Lib 和 pandas-ta 提取了 RSI、MACD、ADX 和 ATR 等技术信号,确保了一致性和可重复性。通过融合短期和长期特征 — 涵盖滞后收益、杨-张(Yang-Zhang)波动率估计以及趋势跟踪指标 — 该模型能够检测市场行为的细微变化,并对不断变化的交易条件做出响应。代码见附件 features.py。

为了说明 CUSUM 滤波器的有效性,我使用 EURUSD M5 数据上的未滤波和滤波信号训练了一个随机森林。 我的水平屏障设置以 100 天内的指数加权日波动率为目标,并将获利屏障设置为 1,止损屏障设置为 2。我的垂直屏障设置为 50 根 K 线。

target = get_daily_vol(close, lookback=100)

cusum_filter_threshold = target.mean()

数据过滤的影响

在深入探讨模型比较之前,先快速了解一下每个分类表中报告的关键指标:
  • 精度:正确正例预测占所有正例预测的百分比。高精度意味着误报较少。
  • 召回率:正确识别的实际正例百分比。高召回率意味着漏报事件较少。
  • F1 分数:对于元标签应用,准确率可能不是一个充分的分类评分指标。假设在应用元标签后,负例(标签为“0”)的数量远多于正例(标签为“1”)的数量。在这种情况下,一个将所有实例都预测为负例的分类器将获得高准确率,即使召回率为 0 且精度未定义。F1 分数通过评估分类器在精度和召回率的(等权重)调和平均值方面来修正这一缺陷。
  • 支持:验证集中每个类别的实例数量。
  • 正确率: 所有类别中正确预测的总比例。

有关这些指标的深入讲解,请参阅“ 如何解释 sklearn 中的分类报告”。

在比较任何分数之前,请注意 CUSUM 过滤器如何将样本量减少了 76.1%。

未过滤信号  已过滤信号  减少 % 
32828 7825 76.1

表 0: 信号计数 - 过滤后的对未过滤

CUSUM 过滤器旨在去除与 0 类动态特性内在相关的“噪声”。理想的结果是提高 1 类的 F1 分数(更好地捕捉事件),同时保持 0 类的 F1 分数不变(不增加虚假信号)。我们的过滤主模型表现理想,但过滤元模型的 0 类 F1 分数下降了 5.8%。为了缓解这一问题,我们可以调整模型中使用的超参数,或者改变特征集。

指标 未过滤
已过滤
Δ
召回率(1) 1.00 1.00
0%
精度(1) 0.33 0.38 +15.2%
F1(1) 0.49
0.55
+11.0%
表3:过滤与未过滤主模型的比较
指标 未过滤
已过滤
Δ
F1 (0) 0.69 0.65 -5.8%
F1(1) 0.57 0.60 +5.3%
正确率 0.64
0.63
-1.6%

表 4 : 过滤后与未过滤后的比较 元模型

数据缩减与模型性能之间的权衡可计算如下:

  • 性能保留率 =过滤后性能 / 未过滤性能 * 100
  • 净收益 = 性能保留率 - 数据减少量

如果我们获得正的净收益,那么该过滤器是有效的,应该使用。

模型 数据缩减 性能保留率 净收益
主模型 76.1% 112.2% +36.1%
元模型 76.1% 98.5% +22.4%

表 5: 权衡分析

通过比较未过滤信号和已过滤信号,我们可以得出以下结论:

  • CUSUM 滤波器成功地将 76.1% 的事件作为噪声丢弃。
  • 过滤提高了主模型和元模型的精度。
  • 尽管数据量减少了 76%,但过滤仅略微降低了元模型的整体性能。 1 类增长了 5.3%,0 类下降了 5.6%,尽管 0 类 F1 下降了,但我们仍然通过使用 CUSUM 滤波器获得了净收益。


元标注报告:布林带策略

下面的分类报告和 ROC 曲线强调了一个关键见解:元标注与现实的、具有风险意识的标注方案相结合才能取得成功。 


分类报告:固定时间范围主要模式;

图 1 :固定时间范围主模型分类报告


分类报告:固定时间范围元模型

图 2 :固定时间范围元模型分类报告


分类报告:三重屏障主模型

图 3 : 三重屏障主模型分类报告


分类报告:三重屏障元模型

图 4 :三重屏障元模型分类报告


接收者操作特性曲线

ROC曲线:固定时间范围与三重屏障标签

图 5 :固定时间范围和三重障碍元模型的ROC曲线


结果解读:解读模型的性能

这些结果的鲜明对比验证了核心论点:标注定义了成功。固定时间范围模型的分类报告揭示了一个根本性的学习失败;其无法区分高于随机水平的信号,这一点从其 ROC 曲线紧贴对角线得到了图形化的证实,这是无用分类器的标志。相比之下,三重屏障方法的报告显示了一个成功识别预测模式的模型,这一事实从其 ROC 曲线明显向左上角弯曲得到了强调,这表明在真正率和假正率之间存在显著的权衡。该 ROC AUC 值显著高于 0.5,表明该模型具有切实的预测能力。

更重要的是,精确度指标直接转化为交易现实:对于“1”类,更高的精确度意味着我们预测的盈利交易(元标签)中更有可能是正确的,从而提高策略的潜在盈利能力,并为基于信心的仓位规模提供具体的统计基础。

经济意义: 样本外表现

虽然三重屏障模型在 AUC 方面显示出统计学上的显著改善,但其真正的价值体现在模拟净值曲线中。图 7 显示,利用我们新的标记方法的策略实现了 -0.03% 的收益,最大回撤为 36.9%,显著优于基准固定期限策略,后者实现了 -0.71% 的收益,最大回撤为 76%。


固定期限策略性能

图 6 : 固定时间范围性能净值曲线


三重屏障策略性能

图 7 :三重屏障策略性能净值曲线


下表详细列出了每种标注方法的性能指标:

指标 固定时间范围 三重屏障
总回报 -0.709771 -0.028839
年化收益率 -0.338102 -0.009714
波动率 0.483111 0.37613
下行波动率 0.336945 0.231413
夏普比率 -4.778646 -0.021566
索提诺比率 -6.851611 -0.035053
95% 风险价值 -0.002864 -0.00215
95% 条件风险价值 -0.004164 -0.002992
偏度 -0.014451 0.034745
峰度 3.857222 2.507046
最大回撤 0.761708 0.368585
平均回撤 0.08375 0.039945
回撤持续时间 84天 01:18:50 32天 03:17:12
溃疡指数 0.217503 0.098507
卡玛比率 -0.443874 -0.026354
交易频率 3901 3969
每年交易次数 1300.040115 1322.701671
交易次数 37691 27426
每年交易次数 12560.83363 9139.93853
胜率 0.497546 0.504339
平均盈利 0.001266 0.001081
平均损失 -0.001322 -0.001105
最佳交易 0.014599 0.01451
最差交易 -0.013828 -0.010548
利润因子 0.952754 0.999799
预期 -0.000034 -0.000002
凯利准则 -0.027194 -0.002226
连续获利 77 92
连续损失 66 90
平均交易持续时间 0 天 00:39:18 0 天 06:22:15

表6 :样本外性能指标


结论

在 MetaTrader 5 机器学习蓝图的第二部分中,我们探讨了标注选择如何影响金融模型的行为和可靠性。通过超越固定时间范围,并采用路径依赖技术(如三重屏障方法),我们展示了如何将风险意识和真实的交易动态直接编码到学习过程中。

元标注作为一种策略性叠加技术应运而生,它能够过滤低置信度信号并提高精度 — 尤其是在与稳健的标注方案结合使用时效果更佳。分类报告和 ROC 曲线展示了这种分层方法如何即使在严格过滤的情况下也能提高信号质量。

但我们的旅程远未结束。

在下一篇文章中,我们将实现趋势扫描方法,该方法允许模型根据具有统计意义的价格变动动态选择其预测范围。这将在波动市场中实现更高水平的适应性。

我们还将通过引入样本权重来应对金融数据中的并发性挑战 — 即多个信号在时间上的重叠 — 这些权重反映了每个观测值的独特性和相关性。这确保我们的模型从真正独立的信号中学习,而非冗余的噪声。
最后,我们将探讨如何利用元标注生成的概率来更智能地确定交易金额。我们将使用概率置信度来调整仓位规模,而非二元执行 — 使模型信念与资本配置相一致。

这些增强功能共同将使我们更接近于为金融市场打造一个生产级的机器学习流程 — 这一流程不仅技术上稳健,而且在策略上与现实世界的交易行为相契合。

本文由MetaQuotes Ltd译自英文
原文地址: https://www.mql5.com/en/articles/18864

附加的文件 |
features.py (12.35 KB)
最近评论 | 前往讨论 (2)
daxiritchietrade
daxiritchietrade | 19 12月 2025 在 04:44

有件事我不明白:


如果训练模型时使用的是经过构建的K线(包含时间、 tick等数据),而不是原始tick数据,那么在实盘交易中是否也需要构建这些K线?

Patrick Murimi Njoroge
Patrick Murimi Njoroge | 18 4月 2026 在 22:45
daxiritchietrade #:

有件事我不明白:


如果训练模型时使用的是经过构建的K线(包含时间、 tick等数据),而不是原始tick数据,那么在实盘交易中是否也需要构建K线?

当然必须!我将发布一篇关于如何在 MQL5 中创建所有替代型K线类型以用于实盘交易的文章。
MQL5交易策略自动化(第三十一部分):构建基于价格行为的三重推进谐波形态系统 MQL5交易策略自动化(第三十一部分):构建基于价格行为的三重推进谐波形态系统
本文中,我们使用MQL5开发一个三重推进形态系统,利用拐点和斐波那契比率识别看涨和看跌的三重推进谐波形态,并依据用户的选择,以可自定义的入场、止损和止盈价位执行交易。 我们通过图表对象提供的可视化反馈,帮助交易者加深对市场的洞察。
通过协整股票进行统计套利(第四部分):实时模型更新 通过协整股票进行统计套利(第四部分):实时模型更新
本文介绍了一条简单而全面的统计套利流水线,用于交易一篮子协整股票。 文中提供了一个功能齐全的 Python 脚本,用于下载和存储数据,以及进行相关性、协整和平稳性检验;还提供了用于更新数据库的 MetaTrader 5 服务程序实现示例及相应的智能交易系统(EA)。 本文记录了一些设计选择,供读者参考,并帮助读者复现实验。
基于图论的算法套利交易 基于图论的算法套利交易
本文将三角套利表述为在有向图中寻找环的问题,其中顶点代表货币,边代表货币对,并以汇率为权重。 盈利环:权重乘积 > 1。 我们的弗洛伊德-沃沙尔(Floyd–Warshall)算法和深度优先搜索(DFS)算法能够找到返回起点并获得利润的最优货币兑换路径。
克服机器学习的局限性(第三部分):不可约误差的新视角 克服机器学习的局限性(第三部分):不可约误差的新视角
本文以全新视角探讨一种隐蔽的几何误差来源,它悄然影响着模型的每一次预测。 通过重新思考如何在交易中衡量和运用机器学习预测,我们揭示了这一被忽视的视角如何带来更精准的决策、更高的回报,以及如何更明智地运用那些我们自以为已经理解的模型。