Portfolio Weight Calculation: Risk Parity, HRP, Minimum Variance, and Maximum Diversification

Portfolio Weight Calculation: Risk Parity, HRP, Minimum Variance, and Maximum Diversification
Download ALL MT5 experts (1732)
YouTube Video Thumbnail



Similar MetaTrader Tools

Portfolio Weight Calculation: Risk Parity, HRP, Minimum Variance, and Maximum Diversification

Info

The Portfolio Weight Calculation: Risk Parity, HRP, Minimum Variance, and Maximum Diversification is a Expert Advisor for MetaTrader 5 that portfolioweights. mqh computes portfolio weights from the returns of its components, which can be symbols or the daily results of multiple Expert Advisors.

Usage

This tool is typically used for automated trading on major forex pairs and gold.

Platform

This Expert Advisor works exclusively on MetaTrader 5 (both build 600+ and newer versions).

Setup

Place the downloaded file in MQL5/Experts folder via File ? Open Data Folder in MetaTrader 5.


How to Install and Use Portfolio Weight Calculation: Risk Parity, HRP, Minimum Variance, and Maximum Diversification

1. Installation: Open the "File" menu, select "Open Data Folder," navigate to MQL/Experts, paste your file, and restart the terminal.

2. Activation: Drag the EA from the Navigator onto a chart, ensure "Allow live trading" is checked in the Common tab, and verify the AutoTrading button is green.

3. Optimization: Right-click your chart, choose "Expert List," click "Properties" to adjust inputs, and save your preferred setup as a set file for future use.

4. Maintenance: Regularly check the "Experts" tab in the terminal window to monitor trade logs and potential execution errors.

Frequently Asked Questions

Q: Why is my EA not opening trades? A: Check the "AutoTrading" button, ensure "Allow live trading" is enabled, and verify your broker allows automated trading on your account type.

Q: Can I run multiple EAs on one chart? A: No, each chart can only host one active EA; however, you can open multiple charts for different currency pairs to run several EAs.

Q: What does the "smiley face" icon mean? A: A smiley face in the top-right corner of the chart indicates the EA is successfully running; a frowny face means it is disabled.

What this tool does

PortfolioWeights.

Typical Use Case

This Expert Advisor excels in automated trading and technical analysis on MetaTrader 5.

Compatible Platform & Setup

This Expert Advisor works on MetaTrader 5. Place the file in the MQL5/Experts folder and restart the terminal.

Description & Settings

Related: Canvas Tabs: a lightweight tab bar for MQL5 based on C Canvas - another powerful expert for MetaTrader 5 traders.

PortfolioWeights.mqh computes portfolio weights from the returns of its components, which can be symbols or the daily results of multiple Expert Advisors. It offers five classic long-only methods, a covariance calculation with Ledoit-Wolf shrinkage, and details the risk contribution of each component. This tool utilizes MQL5's matrix and vector types and requires no external DLLs.

Also recommended: Portfolio Allocation Planner: Budget to Lots Dashboard and CSV Export - similar expert with strong performance on MetaTrader 5.


Usage

matrix returns(days, assets); // Period data in rows, asset data in columns // ... populate returns matrix ... matrix cov; double shrink = CPortfolioWeights::LedoitWolf(returns, cov); // or CPortfolioWeights::Covariance(returns, cov) int order[]; vector w = CPortfolioWeights::RiskParity(cov); // Weights sum to 1 vector h = CPortfolioWeights::HierarchicalRiskParity(cov, order); vector rc = CPortfolioWeights::RiskContributions(cov, w);

Methods

InverseVolatility
: Assigns weights inversely proportional to each component's volatility. RiskParity
: Achieves equal risk contribution, meaning each component contributes equally to the portfolio's variance. This method uses cyclical coordinate descent (Griveau-Billion, Richard, and Roncalli, 2013). HierarchicalRiskParity
: Components are ordered using a single-linkage tree based on the distance metric sqrt((1 - correlation) / 2). Weights are then allocated down this ordered list, inversely proportional to the variance of each sub-group. The 'order[]' array returns the tree's ordering (Lopez de Prado, 2016). MinimumVariance
: Aims to minimize the portfolio's overall variance, with an option to set a cap on individual component weights. MaximumDiversification
: Maximizes the ratio of weighted component volatilities to the overall portfolio volatility (Choueifaty and Coignard, 2008). LedoitWolf
: Calculates the sample covariance matrix, shrinking its correlations towards zero using the optimal intensity determined by Ledoit and Wolf (2004). This calculation is performed on returns scaled to unit variance. For datasets with few periods and many components, where sample correlations can be noisy, the shrunk covariance provides more stable weights. Both optimization methods are solved precisely using an active-set quadratic programming approach (handling bounds and a single equality constraint), rather than iterative search.

Example

The script PortfolioWeightsExample.mq5 demonstrates the functionality. It takes a list of symbols (or the first 8 from Market Watch), calculates their daily log returns over a specified number of days, and outputs the weights for each method along with its diversification ratio and the risk contributions for the risk parity mix (refer to picture 1).

Validation

On a dataset of 750 periods from 8 correlated series, the shrinkage intensity matched scikit-learn's LedoitWolf implementation. The hierarchical method's tree order aligned with scipy's single linkage, and its weights corresponded to a Python version using bisection within 1e-15 precision for risk parity contributions. The minimum variance (with and without caps) and maximum diversification weights were found to be within 2e-8 of scipy's SLSQP optimizer results.

Files

Place PortfolioWeights.mqh in the MQL5\Include\PortfolioWeights directory. Place PortfolioWeightsExample.mq5 in the MQL5\Scripts\PortfolioWeights directory.

You may also like: Prop Spread: Time-Weighted Spread Monitor with ATR Context, Alerts, and CSV Logging - excellent alternative for expert users on MetaTrader 5.

Source Code

#property copyright "RobotFX"
#property version     "1.00"
#property script_show_inputs
#include <PortfolioWeights\PortfolioWeights.mqh>
input string InpSymbols = "";
input int    InpDays    = 500;
input bool   InpShrink  = true;
void OnStart()
  {
   string symbols[];

.......

Leave your opinion, ask a question, share some knowledge

⚠ Limitations & Risk Warning

  • This tool is provided for educational and testing purposes only.
  • Past performance does not guarantee future results.
  • Trading involves substantial risk of loss. Use on a demo account first.
  • Results may vary depending on market conditions, broker, and settings.
  • We recommend thorough backtesting and forward testing before using with real funds.
© ROBOTFX Free educational tools by RobotFX. Use entirely at your own risk; we are not liable for any financial losses incurred.