How to Calculate Minimum Variance Portfolio Weights
Give me a candidate list of stocks and a few years of end-of-day prices, and the minimum variance problem has exactly one answer: the weight vector that produces the lowest possible portfolio variance for that data. No return forecast, no view on the market — just the covariance structure of the assets you picked.
The catch is that “exactly one answer” only holds for a fixed universe, a fixed covariance estimate and a fixed set of constraints. Change any of the three and the weights move. So the useful skill isn’t punching numbers into a solver once; it’s running the calculation in a way that is reproducible and that you can re-run when the inputs change.
This walkthrough does both. You’ll go from raw prices to a checked weight vector in six steps, with a Python reference implementation you can use to verify any result, and then see how RSJ Portfolio runs the same steps as a managed desktop workflow — no code, no hand-rolled data pipeline.
It’s written for investors and quants who want a rigorous, repeatable method. If you want the underlying theory of why weak correlation lowers volatility, that’s covered separately in Why Low Correlation Stocks Reduce Portfolio Volatility; here we stay on the mechanics.
Prerequisites: Prices, Math, and a Place to Run It
Before the first line of code or the first click, get these in order:
- Historic end-of-day prices for every candidate, adjusted for splits and dividends. Unadjusted prices inject fake jumps into returns, and the covariance matrix faithfully amplifies them.
- More observations than assets. A covariance matrix over N assets needs more than N return observations to be well behaved. Practically, use several years of daily data for a dozen or so names.
- Working knowledge of returns and covariance — or a tool that owns that layer for you. The algebra is not deep, but the data handling around it is where most mistakes happen.
- An environment. Python or R if you want to compute and inspect every intermediate step. A dedicated application if you want the pipeline managed end to end.
RSJ Portfolio is a Windows desktop application that falls in the second category. It pulls prices from supported data providers, runs them through a price cleaning pipeline, keeps a local cache, and handles portfolios quoted in several currencies through a conversion path driven by a local currency setting. The details are on the Data and currencies page.
With that, here’s the calculation.
Step-by-Step: Calculating Minimum Variance Weights
Step 1 — Collect and clean the price history
For the manual route, export adjusted close prices into a single table: one row per date, one column per ticker, aligned on a common trading calendar. Drop any column that doesn’t have a full history over your window; partial series are worse than absent ones.
With RSJ Portfolio, this is configuration rather than code. You choose the data provider, set the date range, and set the cleaning options before the first run. The Configuration chapter of the user guide lists every setting.
One check worth doing either way: look at the largest single-day moves per ticker. A 40% one-day drop in a large-cap that didn’t actually happen is almost always an unadjusted split.
Step 2 — Compute returns and the covariance matrix
Convert prices to simple or log returns, then estimate the covariance matrix Σ. If you want to reproduce the numbers yourself, this is the whole core of it:
import numpy as np
import pandas as pd
# rows: dates, columns: tickers, values: adjusted close
prices = pd.read_csv("prices.csv", index_col="date", parse_dates=True).dropna(how="any")
returns = prices.pct_change().dropna()
sigma = returns.cov().values * 252 # annualised sample covariance
mu = returns.mean().values * 252 # not needed for min-variance, but useful later
n = sigma.shape[0]
print(f"{n} assets, {len(returns)} return observations")
Two things matter here. First, the scaling factor (252) is a convention, not a law — it changes the magnitude of the variance, not the argmin. Second, the estimator you choose does change the weights. Sample covariance is the default; RSJ Portfolio exposes a set of selectable risk models, and the methods page describes each one. For a comparison of how the choice affects allocations, see Portfolio Optimizer with Selectable Risk Models: A Comparison.
Step 3 — Write down the optimization problem
Minimum variance is a quadratic program:
minimise wᵀ Σ w
subject to Σᵢ wᵢ = 1 (fully invested)
0 ≤ wᵢ ≤ cap (no shorting, per-stock cap)
The objective is the portfolio variance. The first constraint makes the weights a portfolio rather than an arbitrary vector. The second is where judgement enters: without a cap, the optimizer will happily put 60% in whichever stock has the lowest variance and the weakest co-movement with everything else.
Step 4 — Solve for the weights
Any quadratic programming solver will do. Sequential least squares is enough for a few dozen assets:
from scipy.optimize import minimize
def variance(w, sigma):
return w @ sigma @ w
constraints = [{"type": "eq", "fun": lambda w: w.sum() - 1.0}]
bounds = [(0.0, 0.20)] * n
w0 = np.repeat(1.0 / n, n)
res = minimize(
variance, w0, args=(sigma,), method="SLSQP",
bounds=bounds, constraints=constraints,
options={"ftol": 1e-12, "maxiter": 1000},
)
weights = pd.Series(res.x, index=prices.columns).round(4).sort_values(ascending=False)
print(weights)
print("status:", res.success, "| variance:", round(res.fun, 6))
In RSJ Portfolio, this step is a selection, not a script: choose Minimum Volatility as the objective, pick the risk model, and run the optimizer. The Recommendation chapter documents the parameters and the resulting allocation view.
Step 5 — Tighten the constraints and re-solve
Run it once with a loose cap, look at the concentration, then tighten. A 20% cap and a 10% cap give you two different portfolios and two different variance estimates; the gap between them tells you how much of the “optimum” was really a bet on one or two names.
In the app, weight constraints are set as optimizer inputs, so this is a re-run rather than a rewrite.
Step 6 — Record or export the allocation
Save the weight vector next to the inputs that produced it: date range, universe, risk model, constraints. A weight vector without its parameters is not reproducible. RSJ Portfolio provides export options for the resulting allocation.
How to Confirm It Worked
Four checks, in increasing order of strictness:
- Feasibility. Weights sum to 1 within tolerance, none are negative (if you banned shorting), none exceed the cap.
- Objective value. Compare the optimized variance against an equal-weight portfolio and against random feasible weight vectors. The optimum must beat all of them.
- Out-of-sample stability. Split the history: estimate on the first part, evaluate the variance of those weights on the second. RSJ Portfolio’s date range selection lets you set in-sample and out-of-sample windows directly.
- Model robustness. Re-run with a different risk estimator — for example minimum semi-variance instead of minimum volatility. If the top holdings barely change, the allocation reflects the data; if they reshuffle completely, it reflects the estimator.
w_eq = np.repeat(1.0 / n, n)
print("optimised :", round(variance(res.x, sigma), 6))
print("equal wt :", round(variance(w_eq, sigma), 6))
print("max weight:", round(res.x.max(), 4), "| sum:", round(res.x.sum(), 10))
A broader checklist for stress-testing output before you act on it is in How to Validate Portfolio Optimizer Output Before You Trade.
Troubleshooting Common Issues
-
Singular or near-singular covariance matrix. Happens when assets are near-duplicates or when observations barely exceed assets. Fix: extend the history, drop redundant tickers, or shrink the estimate:
sigma_shrunk = 0.9 * sigma + 0.1 * np.diag(np.diag(sigma)) -
Unstable weights. Small input changes produce large allocation shifts — the classic symptom of an unconstrained minimum variance solve. Fix: per-stock caps, a longer window, or a shrinkage estimator.
-
Currency effects. For a portfolio quoted in several currencies, the covariance must be computed on returns expressed in one common currency. RSJ Portfolio handles this through its local currency setting and conversion path; the multi-currency specifics are covered in Portfolio Optimization for Multi-Currency Portfolios: A Guide.
-
Data errors. A single bad print can dominate a covariance estimate. Either run your own outlier screen or use the cleaning pipeline in RSJ Portfolio before the optimizer sees the data.
Automating with RSJ Portfolio: A Managed Workflow
Everything above collapses into one desktop workflow: search and select candidates, pick the Minimum Volatility objective, choose a risk estimator, set weight constraints, run. The math is modern portfolio theory, applied consistently, with the data acquisition and cleaning already handled.
The point of the tool is the part that’s hard to do by hand at scale: it analyses the return correlation between candidates and allocates capital toward stocks that correlate weakly — or whose downside correlates weakly — which is what actually reduces the volatility of the resulting portfolio. You can read more about the product on the overview page, and the Getting Started guide covers the configuration worth setting before your first run.
The Windows installer is on the downloads page with a published SHA-512 in a versioned filename, alongside the full user guide. If you want to verify the download before running it:
certutil -hashfile <installer>.exe SHA512
Compare the output against the hash on the downloads page.
FAQ
What is the difference between minimum variance and minimum volatility portfolios? They refer to the same objective: minimizing the portfolio’s variance (or equivalently, its volatility). The term “minimum variance” is more common in academic literature, while “minimum volatility” is often used in practice.
Can I calculate minimum variance weights in Excel? Yes — Excel’s Solver add-in can minimize portfolio variance by changing weights, subject to constraints. For larger universes or advanced risk models, a dedicated tool like RSJ Portfolio is more efficient and less error-prone.
How many stocks do I need for a reliable minimum variance portfolio? There is no fixed number, but typically 10–20 stocks with low correlation can achieve diversification benefits. Beyond that, the marginal reduction in variance diminishes. The key is the correlation structure, not just the count.
Does RSJ Portfolio require programming skills? No. RSJ Portfolio is a Windows desktop application with a graphical interface. You can select stocks, configure parameters, and run the optimizer without writing code.
Conclusion
The calculation itself is short: prices → returns → covariance → constrained quadratic program → weights. What makes it useful is doing it reproducibly, with the covariance estimator and the constraints written down next to the result, and then checking that the answer survives a different window and a different risk model.
Run it once in Python to see the machinery. Then run it in RSJ Portfolio, where the data, cleaning and currency conversion are handled for you and the constraint set is a form field rather than a line of code.
RSJ Portfolio is licensed per single user; the pricing page lists what the license includes and takes you to checkout.
Related posts
- Modern Portfolio Theory vs Hierarchical Risk Parity
- Portfolio Optimization for Multi-Currency Portfolios: A Guide
- Why Low Correlation Stocks Reduce Portfolio Volatility