Matlab Optimize Portfolio
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Business and productivity
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to portfolio optimization using the MATLAB Financial Toolbox. It guides users to leverage the Portfolio object for tasks such as mean-variance analysis, efficient frontier computation, and maximizing the Sharpe ratio. By using built-in methods, users avoid the pitfalls of manual solver configuration and ensure robust, mathematically sound results for asset allocation problems.
What it does
- Formulates mean-variance portfolio optimization problems.
- Computes efficient frontiers and target-return portfolios.
- Calculates the maximum Sharpe ratio (tangency) portfolio.
- Manages complex constraints like cardinality and semicontinuous bounds.
- Provides built-in visualization for efficient frontiers and optimal portfolios.
- Calculates portfolio risk and return metrics automatically.
When to use it
- When you need to perform mean-variance or Markowitz portfolio optimization.
- When you want to find the tangency portfolio or maximize the Sharpe ratio.
- When you need to trace an efficient frontier for a set of assets.
- When you are struggling with manual solver implementations like fmincon or quadprog for asset allocation.
- When you need to apply specific constraints such as turnover, groups, or cardinality to a portfolio.
Advantages
- Reduces code complexity by using high-level object methods.
- Ensures global optima by using specialized internal solver configurations.
- Simplifies constraint management through dedicated API methods.
- Provides reliable, built-in functions for risk and return analysis.
- Prevents common errors associated with manual nonlinear objective function definitions.
Usage examples
- “How do I find the minimum variance portfolio in MATLAB?”
- The agent will show how to create a Portfolio object, set default constraints, and use estimateFrontierLimits(p, 'Min') to compute the minimum variance weights.
- “I want to maximize my Sharpe ratio, but my manual fmincon code is failing.”
- The agent will explain why the Portfolio object is preferred, show how to set the RiskFreeRate, and demonstrate the use of estimateMaxSharpeRatio(p).
- “How can I plot the efficient frontier for my asset returns?”
- The agent will provide a workflow to set asset moments, define constraints, compute the frontier using estimateFrontier(p, 20), and visualize it with plotFrontier(p, w).
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-optimize-portfolio/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-optimize-portfolio.zip -d .agents/skills
Documentation by MathWorks
Portfolio Optimization with Financial Toolbox
You are helping a user formulate and solve a portfolio optimization problem using MATLAB's Financial Toolbox Portfolio object.
When to Use
User wants to optimize a portfolio (minimize variance, maximize Sharpe ratio, trace efficient frontier)
User asks about Markowitz, mean-variance, minimum-variance, or tangency portfolios
User asks about the efficient frontier or target-return portfolios
User is trying to use fmincon, quadprog, ga, or problem-based optimize for portfolio optimization (redirect to Portfolio object)
User asks how to set up constraints for portfolio optimization (bounds, groups, turnover, one-way turnover, cardinality, semicontinuous)
User asks about mean-variance with cardinality or semi-continuous constraints
User gets errors from Portfolio, estimateMaxSharpeRatio, estimateFrontier, or related methods
When NOT to Use
User has a general optimization problem (QP, NLP, MILP) that is NOT financial asset allocation (e.g., filter design, resource allocation, mixture proportions) — use
matlab-solve-optimizationUser needs to retrieve market data from Bloomberg, FRED, or Haver Analytics — use
matlab-access-datafeedUser wants to predict returns or portfolio weights using neural networks or ML — use
matlab-train-networkUser only wants to clean, explore, or summarize a returns table without optimization — use
matlab-analyze-dataUser wants Experiment Manager parameter sweeps (not portfolio frontier) — use
matlab-use-experiment-managerUser wants CVaR, MAD, or other non-mean-variance risk measures — use
PortfolioCVaRorPortfolioMADclasses (not covered by this skill)
Key Principle
Always use the Portfolio class — never let users manually code the optimization with fmincon or quadprog. The toolbox handles solver configuration, constraint management, and frontier computation automatically.
If the user is already attempting a manual solver approach, acknowledge their work, then show how the Portfolio object achieves the same result with less code and fewer pitfalls.
Step 1: Identify the Formulation
Determine which problem the user is trying to solve:
| User wants to... | Formulation | Reference |
|---|---|---|
| Minimize portfolio risk (no return target) | Mean-variance (min-variance) | formulation-mean-variance.md |
| Minimize risk for a given target return | Mean-variance (target-return) | formulation-mean-variance.md |
| Trace the efficient frontier | Mean-variance (frontier) | formulation-mean-variance.md |
| Maximize risk-adjusted return (Sharpe ratio) | Max Sharpe / tangency | formulation-max-sharpe.md |
Consult the relevant formulation file for problem-specific guidance and methods.
Step 2: Determine What Data the User Has
Ask (if not clear) whether they have:
A matrix of historical asset returns (or prices that need converting)
Pre-computed mean returns (mu) and covariance matrix (Sigma)
A risk-free rate (relevant for Sharpe ratio; defaults to 0 if unspecified)
Step 3: Create the Portfolio Object
See reference-core.md for all creation patterns. The most common:
From return statistics:
p = Portfolio('AssetMean', mu, 'AssetCovar', Sigma);From historical returns:
p = Portfolio;
p = setAssetMoments(p, mean(returns)', cov(returns));Step 4: Set Constraints
Always set constraints. At minimum, use default constraints (fully invested, long-only):
p = setDefaultConstraints(p);For other constraint types (bounds, groups, turnover, one-way turnover, cardinality), see reference-core.md.
Step 5: Solve
Use the method appropriate to the formulation (see the formulation file). Common patterns:
wMinVar = estimateFrontierLimits(p, 'Min'); % minimum-variance
wTarget = estimateFrontierByReturn(p, targetRet); % target-return
wSharpe = estimateMaxSharpeRatio(p); % max Sharpe ratio
wFrontier = estimateFrontier(p, 20); % efficient frontierStep 6: Analyze and Visualize
Use built-in methods for portfolio statistics — never compute them manually:
portRisk = estimatePortRisk(p, w);
portRet = estimatePortReturn(p, w);
[risk, ret] = estimatePortMoments(p, w);Always use plotFrontier as the primary frontier visualization — add custom annotations (special portfolios, CAL line) with hold on/hold off afterward:
wFrontier = estimateFrontier(p, 20);
plotFrontier(p, wFrontier);
hold on
[risk, ret] = estimatePortMoments(p, wSpecial);
plot(risk, ret, 'r*', 'MarkerSize', 12);
hold offCommon Pitfalls
Manual solver usage — quadprog/fmincon for portfolio problems is error-prone; Portfolio handles it.
Missing constraints — A Portfolio without constraints is underdetermined.
Redundant solves — Pass weights to
plotFrontier, not a number of portfolios, if you already solved.Manual risk/return formulas — Use
estimatePortRisk,estimatePortReturn,estimatePortMoments.Cardinality/semicontinuous constraints — When calling
estimateMaxSharpeRatio, specify'Method','iterative'(MATLAB auto-selects with a warning if omitted, but explicit is cleaner). Frontier methods (estimateFrontier,estimateFrontierLimits,estimateFrontierByReturn) auto-detect these constraints and select the mixed-integer solver internally — do NOT pass'Method','iterative'to them.
Tone
Be direct and practical. Show working MATLAB code. If the user provides data, use their actual data. If not, use a small illustrative example so they can see the pattern and adapt.
Reference Materials
reference-core.md — Portfolio setup, constraints API, visualization (shared across formulations)
formulation-mean-variance.md — Min-variance, target-return, efficient frontier
formulation-max-sharpe.md — Max Sharpe ratio / tangency portfolio
examples.md — Complete runnable examples for all formulations
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md6.9 KiB
- manifest.yaml483 B
- references/examples.md8.7 KiB
- references/formulation-max-sharpe.md3.6 KiB
- references/formulation-mean-variance.md3.5 KiB
- references/reference-core.md6.8 KiB
references/reference-core.md
Portfolio Object — Core API Reference
Portfolio Object Creation
From pre-computed statistics
p = Portfolio('AssetMean', mu, 'AssetCovar', Sigma);
p = Portfolio('AssetMean', mu, 'AssetCovar', Sigma, 'RiskFreeRate', rf);From historical return data
p = Portfolio;
p = setAssetMoments(p, mean(returns)', cov(returns));
% or let the object estimate moments from a time series:
p = estimateAssetMoments(p, returns);From price data (convert to returns first)
returns = tick2ret(prices); % log returns from price series
p = Portfolio;
p = estimateAssetMoments(p, returns);Optional metadata
p = Portfolio('AssetList', ["AAPL","MSFT","GOOG"], ...
'AssetMean', mu, 'AssetCovar', Sigma);Note: p.AssetList is stored as a cell array of character vectors regardless of input type. Use curly-brace indexing (p.AssetList{i}) or convert with string(p.AssetList) before passing to fprintf or string operations.
Setting the risk-free rate
p = Portfolio('AssetMean', mu, 'AssetCovar', Sigma, 'RiskFreeRate', 0.02);
% or after construction:
p.RiskFreeRate = 0.02;Note: estimateMaxSharpeRatio does NOT accept a 'RiskFreeRate' argument — it reads from the Portfolio object. Only 'Method' and 'TolX' are valid name-value pairs for that function.
Periodicity and annualization
The Portfolio object is periodicity-agnostic — all outputs (estimatePortRisk, estimatePortReturn, plotFrontier, etc.) inherit the periodicity of the inputs. If the desired analysis periodicity differs from the data periodicity (e.g., user wants annualized results but has daily returns), convert the moments before creating the Portfolio. This way all downstream analysis produces results in the target periodicity directly, with no manual conversions in plotting or reporting code.
From pre-computed statistics (annualize before passing in):
muAnn = muDaily * 252;
SigmaAnn = SigmaDaily * 252;
rfAnn = rfDaily * 252;
p = Portfolio('AssetMean', muAnn, 'AssetCovar', SigmaAnn, 'RiskFreeRate', rfAnn);From historical data via estimateAssetMoments (rescale after estimation):
p = Portfolio;
p = estimateAssetMoments(p, dailyReturns);
p.AssetMean = p.AssetMean * 252;
p.AssetCovar = p.AssetCovar * 252;
p.RiskFreeRate = rfDaily * 252;All inputs must share the same periodicity — AssetMean, AssetCovar, and RiskFreeRate must all be expressed in the same units (daily, monthly, or annual).
Constraints
Default constraints (fully invested, long-only)
p = setDefaultConstraints(p);
% Equivalent to:
% p = setBudget(p, 1, 1); % weights sum to 1
% p = setBounds(p, 0, 1); % each weight in [0, 1]Bounds (upper/lower limits per asset)
p = setBounds(p, 0, 0.10); % all assets: 0% to 10%
p = setBounds(p, lbVector, ubVector); % per-asset vectorsBudget constraint (weights sum)
p = setBudget(p, 1, 1); % fully invested (sum = 1)
p = setBudget(p, 0.9, 1.1); % allow 90%-110% investedAllow short selling
p = setBudget(p, 1, 1);
p = setBounds(p, -0.3, 1); % short up to 30%, long up to 100%Group/sector constraints
GroupMatrix = [1 1 0 0 0; % assets 1-2 = sector A
0 0 1 1 1]; % assets 3-5 = sector B
p = setGroups(p, GroupMatrix, [0.2; 0.3], [0.6; 0.7]);
% sector A: 20%-60%, sector B: 30%-70%Cardinality constraints (min/max number of assets)
p = setMinMaxNumAssets(p, 3, 5); % hold between 3 and 5 assets
% NOTE: requires 'Method','iterative' when calling estimateMaxSharpeRatio.
% Frontier methods (estimateFrontier, estimateFrontierLimits) auto-detect.Important: Cardinality alone does not prevent near-zero allocations. Pair with conditional bounds to enforce a meaningful minimum position size:
p = setMinMaxNumAssets(p, 3, 5);
p = setBounds(p, 0.05, 0.5, 'BoundType', 'Conditional');
% Each asset is either 0% (not held) or between 5% and 50%Semicontinuous bounds (minimum position size if held)
p = setBounds(p, 0.02, 0.5, 'BoundType', 'Conditional');
% Each asset is either 0% or at least 2%
% NOTE: requires 'Method','iterative' when calling estimateMaxSharpeRatio.
% Frontier methods (estimateFrontier, estimateFrontierLimits) auto-detect.Turnover constraints
p = setTurnover(p, 0.15); % max 30% total turnover (constraint is 0.5*sum(|w-w0|) <= T)
p.InitPort = currentWeights; % current portfolio for turnover calcOne-way turnover constraints
p = setOneWayTurnover(p, 0.10, 0.15); % max 10% purchases, max 15% sales
p.InitPort = currentWeights;setOneWayTurnover(p, BuyTurnover, SellTurnover) constrains purchases and sales independently:
sum(max(w - w0, 0)) <= BuyTurnoversum(max(w0 - w, 0)) <= SellTurnover
Use instead of setTurnover when buy/sell costs are asymmetric or when rebalancing policy limits purchases differently from sales.
Tracking error constraint
benchmarkWgts = [0.2; 0.2; 0.2; 0.2; 0.2];
p = setTrackingError(p, 0.05, benchmarkWgts); % max 5% TE
% NOTE: requires fmincon solverLinear inequality constraints (custom)
% A*w <= b
A = [1 1 0 0 0]; % e.g., first two assets combined <= 40%
b = 0.4;
p = setInequality(p, A, b);Post-Solution Analysis
Always use built-in methods — never compute risk/return manually.
portRisk = estimatePortRisk(p, w); % standard deviation
portRet = estimatePortReturn(p, w); % expected return
[risk, ret] = estimatePortMoments(p, w); % both at once
sharpe = estimatePortSharpeRatio(p, w); % Sharpe ratioThese methods accept single portfolios (N-by-1) or multiple portfolios (N-by-K columns).
Visualization
Efficient frontier plot (from pre-computed weights)
wFrontier = estimateFrontier(p, 20);
plotFrontier(p, wFrontier);Annotating special portfolios on the frontier
wFrontier = estimateFrontier(p, 20);
plotFrontier(p, wFrontier);
hold on
[risk, ret] = estimatePortMoments(p, wSpecial);
plot(risk, ret, 'r*', 'MarkerSize', 12);
legend('Efficient Frontier', 'Special Portfolio');
hold offSolver Configuration
Default solver (quadprog — works for most problems)
No configuration needed; Portfolio uses quadprog by default.
Custom solver settings
p = setSolver(p, 'quadprog', 'Display', 'off', ...
'ConstraintTolerance', 1e-8, 'OptimalityTolerance', 1e-8);fmincon solver (required for nonlinear constraints like tracking error)
p = setSolver(p, 'fmincon', 'Display', 'off', 'Algorithm', 'sqp', ...
'SpecifyObjectiveGradient', true, 'SpecifyConstraintGradient', true, ...
'ConstraintTolerance', 1e-8, 'OptimalityTolerance', 1e-8);Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/computational-finance/matlab-optimize-portfolio · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-optimize-portfolio.zip