N-BEATSネットワークを用いたFX取引用EA
最新のFX自動売買ロボットは、今でも20年前の指標を使用しています。 移動平均線のクロスオーバーが発生し、RSIが70を上回り、MACDが下降に転じると、ロボットは数百万ドル規模の売買判断を下します。 荒唐無稽に聞こえるかもしれませんが、ほとんどのエキスパートアドバイザー(EA)はこのように動作しています。
金融市場には、従来のアプローチが見過ごしている重要な特徴があります。 信号対雑音比は約1:10で、価格変動全体の10分の9はランダムな変動です。 長期依存関係が重要な役割を果たします。1か月前の欧州中央銀行の決定が現在のユーロ為替レートにも影響を及ぼす可能性がありますが、従来の指標はこれを考慮していません。
市場の非定常性は、問題をさらに複雑にします。 1か月前に有効だったパターンも、マクロ経済情勢や主要な市場参加者の行動の変化によって、もはや通用しなくなる可能性があります。 どのような取引システムであれ、こうした変化に対応できなければなりません。
そのため、私たちはN-BEATSアーキテクチャを採用しました。これは、複雑な時間的依存性を処理するために特別に設計された、時系列予測における革新的なアプローチです。
N-BEATS:時系列解析におけるアーキテクチャの飛躍的進歩
Element AIの研究者たちは、早くも2019年に、予測のための根本的に新しいアプローチを提案しました。 既存のRNNやCNNのアーキテクチャを修正するのではなく、彼らは「予測タスクにはどのアーキテクチャが理想的か」という根本的な問いを投げかけました。
N-BEATSは、時系列分解の原理に基づいています。 ある楽曲を想像してみてください。全体の響きから次の音符を予測しようとするのではなく、メロディー、リズム、ハーモニーを個別に分析し、それらを組み合わせて予測を導き出すのです。 同様に、N-BEATSは時系列データをトレンド、季節変動、および残差パターンに分解します。
このアーキテクチャでは残差学習を採用しており、各ブロックは将来を予測するだけでなく、過去のデータを説明する役割も担います。 説明が不正確な場合、その誤差は次のブロックに引き継がれます。 まるで刑事の捜査のようです。各捜査官が証拠の一部について説明し、未解決の疑問を同僚に引き継いでいきます。
N-BEATSの重要な利点は、解釈可能性にあります。 従来のニューラルネットワークの「ブラックボックス」とは異なり、このアーキテクチャでは、予測においてトレンドがどのような役割を果たし、季節変動がどのような役割を果たしているかを明らかにすることができます。 トレーダーにとって、これは「何が起こるか」だけでなく、「なぜそうなるのか」も理解することを意味します。
標準的なベンチマークを用いたテストの結果は、科学界に衝撃を与えました。 N-BEATSは、LSTMネットワークやTransformerアーキテクチャを含む、既存のあらゆる手法を上回る性能を示しました。 最も印象的なのは、外部の特徴量を用いることなく、時系列データそのものの履歴データのみを用いてこれを達成した点です。
RNNとは異なり、N-BEATSは入力シーケンスを厳密に順次処理するのではなく、並列に処理することができます。 アルゴリズム取引では、これは動きの速い市場でもリアルタイムで予測できることを意味します。
しかし、学術研究で用いられるアーキテクチャを混沌とした為替市場の世界に適応させるには、大幅な修正が必要となります。 点推定値ではなく分位点予測を用いること、多変量入力、および市場ノイズに対する特別な処理が必要となります。
勾配を保持するMatrix構造体の基本構造
MetaTrader 5には機械学習用の既製のツールが用意されていないため、すべてを一から構築する必要があります。 本システムは、データだけでなく各要素の勾配も格納するMatrix構造体を基盤としています。
struct Matrix { double data[]; double gradients[]; // Key complement for backprop int rows, cols; void Init(int r, int c) { rows = r; cols = c; ArrayResize(data, r * c); ArrayResize(gradients, r * c); ArrayInitialize(data, 0.0); ArrayInitialize(gradients, 0.0); } double Get(int r, int c) { if(r < 0 || r >= rows || c < 0 || c >= cols) return 0.0; return data[r * cols + c]; } void AddGrad(int r, int c, double grad) { if(r < 0 || r >= rows || c < 0 || c >= cols) return; gradients[r * cols + c] += grad; // Accumulation of gradients } void ZeroGrad() { ArrayInitialize(gradients, 0.0); // Zeroing before a new iteration } };
この構造体により、ネットワークの各層は勾配を自動的に蓄積し、それを前の層へと伝達することができます。
SiLU関数はニューロンの活性化に使用され、従来のReLUと比較して金融データにおいてより良い結果を示します。 誤差逆伝播法を正しく実行するためには、関数そのものだけでなく、その導関数も実装することが重要です。// SiLU (Swish) activation is smoother than ReLU double SiLU(double x) { double sig = 1.0 / (1.0 + MathExp(-MathMin(MathMax(x, -50), 50))); return x * sig; } double SiLUDerivative(double x) { double sig = 1.0 / (1.0 + MathExp(-MathMin(MathMax(x, -50), 50))); return sig * (1.0 + x * (1.0 - sig)); } // Sigmoid for the output layer double Sigmoid(double x) { return 1.0 / (1.0 + MathExp(-MathMin(MathMax(x, -50), 50))); } double SigmoidDerivative(double x) { double s = Sigmoid(x); return s * (1.0 - s); }
入力値を-50から50の範囲に制限することで、指数関数の計算時のオーバーフローを防ぎます。これは、ノイズの多い金融データを用いた学習の安定性にとって極めて重要です。
単純な勾配降下法は、ノイズのレベルが高いため、金融時系列データにはあまり適していません。 そこで、勾配の履歴に基づいて各パラメータの学習率を適応的に調整するAdamオプティマイザを実装します。
struct AdamOptimizer { Matrix m, v; // Momentum and speed double beta1, beta2, eps; int step; void Init(int rows, int cols) { m.Init(rows, cols); v.Init(rows, cols); beta1 = 0.9; beta2 = 0.999; eps = 1e-8; step = 0; } void Update(Matrix &weights, double lr, double weight_decay = 0.01) { step++; for(int i = 0; i < weights.rows; i++) { for(int j = 0; j < weights.cols; j++) { double grad = weights.GetGrad(i, j) + weight_decay * weights.Get(i, j); // Update moments double m_val = beta1 * m.Get(i, j) + (1 - beta1) * grad; double v_val = beta2 * v.Get(i, j) + (1 - beta2) * grad * grad; m.Set(i, j, m_val); v.Set(i, j, v_val); // Bias correction double m_hat = m_val / (1 - MathPow(beta1, step)); double v_hat = v_val / (1 - MathPow(beta2, step)); // Update weights double update = lr * m_hat / (MathSqrt(v_hat) + eps); weights.Set(i, j, weights.Get(i, j) - update); } } weights.ZeroGrad(); // Clear gradients after updating } };
N-BEATSブロックにおける順伝播と逆伝播
各N-BEATSブロックは、複雑な一連の演算を実行します。 逆伝播に備えて中間値を保存しておくことが極めて重要です。
struct NBeatsBlock { Matrix fc1_w, fc1_b, fc2_w, fc2_b, theta_projection; AdamOptimizer fc1_opt, fc2_opt, theta_opt; // Intermediate values for backprop Matrix fc1_input, fc1_output, fc2_input, fc2_output; void Forward(Matrix &input_patch, Matrix &backcast, Matrix &forecast) { // Save the input for backprop fc1_input.Copy(input_patch); // FC1 layer fc1_output.Init(1, HIDDEN_SIZE); for(int j = 0; j < HIDDEN_SIZE; j++) { double s = 0.0; for(int i = 0; i < input_patch.cols; i++) s += input_patch.Get(0, i) * fc1_w.Get(i, j); s += fc1_b.Get(0, j); fc1_output.Set(0, j, s); // Save BEFORE activation } // Activation with saving for backprop fc2_input.Init(1, HIDDEN_SIZE); for(int j = 0; j < HIDDEN_SIZE; j++) { fc2_input.Set(0, j, SiLU(fc1_output.Get(0, j))); } // Similar for FC2 layer... // Theta projection and backcast/forecast generation } void Backward(Matrix &backcast_grad, Matrix &forecast_grad) { // Backprop starts with output gradients // Combine backcast and forecast gradients Matrix theta_grad; theta_grad.Init(1, theta_projection.cols); // Calculate theta projection gradients for(int i = 0; i < theta_projection.cols; i++) { double grad = 0.0; if(i < backcast_size) { grad += backcast_grad.GetGrad(0, i); } else { grad += forecast_grad.GetGrad(0, i - backcast_size); } theta_grad.SetGrad(0, i, grad); } // Backprop via theta projection к FC2 Matrix fc2_grad; fc2_grad.Init(1, HIDDEN_SIZE); for(int i = 0; i < HIDDEN_SIZE; i++) { double grad_sum = 0.0; for(int j = 0; j < theta_projection.cols; j++) { grad_sum += theta_grad.GetGrad(0, j) * theta_projection.Get(i, j); // Accumulate gradients for the theta_projection weights theta_projection.AddGrad(i, j, theta_grad.GetGrad(0, j) * fc2_output.Get(0, i)); } fc2_grad.SetGrad(0, i, grad_sum); } // Backprop via SiLU activation Matrix fc2_input_grad; fc2_input_grad.Init(1, HIDDEN_SIZE); for(int i = 0; i < HIDDEN_SIZE; i++) { double grad = fc2_grad.GetGrad(0, i) * SiLUDerivative(fc1_output.Get(0, i)); fc2_input_grad.SetGrad(0, i, grad); } // Backprop through FC1 layer to inputs // ... similar calculations for all layers } };
分位点損失関数
不確実性を予測するために、通常のMSEの代わりに分位点損失を用います。
void Train(double &time_series[], double target) { step_count++; // Forward pass for all quantiles double predictions[QUANTILE_LEVELS]; Predict(time_series, predictions); // Calculate quantile losses for(int q = 0; q < QUANTILE_LEVELS; q++) { double pred = predictions[q]; double error = target - pred; double quantile = quantiles[q]; // 0.1, 0.5, 0.9 // Quantile loss double loss_weight = (error >= 0) ? quantile : (1.0 - quantile); double focal_weight = class_weights.GetFocalWeight(target, pred); double loss = focal_weight * loss_weight * MathAbs(error); // Gradient for quantile loss double grad_wrt_pred = focal_weight * loss_weight * ((error >= 0) ? -1.0 : 1.0); double grad_wrt_logit = grad_wrt_pred * SigmoidDerivative(pred); // Backprop to output weights for(int h = 0; h < HIDDEN_SIZE; h++) { double grad = grad_wrt_logit * pooled_features[h]; output_proj[q].SetGrad(h, 0, grad); } } // Run a backward pass through the entire network BackpropagateToAllLayers(); // Update the weights of all layers UpdateAllWeights(); }
入力データの質は、あらゆる機械学習モデルの成功にとって極めて重要ですが、取引アルゴリズムの場合、それが口座の保全と破綻を分ける決定的な要因となり得ます。
多変量特徴量
単なる終値の連続データではなく、豊富な特徴量セットを使用しています。
void PrepareInputData(MqlRates &rates[], double &input_data[], int input_bars) { ArrayResize(input_data, input_bars * 2); // 2 features per bar for(int i = 0; i < input_bars; i++) { if(i < ArraySize(rates) - 1) { // Feature 1: Normalized price change double price_change = (rates[i].close - rates[i].open) / rates[i].open; input_data[i * 2] = MathMax(-1.0, MathMin(1.0, price_change * 100)); // Feature 2: Logarithmically normalized volume double vol_ratio = (rates[i].tick_volume > 0) ? MathLog(1.0 + rates[i].tick_volume / 1000.0) : 0.0; input_data[i * 2 + 1] = MathMax(0.0, MathMin(1.0, vol_ratio / 10.0)); } else { input_data[i * 2] = 0.0; input_data[i * 2 + 1] = 0.0; } } }
値を妥当な範囲にクリッピングすることで、極端な外れ値がモデルの学習に影響を与えるのを防ぐことができます。
ノイズに頑健な正規化
金融データには、価格の急変、技術的な不具合、異常な出来高など、さまざまな異常現象が数多く見られます。 単純な最小最大正規化は、たった1つの外れ値によって破綻する可能性があります。
void RobustNormalization(double &data[], int window_size = 200) { int data_size = ArraySize(data); for(int i = window_size; i < data_size; i++) { // Calculate robust statistics for a sliding window double window_data[]; ArrayResize(window_data, window_size); for(int j = 0; j < window_size; j++) { window_data[j] = data[i - window_size + j]; } // Median instead of mean (robust to outliers) ArraySort(window_data); double median = window_data[window_size / 2]; // MAD (Median Absolute Deviation) instead of standard deviation double deviations[]; ArrayResize(deviations, window_size); for(int j = 0; j < window_size; j++) { deviations[j] = MathAbs(window_data[j] - median); } ArraySort(deviations); double mad = deviations[window_size / 2]; // Robust normalization if(mad > 1e-8) { data[i] = MathMax(-3.0, MathMin(3.0, (data[i] - median) / mad)); } } }
平均値と標準偏差の代わりに中央値と中央絶対偏差(MAD)を用いることで、外れ値の影響を受けにくい正規化が可能になります。
異常の検出と対応
システムは、市場の異常な状況を自動的に検知する必要があります。
bool DetectMarketAnomaly(MqlRates &rates[], int lookback = 50) { if(ArraySize(rates) < lookback) return false; // Calculate volatility for the period double volatilities[]; ArrayResize(volatilities, lookback); for(int i = 1; i < lookback; i++) { double change = MathAbs(rates[i].close - rates[i-1].close) / rates[i-1].close; volatilities[i] = change; } ArraySort(volatilities); double median_vol = volatilities[lookback / 2]; double vol_95 = volatilities[(int)(lookback * 0.95)]; // Current volatility double current_vol = MathAbs(rates[0].close - rates[1].close) / rates[1].close; // Anomaly if current volatility exceeds 95th percentile 2+ times return (current_vol > vol_95 * 2.0); }異常が検出された場合、取引システムは一時的にポジションサイズを縮小したり、取引を一時停止したりすることがあります。
従来の予測手法では、単一の点推定値、つまり「価格はこうなるだろう」という予測が提示されます。 しかし、取引を行う上では、予測の不確実性を理解することが極めて重要です。 このため、本実装のN-BEATSでは分位点予測を採用しています。
システムは、単一の値ではなく、悲観的なシナリオ(0.1分位点)、現実的な予測(中央値)、楽観的なシナリオ(0.9分位点)という3つの推定値を出力します。 分位点間の差は、予測に対するモデルの信頼度を示しています。
分位点予測の学習には、対象の分位点に応じて過小推定と過大推定に異なるペナルティを課す、特殊な損失関数を用います。
void ProcessQuantilePredictions(double &predictions[]) { double q10 = predictions[0]; // Pessimistic scenario double q50 = predictions[1]; // Median forecast double q90 = predictions[2]; // Optimistic scenario // Calculate the model uncertainty double uncertainty = q90 - q10; double confidence = 1.0 - MathMin(1.0, uncertainty / 0.4); // Normalize [0,1] // Dynamically adjust position size double base_lot = CalculateBaseLotSize(); double adjusted_lot = base_lot * confidence; if(q50 > 0.65 && uncertainty < 0.2) { // High growth confidence, low uncertainty OpenPosition(ORDER_TYPE_BUY, adjusted_lot * 1.5, "High confidence"); } else if(q50 > 0.6 && uncertainty < 0.3) { // Moderate confidence in growth OpenPosition(ORDER_TYPE_BUY, adjusted_lot, "Medium confidence"); } else if(q10 > 0.55) { // Even the pessimistic scenario shows growth OpenPosition(ORDER_TYPE_BUY, adjusted_lot * 0.7, "Conservative long"); } Print("Uncertainty: ", DoubleToString(uncertainty, 3), " | Confidence: ", DoubleToString(confidence, 3), " | Adjusted lot: ", DoubleToString(adjusted_lot, 2)); }
フォーカル損失:クラス不均衡への対処
金融市場は本質的に不均衡であり、穏やかな取引が続く中に、まれに激しい値動きが発生します。 標準的な損失関数ではこの問題に対処できないため、フォーカル損失を用います。
struct ClassWeights { double strong_bull, weak_bull, neutral, weak_bear, strong_bear; void UpdateWeights(int &counts[]) { int total = counts[0] + counts[1] + counts[2] + counts[3] + counts[4]; if(total == 0) return; // Inverted weights - rare classes get more weight strong_bear = (counts[0] > 0) ? (double)total / (5 * counts[0]) : 1.0; weak_bear = (counts[1] > 0) ? (double)total / (5 * counts[1]) : 1.0; neutral = (counts[2] > 0) ? (double)total / (5 * counts[2]) : 1.0; weak_bull = (counts[3] > 0) ? (double)total / (5 * counts[3]) : 1.0; strong_bull = (counts[4] > 0) ? (double)total / (5 * counts[4]) : 1.0; } double GetFocalWeight(double target, double pred) { double alpha = GetClassWeight(target); double pt = (target > 0.5) ? pred : (1.0 - pred); // Focal Loss: focuses on difficult samples return alpha * MathPow(MathMax(1.0 - pt, 1e-8), FOCAL_GAMMA); } };
フォーカル損失は、発生頻度は低いものの重要な市場イベント、つまり最も大きな利益を得られるイベントを、自動的に重視するようにします。
不確実性に基づく適応型ストップロス
従来のストップロスの設定方法は単純で、エントリー価格から一定のポイント数だけ離れた位置に設定するというものです。 当システムでは、予測された不確実性を使用しています。
double CalculateAdaptiveStopLoss(double entry_price, ENUM_ORDER_TYPE order_type, double uncertainty, double base_sl_points = 500) { // Increase stop loss when uncertainty is high double uncertainty_multiplier = 1.0 + uncertainty * 2.0; // [1.0, 3.0] double adaptive_sl_points = base_sl_points * uncertainty_multiplier; // Take into account the current volatility double atr = CalculateATR(14); // Average True Range for 14 periods double volatility_adjustment = MathMax(0.5, MathMin(2.0, atr / (Point() * 100))); adaptive_sl_points *= volatility_adjustment; double sl_price; if(order_type == ORDER_TYPE_BUY) { sl_price = entry_price - adaptive_sl_points * Point(); } else { sl_price = entry_price + adaptive_sl_points * Point(); } Print("Adaptive SL: base=", base_sl_points, " uncertainty_mult=", DoubleToString(uncertainty_multiplier, 2), " volatility_adj=", DoubleToString(volatility_adjustment, 2), " final=", DoubleToString(adaptive_sl_points, 0)); return sl_price; } double CalculateATR(int period) { double atr_values[]; if(CopyBuffer(iATR(Symbol(), Period(), period), 0, 0, 1, atr_values) <= 0) { return Point() * 100; // Fallback value } return atr_values[0]; }
MetaTrader 5の取引ロジックとの連携
強力なニューラルネットワークを構築しても、それだけでは目標達成への道半ばに過ぎません。 主な目標は、これを取引プラットフォームと統合し、リアルタイムで動作させ、すべてのティックを処理し、ミリ秒単位で取引判断を下せるようにすることです。
MetaTrader 5は、イベント駆動型モデルで動作します。 ティックが発生するたびに、また価格が変動するたびに、OnTick()関数が呼び出されます。 しかし、ティックごとにニューラルネットワークの負荷の高い計算を実行するのは非効率的であるため、賢くキャッシュを利用する仕組みが必要です。
datetime g_last_bar_time = 0; double g_cached_prediction = 0.5; bool g_prediction_valid = false; bool IsNewBar() { datetime current_bar_time = iTime(Symbol(), Period(), 0); if(current_bar_time != g_last_bar_time) { g_last_bar_time = current_bar_time; g_prediction_valid = false; // Cache is out of date return true; } return false; } void OnTick() { if(!g_net_initialized) return; // Perform light operations on every tick if(UseTrailingStop) UpdateTrailingStops(); // Heavy calculations only on the new bar if(IsNewBar()) { double prediction = GetAIPrediction(); // Computationally expensive operation g_cached_prediction = prediction; g_prediction_valid = true; ProcessTradingSignals(prediction); } // Check emergency exits on every tick if(g_prediction_valid) { CheckEmergencyExits(g_cached_prediction); } }ヒステリシス信号システム
「閾値を上回れば買い、下回れば売り」という単純なロジックは、信号のチャタリングという問題を引き起こします。 予測値が閾値付近で変動すると、システムはポジションの新規建てと決済を繰り返します。 その解決策はヒステリシスです。
void ProcessTradingSignalsWithHysteresis(double prediction) { static double last_prediction = 0.5; static datetime last_signal_time = 0; // Minimum interval between signals if(TimeCurrent() - last_signal_time < PeriodSeconds(Period()) * 2) return; int current_positions = CountPositions(); bool currently_long = HasLongPosition(); bool currently_short = HasShortPosition(); // Different thresholds for entry and exit (hysteresis) double long_entry_threshold = 0.70; double long_exit_threshold = 0.55; double short_entry_threshold = 0.30; double short_exit_threshold = 0.45; // Logic with hysteresis if(!currently_long && prediction > long_entry_threshold && last_prediction <= long_entry_threshold) { if(currently_short) CloseAllPositions("Signal reversal"); OpenPosition(ORDER_TYPE_BUY, prediction); last_signal_time = TimeCurrent(); Print("🚀 LONG ENTRY: ", DoubleToString(prediction, 3)); } else if(currently_long && prediction < long_exit_threshold && last_prediction >= long_exit_threshold) { CloseAllPositions("Long exit signal"); Print("📤 LONG EXIT: ", DoubleToString(prediction, 3)); } // Similar logic for short positions... last_prediction = prediction; }本番環境での継続学習
市場は絶えず変化しています。 1か月前にはうまく機能していたモデルでも、今日では役に立たないかもしれません。 したがって、継続学習の仕組みが必要となります。
struct ContinuousLearning { datetime last_retrain_time; double performance_buffer[]; int performance_window; double performance_threshold; void Init() { last_retrain_time = TimeCurrent(); performance_window = 100; // Track the last 100 trades performance_threshold = 0.45; // Degradation threshold ArrayResize(performance_buffer, performance_window); } void AddTradeResult(double prediction, double actual_outcome) { // Shift the buffer for(int i = 0; i < performance_window - 1; i++) { performance_buffer[i] = performance_buffer[i + 1]; } // Add a new result (1.0 = accurate prediction, 0.0 = completely wrong) double accuracy = 1.0 - MathAbs(prediction - actual_outcome); performance_buffer[performance_window - 1] = accuracy; // Check if retraining is necessary if(ShouldRetrain()) { ScheduleRetraining(); } } bool ShouldRetrain() { // Condition 1: Enough time has passed bool time_condition = (TimeCurrent() - last_retrain_time) > 24 * 3600; // Condition 2: Performance has decreased double avg_performance = 0.0; for(int i = 0; i < performance_window; i++) { avg_performance += performance_buffer[i]; } avg_performance /= performance_window; bool performance_condition = avg_performance < performance_threshold; return time_condition || performance_condition; } void ScheduleRetraining() { Print("🔄 Scheduling model retraining..."); Print("Average performance: ", DoubleToString(GetAveragePerformance(), 3)); // Retrain in a separate thread (simulate) RetrainModel(); last_retrain_time = TimeCurrent(); } }; ContinuousLearning g_learning_system;
N-BEATSは、多くのパラメータを持つ複雑なアーキテクチャです。 本番環境では、1ミリ秒の遅延でもコストにつながる可能性があるため、パフォーマンスの最適化は極めて重要です。
メモリ管理ネットワーク内の各行列には、数千ものパラメータが含まれることがあります。 適切なメモリ管理を行わないと、システムはすぐにリソースを使い果たしてしまいます。
struct MemoryManager { Matrix temp_matrices[]; int allocated_count; int max_temp_matrices; void Init() { max_temp_matrices = 100; ArrayResize(temp_matrices, max_temp_matrices); allocated_count = 0; } Matrix* AllocateTempMatrix(int rows, int cols) { if(allocated_count >= max_temp_matrices) { Print("⚠️ Temporary matrix pool exhausted!"); return NULL; } temp_matrices[allocated_count].Init(rows, cols); return &temp_matrices[allocated_count++]; } void ResetTempPool() { // Quick "release" without real deallocation allocated_count = 0; } void PrintMemoryUsage() { int total_elements = 0; for(int i = 0; i < allocated_count; i++) { total_elements += temp_matrices[i].rows * temp_matrices[i].cols; } double memory_mb = total_elements * sizeof(double) / (1024.0 * 1024.0); Print("Memory usage: ", DoubleToString(memory_mb, 2), " MB"); Print("Active matrices: ", allocated_count); } }; MemoryManager g_memory_manager;クリティカルパスのプロファイリング
実行時間が具体的にどこに費やされているかを把握することは重要です。
struct Profiler { string operation_names[]; ulong operation_times[]; int operation_counts[]; int num_operations; void Init() { num_operations = 0; ArrayResize(operation_names, 50); ArrayResize(operation_times, 50); ArrayResize(operation_counts, 50); } void StartTimer(string operation) { // MQL5 does not have high-precision timers, use GetMicrosecondCount() ulong start_time = GetMicrosecondCount(); // Search for an existing operation or create a new one int index = FindOrCreateOperation(operation); operation_times[index] = start_time; } void EndTimer(string operation) { ulong end_time = GetMicrosecondCount(); int index = FindOperation(operation); if(index >= 0) { ulong elapsed = end_time - operation_times[index]; operation_times[index] = elapsed; // Reuse to store time operation_counts[index]++; } } void PrintReport() { Print("=== PERFORMANCE REPORT ==="); for(int i = 0; i < num_operations; i++) { double avg_time_ms = operation_times[i] / (double)operation_counts[i] / 1000.0; Print(operation_names[i], ": ", DoubleToString(avg_time_ms, 3), " ms avg, ", operation_counts[i], " calls"); } } }; Profiler g_profiler; // Usage: void OptimizedPredict(double &time_series[]) { g_profiler.StartTimer("PatchEmbedding"); // ... patch embedding code g_profiler.EndTimer("PatchEmbedding"); g_profiler.StartTimer("StackForward"); // ... forward pass via stacks g_profiler.EndTimer("StackForward"); }
プロファイリングをおこなうことで、ボトルネックを特定し、本当に重要な部分に最適化の取り組みを集中させることができます。
ニューラルネットワークを搭載した自動売買ロボットは、単に実行してそのまま放置できるようなコードではありません。 これは、絶え間ない監視、診断、調整を必要とする複雑なシステムです。 適切な監視システムがなければ、どんなに完璧なアーキテクチャであっても、知らぬ間に性能が低下し、損失を出し始める可能性があります。
予測品質のリアルタイム監視第一の防衛策は、予測精度をリアルタイムで継続的に監視することです。
struct PredictionMonitor { double accuracy_buffer[]; double confidence_buffer[]; double actual_outcomes[]; int buffer_size, current_index; datetime last_evaluation; void Init(int size = 1000) { buffer_size = size; current_index = 0; ArrayResize(accuracy_buffer, buffer_size); ArrayResize(confidence_buffer, buffer_size); ArrayResize(actual_outcomes, buffer_size); ArrayInitialize(accuracy_buffer, 0.5); last_evaluation = TimeCurrent(); } void RecordPrediction(double prediction, double confidence) { confidence_buffer[current_index] = confidence; // Save the forecast for future evaluation // actual_outcomes will be filled later when the result is known } void RecordOutcome(double actual_movement) { if(current_index >= buffer_size) return; actual_outcomes[current_index] = actual_movement; // Calculate the forecast accuracy double predicted = confidence_buffer[current_index]; double accuracy = 1.0 - MathAbs(predicted - actual_movement); accuracy_buffer[current_index] = accuracy; current_index = (current_index + 1) % buffer_size; // Periodically display statistics if(TimeCurrent() - last_evaluation > 3600) { // Every hour PrintAccuracyReport(); last_evaluation = TimeCurrent(); } } void PrintAccuracyReport() { double total_accuracy = 0.0, total_confidence = 0.0; int valid_samples = 0; for(int i = 0; i < buffer_size; i++) { if(accuracy_buffer[i] > 0) { total_accuracy += accuracy_buffer[i]; total_confidence += confidence_buffer[i]; valid_samples++; } } if(valid_samples > 10) { double avg_accuracy = total_accuracy / valid_samples; double avg_confidence = total_confidence / valid_samples; Print("=== PREDICTION QUALITY REPORT ==="); Print("Average accuracy: ", DoubleToString(avg_accuracy * 100, 2), "%"); Print("Average confidence: ", DoubleToString(avg_confidence * 100, 2), "%"); Print("Valid samples: ", valid_samples); // Degradation warning if(avg_accuracy < 0.5) { Print("⚠️ WARNING: Model accuracy below random baseline!"); } if(avg_accuracy < avg_confidence - 0.1) { Print("⚠️ WARNING: Model overconfident - accuracy vs confidence gap!"); } } } double GetRecentAccuracy(int lookback = 100) { double sum = 0.0; int count = 0; for(int i = 0; i < MathMin(lookback, buffer_size); i++) { int idx = (current_index - i - 1 + buffer_size) % buffer_size; if(accuracy_buffer[idx] > 0) { sum += accuracy_buffer[idx]; count++; } } return (count > 0) ? sum / count : 0.5; } }; PredictionMonitor g_monitor;コンセプトドリフトの検出
金融市場は絶えず変化し続けています。 1か月前に有効だったパターンが、もはや通用しなくなっている可能性があります。 システムは、このような変化を自動的に検知する必要があります。
struct ConceptDriftDetector { double recent_performance[]; double historical_baseline; int window_size; bool drift_detected; datetime last_drift_check; void Init(int window = 200) { window_size = window; ArrayResize(recent_performance, window_size); historical_baseline = 0.55; // Base model accuracy drift_detected = false; last_drift_check = TimeCurrent(); } void AddPerformancePoint(double accuracy) { // Move the window for(int i = 0; i < window_size - 1; i++) { recent_performance[i] = recent_performance[i + 1]; } recent_performance[window_size - 1] = accuracy; // Check drift every 4 hours if(TimeCurrent() - last_drift_check > 4 * 3600) { CheckForDrift(); last_drift_check = TimeCurrent(); } } void CheckForDrift() { // Calculate the average performance in the window double window_mean = 0.0; int valid_count = 0; for(int i = 0; i < window_size; i++) { if(recent_performance[i] > 0) { window_mean += recent_performance[i]; valid_count++; } } if(valid_count < 50) return; // Not enough data window_mean /= valid_count; // Statistical test for significant deviation double variance = 0.0; for(int i = 0; i < window_size; i++) { if(recent_performance[i] > 0) { double diff = recent_performance[i] - window_mean; variance += diff * diff; } } variance /= (valid_count - 1); double std_error = MathSqrt(variance / valid_count); // Z test to determine the significance of the deviation double z_score = (window_mean - historical_baseline) / std_error; bool significant_drift = MathAbs(z_score) > 2.58; // 99% confidence level if(significant_drift && !drift_detected) { drift_detected = true; Print("🚨 CONCEPT DRIFT DETECTED!"); Print("Historical baseline: ", DoubleToString(historical_baseline, 3)); Print("Recent performance: ", DoubleToString(window_mean, 3)); Print("Z-score: ", DoubleToString(z_score, 2)); Print("Recommendation: Schedule model retraining"); // Automatically start retraining TriggerEmergencyRetraining(); } else if(!significant_drift && drift_detected) { drift_detected = false; Print("✅ Concept drift resolved - model performance stabilized"); } } void UpdateBaseline(double new_baseline) { historical_baseline = new_baseline; Print("📊 Performance baseline updated to ", DoubleToString(new_baseline, 3)); } }; ConceptDriftDetector g_drift_detector;警報および自動対応システム
重大な事態には、トレーダーが就寝中であったり対応できなかったりする場合でも、即座の対応が求められます。
struct AlertSystem { enum ALERT_LEVEL { INFO = 0, WARNING = 1, CRITICAL = 2, EMERGENCY = 3 }; struct Alert { ALERT_LEVEL level; string message; datetime timestamp; bool acknowledged; }; Alert active_alerts[]; int max_alerts; datetime last_notification; void Init() { max_alerts = 100; ArrayResize(active_alerts, max_alerts); last_notification = 0; } void RaiseAlert(ALERT_LEVEL level, string message) { // Look for a free slot for an alert int slot = -1; for(int i = 0; i < max_alerts; i++) { if(active_alerts[i].timestamp == 0) { slot = i; break; } } if(slot == -1) { // Replace the oldest alert datetime oldest = TimeCurrent(); for(int i = 0; i < max_alerts; i++) { if(active_alerts[i].timestamp < oldest) { oldest = active_alerts[i].timestamp; slot = i; } } } // Create an alert active_alerts[slot].level = level; active_alerts[slot].message = message; active_alerts[slot].timestamp = TimeCurrent(); active_alerts[slot].acknowledged = false; // Display in the log with the corresponding prefixes string prefix = GetAlertPrefix(level); Print(prefix, " ", message); // Critical alerts require immediate action if(level >= CRITICAL) { HandleCriticalAlert(message); } // Limit the frequency of notifications if(TimeCurrent() - last_notification > 300) { // No more than once every 5 minutes SendNotification(level, message); last_notification = TimeCurrent(); } } string GetAlertPrefix(ALERT_LEVEL level) { switch(level) { case INFO: return "ℹ️ INFO:"; case WARNING: return "⚠️ WARNING:"; case CRITICAL: return "🚨 CRITICAL:"; case EMERGENCY: return "🆘 EMERGENCY:"; default: return "❓ UNKNOWN:"; } } void HandleCriticalAlert(string message) { // Automatic actions for critical alerts if(StringFind(message, "accuracy") >= 0) { // Accuracy issues - reducing position size ReducePositionSizes(0.5); } else if(StringFind(message, "memory") >= 0) { // Memory issues - forced cleanup g_memory_manager.ResetTempPool(); } else if(StringFind(message, "drift") >= 0) { // Conceptual drift - stop trading until retraining DisableTrading("Concept drift detected"); } } void SendNotification(ALERT_LEVEL level, string message) { // In a real system this could be: // - Send email via web requests // - Push notifications via Telegram Bot API // - SMS via external services string notification = StringFormat("[%s] %s: %s", TimeToString(TimeCurrent()), EnumToString(level), message); // For demonstration purposes, we simply output it to the terminal Print("📱 NOTIFICATION SENT: ", notification); } }; AlertSystem g_alerts;
N-BEATSシステムの開発が完了し、実際の取引環境でその有効性を検証する段階に入りました。 MetaTrader 5にはプロ向けのテストツールが備わっており、今回はこれらを活用します。
N-BEATSロボットのテスト結果
残念ながら、本連載でこれまでに成果を上げたMambaやPatchTSTとは異なり、有望なアーキテクチャであるにもかかわらず、2025年1月から8月までのテスト期間では利益を上げることができませんでした。

このアルゴリズムに関する数十本の記事を調べ、EAの第2版を作成しても、状況はあまり改善しませんでした。

実装は技術的に複雑かつ洗練されていたものの、2025年1月から8月までの過去データを用いたテストでは、このシステムが安定した利益を生み出せないことが示されました。 これまで成功を収めてきたMambaやPatchTSTといったアーキテクチャとは異なり、N-BEATSは実際の取引環境で十分な成果を上げることができませんでした。
結論
今回の研究では、N-BEATSアーキテクチャを金融時系列の予測問題にそのまま適用しても、期待される結果は得られないことが示されました。 主な理由としては、外国為替データのノイズの多さ、市場マイクロストラクチャへの考慮の欠如、計算コストと得られた取引成績の改善が見合わなかったことが挙げられます。
それでも、このプロジェクトには大きな実用的価値があります。 MQL5でニューラルネットワークの実験を行うための基盤を構築し、誤差逆伝播法を一から実装するとともに、不確実性に基づくリスク管理ツールを開発しました。 さらに、コンセプトドリフトの検出やモデルの性能劣化への自動対応を含む監視・診断システムも実装しました。これらは、機械学習に基づく幅広い取引ソリューションにとっても注目に値します。
ここで紹介したコードは、金融市場の特性をより正確に反映する特化型アルゴリズムのさらなる研究・開発の基盤となり得ます。 これらの知見は、機械学習のアーキテクチャや手法を市場動態の特性に合わせて適応させる必要性を浮き彫りにするとともに、この分野で成功を収めるには、工学的な解決策と経済プロセスへの深い理解を組み合わせる必要があることを裏付けています。
| ファイル名 | ファイルの用途 |
|---|---|
| NBeats_TimeSeriesNet.mqh | モデルの第1版。 /Includeフォルダに配置してください。 |
| NBeats_TimeSeriesNetV2.mqh | モデルの第2版。 /Includeフォルダに配置してください。 |
| NBeats_EA.mq5 | EAの第1版。 /Expertsフォルダに配置してください。 |
| NBeats_EAV2.mq5 | EAの第2版。 /Expertsフォルダに配置してください。 |
MetaQuotes Ltdによってロシア語から翻訳されました。
元の記事: https://www.mql5.com/ru/articles/19317
警告: これらの資料についてのすべての権利はMetaQuotes Ltd.が保有しています。これらの資料の全部または一部の複製や再プリントは禁じられています。
この記事はサイトのユーザーによって執筆されたものであり、著者の個人的な見解を反映しています。MetaQuotes Ltdは、提示された情報の正確性や、記載されているソリューション、戦略、または推奨事項の使用によって生じたいかなる結果についても責任を負いません。