ML5 Machine Learning and Data Science Library for MQL5
repository·main·Indexed 42 days ago
https://github.com/megajoctan/male5A Python-inspired machine learning and data science library for the MQL5 programming language, enabling advanced data processing within MetaTrader 5. It includes implementations for dimensionality reduction (CLDA, CPCA, CNMF, CTruncatedSVD), ensemble learning (AdaBoost, CRandomForestClassifier, CRandomForestRegressor), and linear models (CLinearRegression, CLogisticRegression, CPolynomialRegression).
What's inside ML5
- ML5 is a Python-like Machine Learning and Data Science library designed specifically for the MQL5 programming language. It allows developers to implement machine learning workflows and data science operations directly within the MetaTrader 5 environment.
Use the CNaiveBayes class for classification
mainTheCNaiveBayesclass implements a Naive Bayes classifier in MQL5. It is a probabilistic classifier that assumes feature independence to simplify prediction calculations. You can use it to train a model on existing data and then predict labels for new feature sets.How linear, logistic, and polynomial regression differ
mainDepending on your data and goal, you should choose one of the following models:
- Linear Regression (
CLinearRegression): Use when you want to predict a continuous value and assume a proportional relationship between independent and dependent variables ($y = \beta_0 + \beta_1x_1 + ...$). - Logistic Regression (
CLogisticRegression): Use for binary classification (predicting 0 or 1). It uses a sigmoid function to map inputs to a probability between 0 and 1. - Polynomial Regression (
CPolynomialRegression): Use when the relationship between variables is non-linear. It fits a polynomial function ($y = \beta_0 + \beta_1x + \beta_2x^2 + ...$) to capture curves in the data.
- Linear Regression (
Component Selection Criteria for CLDA and CPCA
mainWhen using
CLDAorCPCA, you can specify how the number of components is determined using them_criterionmember variable via theCRITERION_enum:CRITERION_VARIANCE: Retains components that explain a specific percentage of variance (defined by athreshold).CRITERION_KAISER: Retains components with eigenvalues greater than 1.CRITERION_SCREE_PLOT: Uses visual analysis of the scree plot to determine significant eigenvalues.
Use AdaBoost for Ensemble Learning
mainThe
AdaBoostclass inadaboost.mqhimplements the Adaptive Boosting algorithm, which combines multiple weak learners into a single strong learner. It works by iteratively training learners on a weighted dataset, where misclassified points receive higher weights in subsequent iterations.Key features:
- Flexible Weak Learners: Supports both
DecisionTreeandLogisticRegressionnamespaces. - Hyperparameter Control: You can configure the number of estimators, reproducibility via
random_state, and bootstrapping behavior.
// Example conceptual usage of AdaBoost // Note: Specific implementation details depend on the chosen namespace (DecisionTree or LogisticRegression) AdaBoost model(50, 42, true); model.fit(x_data, y_labels); int prediction = model.predict(new_x_vector);- Flexible Weak Learners: Supports both
Install ML5 for MetaTrader 5
mainTo use ML5 in your MQL5 projects, you must manually install the library files into your MetaTrader 5 terminal directory.
- Download the repository as a ZIP file or clone it from the releases section.
- Locate the
ML5folder within the extracted contents. - Copy the
ML5folder into theIncludedirectory of your MetaTrader 5 terminal data path.
Your directory structure should look like:
[MetaTrader5 Data Path]/MQL5/Include/ML5/.Use CDecisionTreeRegressor for regression tasks
mainThe
CDecisionTreeRegressorclass is used for regression problems (predicting continuous numerical values). It specializes in maximizing variance reduction during the splitting process.Hyperparameters:
min_samples_split: The minimum number of samples required to split an internal node.max_depth: The maximum depth of the tree.
Core Methods:
fit(matrix &x, vector &y): Trains the model using a matrix of independent variablesxand a vector of continuous target valuesy.predict(const vector &x): Returns the predicted continuous value for a single data point.
// Example initialization and training CDecisionTreeRegressor regressor(2, 5); regressor.fit(features_matrix, target_values_vector); // Predict a continuous value double value = regressor.predict(new_sample_vector);Use the CPolynomialRegression class for non-linear modeling
mainThe
CPolynomialRegressionclass extends linear regression by fitting a higher-degree polynomial function, allowing it to capture complex non-linear relationships.Initialization
Set the polynomial degree during construction:
CPolynomialRegression(int degree=2)Training and Prediction
fit(matrix &x, vector &y): Trains the model using the specified degree.predict(vector &x)orpredict(matrix &x): Predicts the dependent variable for new data points.
Degree Selection with BIC
You can use the Bayesian Information Criterion (BIC) to find the optimal polynomial degree to avoid overfitting:
void BIC(ulong k, vector &bic, int &best_degree)k: A vector of degree values to evaluate.bic: Output vector where BIC values for each degree inkare stored.best_degree: Output variable that will store the recommended degree (the one with the lowest BIC).
// Initialize with degree 3 CPolynomialRegression model(3); model.fit(x_data, y_data); // Selecting the best degree using BIC vector degrees = {1, 2, 3, 4, 5}; vector bic_values; int best_deg; CPolynomialRegression bic_helper; bic_helper.BIC(degrees, bic_values, best_deg);Train a Naive Bayes model with fit()
mainTo train the classifier, use the
fit(matrix &x, vector &y)method.x: Amatrixrepresenting the input features.y: Avectorrepresenting the target labels.
During training, the class calculates the prior probability of each class and estimates the conditional probability of each feature value given each class (utilizing Laplace smoothing to handle unseen features).
void fit(matrix &x, vector &y);Use CRandomForestClassifier for Classification
mainThe
CRandomForestClassifierclass implements a random forest ensemble specifically for classification tasks. It builds multiple decision trees using random subsets of features and bootstrapped samples to reduce variance and prevent overfitting.Constructor
CRandomForestClassifier(uint n_trees=100, uint minsplit=NULL, uint max_depth=NULL, int random_state=-1)n_trees: Number of trees in the forest.minsplit: Minimum samples required to split a node.max_depth: Maximum depth of the trees.random_state: Seed for reproducibility.
Methods
void fit(matrix &x, vector &y, bool replace=true, errors_classifier err=ERR_ACCURACY):x: Independent variables.y: Class labels.replace: Iftrue, uses bootstrapping (sampling with replacement).err: Error metric for training evaluation (default:ERR_ACCURACY).
double predict(vector &x): Predicts the class label for a single data point.vector predict(matrix &x): Predicts class labels for multiple data points.
Use the CLinearRegression class for linear modeling
mainThe
CLinearRegressionclass implements linear regression to model the relationship between a dependent variable and one or more independent variables. It supports two training methods: Least Squares for direct optimization and Gradient Descent for iterative optimization.Training Methods
fit_LeastSquare(matrix &x, vector &y): Fits the model by minimizing the sum of squared errors using the least squares method.fit_GradDescent(matrix &x, vector &y, double alpha, uint epochs = 1000): Fits the model iteratively using gradient descent. You must provide a learning ratealphaand can optionally specify the number ofepochs.
Prediction
Once trained, you can predict values using:
predict(vector &x): For a single new data point.predict(matrix &x): For multiple new data points (each row in the matrix is a data point).
CLinearRegression model; model.fit_GradDescent(x_data, y_data, 0.01, 500); // Predict a single point vector single_point = ...; double prediction = model.predict(single_point); // Predict multiple points matrix multiple_points = ...; vector predictions = model.predict(multiple_points);Use the CTruncatedSVD class for Truncated SVD
mainThe
CTruncatedSVDclass implements Truncated Singular Value Decomposition for dimensionality reduction and feature extraction.Constructor
CTruncatedSVD(uint k=0)k: Number of top singular values/components to retain. If0, it is determined automatically.
Public Methods
matrix fit_transform(matrix& X): Trains the model onXand returns the transformed data.matrix transform(matrix &X): Transforms new dataXusing the trained model.vector transform(vector &X): Transforms a single data pointXusing the trained model.
// Example usage of CTruncatedSVD CTruncatedSVD svd(10); matrix reduced_X = svd.fit_transform(X);