OPEN-SOURCE SCRIPT

Machine Learning Random Forest Strategy | GainzAlgo

63 832
Machine Learning Random Forest Strategy

We are excited to introduce the Machine Learning Based Random Forest Strategy indicator.

What Even Is a Random Forest?

Machine learning and AI get thrown around so loosely these days that they've almost lost all meaning. So let's start from the beginning.

A Random Forest is an ensemble learning method. Instead of relying on a single model, it combines many models that work together and vote on an outcome.

The individual models are called decision trees.

A decision tree is essentially a flowchart:

  • Is a feature above or below a threshold?
  • If yes, go left.
  • If no, go right.
  • Continue until a prediction is reached.


The problem with a single decision tree is that it is fragile. Train it on slightly different data and you may get a completely different tree. This creates high variance and causes overfitting.

This is the same weakness many rule-based indicators suffer from. They perform well in one market regime and break down when conditions change.

A Random Forest solves this problem through two core mechanisms:

  • Bootstrap Sampling — Each tree is trained on a random subset of historical data using sampling with replacement.
  • Random Feature Selection — Each tree can only evaluate a random subset of features at every split.


Without random feature selection, every tree would focus on the same dominant signal and become nearly identical.

By forcing trees to learn different relationships, prediction errors become less correlated. When many uncorrelated predictors are averaged together, noise tends to cancel out while useful signal remains.

This is the foundation of ensemble learning and the reason Random Forests remain one of the most widely used machine learning models.

The Pine Script Problem (And How We Solved It)

Pine Script was never designed to support traditional machine learning workflows.

There are no native machine learning primitives, no recursion, strict execution limits, and memory is largely restricted to arrays and matrices.

Building a traditional multi-level decision tree inside Pine Script is therefore extremely difficult.

The solution was to use decision stumps.

A decision stump is simply a decision tree with exactly one split.

By themselves, stumps are weak predictors. However, when many stumps are combined together using random feature selection, they form a legitimate shallow Random Forest.

The core ensemble behavior remains intact:

  • Each stump learns a slightly different relationship.
  • Prediction errors become decorrelated.
  • Averaging outputs creates a more stable forecast.


This is not a workaround.

A depth-1 Random Forest is still a Random Forest. Production libraries such as scikit-learn simply allow deeper trees, while the underlying ensemble mechanism remains the same.

Threshold Optimization Using Information Gain

A naive stump implementation would select completely random thresholds.

The problem is that random thresholds often produce meaningless 50/50 predictions.

To solve this, the model performs a threshold search.

Each stump evaluates multiple candidate thresholds and selects the one that maximizes Information Gain using Gini Impurity.

Gini Impurity Explained

  • Gini = 0 → Perfectly pure node.
  • Gini = 0.5 → Completely mixed node.
  • Lower values are better.


Information Gain measures how much impurity is reduced after a split.

The model evaluates multiple threshold candidates and selects the threshold that best separates bullish and bearish outcomes.

This is the same methodology used by scikit-learn's DecisionTreeClassifier using the Gini criterion.

The Two Models Running In Parallel

The indicator actually runs two separate Random Forest models simultaneously.

1. RF Classifier

The classifier answers a binary question:

"Is the next move likely bullish or bearish?"

It outputs a probability representing the likelihood that the next close will be higher than the current close.

This probability drives the signal generation process.

  • Bull probability exceeds threshold → ▲ Bullish Signal
  • Bear probability exceeds threshold → ▼ Bearish Signal


2. Regression Forest

The regression forest estimates the magnitude of the next move.

Instead of predicting direction, it predicts expected return.

This value appears as "Exp. Ret" inside the statistics table.

Having both models creates stronger confirmation.

  • High Bull Probability + Positive Expected Return = Strong Confirmation
  • High Bear Probability + Negative Expected Return = Strong Confirmation
  • Conflicting Signals = Reduced Conviction


Features: What The Model Actually Looks At

All features are normalized to a 0-100 scale.

Anchor Oscillator

Users can select:

  • RSI
  • MFI
  • Stochastic
  • Z-Score


This acts as the model's primary momentum or mean reversion feature.

Trend Correlation Feature

The model measures how strongly price has been correlated with time over a specified lookback period.

High values indicate strong directional trends.

Low values indicate choppy or sideways conditions.

Momentum / ATR Feature

Raw momentum is normalized using ATR.

This allows momentum strength to remain comparable across different volatility environments.

The Rolling Training Window

The model does not train on all historical data.

Instead, it continuously trains on the most recent N bars.

Every new bar:

  • Oldest sample is removed.
  • Newest sample is added.
  • Model retrains using current market conditions.


This is critical because markets are non-stationary.

Patterns that worked years ago may no longer be relevant today.

The rolling window helps the model adapt to changing market conditions.

Preventing Lookahead Bias

Many TradingView machine learning indicators accidentally introduce lookahead bias.

This occurs when a model trains using information that would not have been available at the time of the prediction.

This implementation avoids that problem by using lagged feature values and future returns as targets.

The model only learns from information that genuinely existed before the outcome occurred.

Adaptive Threshold: The Self-Correcting Layer

One of the most unique aspects of this indicator is its adaptive threshold system.

The default probability threshold is 60%.

However, that threshold is not fixed.

After trades resolve:

  • Strong recent performance → Threshold remains relaxed.
  • Weak recent performance → Threshold automatically increases.


This forces the model to demand greater conviction during difficult market conditions.

When active, an orange ▲ marker appears next to the threshold value inside the statistics table.

This indicates that the model has tightened its own standards due to recent underperformance.

Signal Logic & Cooldown

Signals are not generated continuously.

Instead, the indicator uses edge-detection logic.

Signals only trigger when probability crosses above the required threshold.

  • Cross Above Threshold → New Signal
  • Remain Above Threshold → No New Signal


Additionally, a cooldown period prevents repetitive signals in the same direction.

The default cooldown is 10 bars.

This reduces signal clustering and improves overall readability.

Reading The Statistics Table

The table provides a complete snapshot of model activity.

  • Bull Prob — Current bullish probability estimate.
  • Signal — Current directional bias.
  • Exp. Ret — Expected return estimate.
  • Anchor — Selected oscillator value.
  • Eff. Thresh — Current effective threshold.


The backtest section includes:

  • Total Signals
  • Win Rate
  • Cumulative PnL
  • Average Trade PnL
  • Profit Factor
  • Wins & Losses


These values serve as a reality check based on current settings and chart conditions.

How To Use The Indicator

Do not blindly chase every arrow.

The strongest opportunities occur when multiple components align.

Look for:

  • High Bull Probability
  • Positive Expected Return
  • Clear Trend Structure
  • Supportive Market Conditions


When Bull Probability and Expected Return disagree, consider that a warning sign and reduce conviction.

Training Window & Tree Selection

The training window controls how much recent history the model learns from.

  • Short Window = Faster Adaptation
  • Long Window = Greater Stability


The number of trees controls prediction smoothness.

  • More Trees = Smoother Predictions
  • Fewer Trees = Faster Computation


Default settings provide a balanced starting point for most markets.

ADX Filtering

Optional ADX filtering can be enabled to isolate signals during stronger trending environments.

This tends to perform particularly well on higher timeframes.

What This Isn't

A few honest disclaimers:

  • This is not a deep neural network.
  • This is not a full-depth Random Forest implementation.
  • This is not a guaranteed profit system.
  • This is not immune to changing market conditions.


The model uses depth-1 decision stumps due to Pine Script limitations.

While this prevents complex nonlinear interactions, it preserves the core ensemble learning principles that make Random Forests effective.

The indicator intentionally uses only a handful of carefully selected features rather than overwhelming the model with unnecessary inputs.

Wrapping It Up

The Machine Learning Random Forest Strategy combines legitimate ensemble learning concepts with practical market analysis.

By leveraging Random Forest classification, regression forecasting, adaptive probability thresholds, and rolling retraining windows, the indicator provides a unique framework for evaluating both direction and expected magnitude of future price movement.

Use it as a decision-support tool, combine it with sound risk management, and let probability—not prediction—guide your trading process.

Thông báo miễn trừ trách nhiệm

Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.