Skip to content
cccskills
FreePublished on GitHub

matlab-optimize-portfolio

Help users formulate and solve portfolio optimization problems using Financial Toolbox's Portfolio object. Covers mean-variance (Markowitz), maximum Sharpe ratio (tangency), and efficient frontier workflows. Use when users ask about portfolio optimization, Markowitz, efficient frontier, Sharpe ratio, or attempt to use generic solvers (quadprog, fmincon, ga, problem-based optimize) for portfolio problems.

The English summary is being prepared. Showing the original description.

See how to install

Files included (6)

  • SKILL.md6.9 KB
  • manifest.yaml483 B
  • references/examples.md8.7 KB
  • references/formulation-max-sharpe.md3.6 KB
  • references/formulation-mean-variance.md3.5 KB
  • references/reference-core.md6.8 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

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-optimization
  • User needs to retrieve market data from Bloomberg, FRED, or Haver Analytics — use matlab-access-datafeed
  • User wants to predict returns or portfolio weights using neural networks or ML — use matlab-train-network
  • User only wants to clean, explore, or summarize a returns table without optimization — use matlab-analyze-data
  • User wants Experiment Manager parameter sweeps (not portfolio frontier) — use matlab-use-experiment-manager
  • User wants CVaR, MAD, or other non-mean-variance risk measures — use PortfolioCVaR or PortfolioMAD classes (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...FormulationReference
Minimize portfolio risk (no return target)Mean-variance (min-variance)formulation-mean-variance.md
Minimize risk for a given target returnMean-variance (target-return)formulation-mean-variance.md
Trace the efficient frontierMean-variance (frontier)formulation-mean-variance.md
Maximize risk-adjusted return (Sharpe ratio)Max Sharpe / tangencyformulation-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 frontier

Step 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 off

Common Pitfalls

  1. Manual solver usage — quadprog/fmincon for portfolio problems is error-prone; Portfolio handles it.
  2. Missing constraints — A Portfolio without constraints is underdetermined.
  3. Redundant solves — Pass weights to plotFrontier, not a number of portfolios, if you already solved.
  4. Manual risk/return formulas — Use estimatePortRisk, estimatePortReturn, estimatePortMoments.
  5. 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


Copyright 2026 The MathWorks, Inc.


Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Guide for accessing financial and economic data in MATLAB using the Datafeed Toolbox. Covers Bloomberg (market data via bloomberg/blp/bloombergHypermedia), FRED (Federal Reserve economic data via fredrs), Haver Analytics (economic data via haver/haverdirect/haverview), and LSEG Datastream (historical data via datastreamws). Use when connecting to any of these data providers from MATLAB.

The English summary is being prepared. Showing the original description.

matlab/matlab-agentic-toolkit1.2KUpdated Oct 14, 2026

Read BEFORE writing any code that adds Additive White Gaussian Noise (AWGN) to signals and converts between SNR, Eb/No, Es/No, and per-subcarrier SNR for communications simulations, using awgn(), convertSNR(), berawgn(). The default MATLAB patterns for AWGN (e.g., 'measured' option, manual SNR formulas) produce subtly incorrect results. This skill specifies the correct calling conventions, required function usage, and critical anti-patterns that must be avoided.

The English summary is being prepared. Showing the original description.

matlab/matlab-agentic-toolkit1.2KUpdated Oct 14, 2026

Analyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.

The English summary is being prepared. Showing the original description.

matlab/matlab-agentic-toolkit1.2KUpdated Oct 14, 2026

Design and analyze electrically large antenna structures using MATLAB Antenna Toolbox. Covers reflector antennas (parabolic, Cassegrain, Gregorian, offset, corner, cylindrical, spherical, custom STL), reflectarrays and reconfigurable intelligent surfaces (RIS), antennas installed on platforms (vehicles, aircraft, ships, satellites), and radar cross section (RCS) analysis. Includes solver selection (MoM-PO, PO, MoM, FMM), mesh control, and GPU acceleration. Use when the user wants to design a dish/reflector antenna, reflectarray, analyze an antenna on a platform, or compute RCS.

The English summary is being prepared. Showing the original description.

matlab/matlab-agentic-toolkit1.2KUpdated Oct 14, 2026

Analyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, row filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.

The English summary is being prepared. Showing the original description.

matlab/matlab-agentic-toolkit1.2KUpdated Oct 14, 2026

S-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).

The English summary is being prepared. Showing the original description.

matlab/matlab-agentic-toolkit1.2KUpdated Oct 14, 2026

See all skills by matlab

Report a problem with this skill