Loading…

Principal Component Analysis

Feed enough indicators into a model and most of them turn out to be saying the same thing. Four moving average distances, three momentum oscillators and a volatility ratio are all, to varying degrees, reading the same underlying trend - correlated inputs that inflate a model's apparent richness without adding real information, and can actively destabilise anything that assumes its inputs are independent. Principal component analysis answers this by finding new axes - linear combinations of the original columns - ranked by how much of the total variance each one explains. The first axis alone often captures the bulk of what several correlated indicators were separately measuring. This library computes that decomposition from raw first principles: a covariance matrix over the input columns, then the classical Jacobi eigenvalue algorithm (Numerical Recipes formulation) to find its eigenvalues and eigenvectors. Every matrix in this library is a flattened 1D array in row-major order - element (row, col) of an R x C matrix lives at data[row*C+col] - rather than a native 2D or matrix type, so the same function signatures and calling code work unchanged on both platforms. MQL5 does have its own native `matrix` type with a built-in eigen decomposition, but this library deliberately keeps the flattened-array interface so calling code that already builds a flattened sample from indicator buffers (the common case in an EA or indicator) ports across without changes. Jacobi is used instead of the more general QR algorithm because a covariance matrix is always symmetric, and Jacobi is simple, numerically stable, and exact in the limit for that specific case - no need for the extra machinery a non-symmetric solver would require. PCA_JacobiEigen repeatedly zeroes the current largest off-diagonal element with a plane rotation until the matrix is diagonal to within tolerance, accumulating the rotations into the eigenvector matrix as it goes. PCA_Run wires the whole pipeline together: covariance, eigen decomposition, descending sort by eigenvalue (largest variance first), and projection of the mean-centred data onto the top N components. PCA_ExplainedVarianceRatio answers the practical question of how many components are actually worth keeping. Notes and limitations - All matrices are flattened row-major 1D arrays: element (row, col) of an R x C matrix is data[row*C+col]. Passing an array sized for the wrong rows/cols reads garbage or runs past the array - the caller owns getting the dimensions right, the library only validates row/column counts, not array length. - PCA_JacobiEigen is capped at 100 sweeps. Every covariance matrix tested at realistic sizes (a handful to a few dozen indicator columns) converges well inside that, but a return of -1 means the cap was hit - the eigenvalues returned are still the best approximation found, not garbage, but treat that case as a warning worth investigating rather than silently trusting the result. - Components are unitless combinations of the input columns' original scale. Indicators measured on very different scales (a price distance in points next to an oscillator bounded 0-100) should be standardised to comparable variance before this runs, or the component with the largest raw scale will dominate for reasons that have nothing to do with genuine shared information. - This library finds the decomposition; it does not decide how many components to keep. Use PCA_ExplainedVarianceRatio and a threshold that suits the model being built (a common rule of thumb is components that together explain 90-95% of total variance).

Script · MT5 · v1.0 · Free

About Principal Component Analysis

Principal Component Analysis is a script for MetaTrader 5. It has 1 setting, such as Rows. MQL source code included.

Files in the download: PrincipalComponentAnalysis.mq5.mqh, PrincipalComponentAnalysis.txt, PrincipalComponentAnalysisDemo.ex5, PrincipalComponentAnalysisDemo.mq5.

Settings

SettingDefaultWhat it does
Rows40Number of synthetic observations (rows)

How to install

  1. Download the ZIP from your PolyMaria library and unzip it.
  2. In MetaTrader 5 open File → Open Data Folder, then go to MQL5 → Scripts.
  3. Copy the .mq5 file(s) there. Put any .mqh files in MQL5 → Include.
  4. Open the .mq5 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
  5. Drag the script onto a chart to run it once.

Download the PDF guide

Tags: Moving Average · Momentum · Oscillator · Trend · MT5 Script · MQL5 Source Code

MQL4 & MQL5 scripts · PolyMaria