Calculator in Markets and quant
Efficient frontier
Finds the minimum-variance and maximum-Sharpe portfolios of 2 to 20 assets from their return series.
- Changed 4 Dec 2026
- 9 test cases pass
- Version 1
- About 8,300 tokens
- Needed by both models tested, 4 Dec 2026
In short
| Formula | Per asset: mean r̄ of its periodic returns; muAnn = (1 + r̄)^periods_per_year − 1Σ = sample covariance of the returns (divide by n − 1) × periods_per_yearminVarWeights = Σ^−1×1 ÷ (sum of Σ^−1×1)tangencyWeights = Σ^−1×(muAnn − risk_free_annual) ÷ (sum of that vector); if the sum is 0, the minimum-variance weightseach portfolio w: RetAnn = w·muAnn; VolAnn = √(w'Σw); SharpeAnn = (RetAnn − risk_free_annual) ÷ VolAnntangencyIsMaxSharpe = the tangency sum > 0 and risk_free_annual < minVarRetAnn |
| Units | Periodic decimal returns in; annual decimals out. Weights sum to 1; negative means short. |
| Defaults | risk_free_annual has no default (−1–1; current annual rate, decimal); periods_per_year 252 (1–366), the trading-day convention for daily returns. 2 to 20 assets, more rows than assets. |
| Worked example | monthly returns A = 0.02, −0.01, 0.03, 0.01, −0.02, 0.03; B = 0.01, 0, 0.01, 0.01, −0.01, 0.01; C = 0.01, 0.02, −0.01, 0, 0.02, 0.01; rate 0.02; periods 12. Monthly covariances: AA 0.00044, AB 0.00016, AC −0.00018, BB 0.00007, BC −0.00007, CC 0.0001367. muAnn = 1.01^12 − 1, … = 0.127, 0.062, 0.105minVarWeights = −12/97, 307/388, 129/388 = -0.124, 0.791, 0.332minVarRetAnn = w·muAnn = 0.068minVarVolAnn = √(0.0000123196×12) = 0.012tangencyWeights = 0.186, 0.271, 0.543 |
By hand: yes. A small model got these answers from the formulas above, without running code.
Say this to your agent
Use https://mysi.dev/efficient-frontier-builder/ to find the min-variance and max-Sharpe mix of these three monthly return series, rate 2%. Nothing to install, no key, no settings. An agent that can open web pages and run Python opens the page, runs the tested code in its own sandbox and gives you the answer.
The code
Copy this into your Python tool. Run efficient_frontier_builder_check() first, then call efficient_frontier_builder() with your numbers. Give the answer with the cite line.
"""Efficient frontier: Markowitz minimum-variance and tangency (maximum-Sharpe) portfolios of
2 to 20 assets from their return series, in closed form with short sales allowed (Merton 1972).
Inputs: assets (2 to 20 return series of equal length, more rows than assets, each a list of
simple periodic returns as decimals or {"name": ..., "returns": [...]}), risk_free_annual
(decimal, -1 to 1, no default), periods_per_year (1 to 366, default 252).
Returns: n, m, muAnn, minVarWeights, minVarRetAnn, minVarVolAnn, minVarSharpeAnn,
tangencyWeights, tangencyRetAnn, tangencyVolAnn, tangencySharpeAnn, tangencyIsMaxSharpe.
mysi, Efficient frontier, mysi.dev/efficient-frontier-builder, version 1, changed 2026-12-04. MIT.
"""
import math
def _efficient_frontier_builder_inverse(m):
k, g = len(m), [r[:] + [float(i == j) for j in range(len(m))] for i, r in enumerate(m)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(g[r][c]))
if abs(g[p][c]) < 1e-12:
raise ValueError("assets: the covariance matrix is singular (perfectly correlated)")
g[c], g[p] = g[p], g[c]
g[c] = [v / g[c][c] for v in g[c]]
for r in range(k):
if r != c:
g[r] = [v - g[r][c] * w for v, w in zip(g[r], g[c])]
return [row[k:] for row in g]
def efficient_frontier_builder(assets, risk_free_annual, periods_per_year=252):
msg = "assets must be a list of 2 to 20 equal-length return series, more rows than assets"
if not isinstance(assets, list) or not 2 <= len(assets) <= 20:
raise ValueError(msg)
data = [a.get("returns") if isinstance(a, dict) else a for a in assets]
if not all(isinstance(s, list) and all(isinstance(x, (int, float)) and not
isinstance(x, bool) and math.isfinite(x) for x in s) for s in data):
raise ValueError(msg)
m, n = len(data), len(data[0])
if any(len(s) != n for s in data) or n <= m or n < 3:
raise ValueError(msg)
for name, v, lo, hi in (("risk_free_annual", risk_free_annual, -1, 1),
("periods_per_year", periods_per_year, 1, 366)):
if isinstance(v, bool) or not isinstance(v, (int, float)) or not lo <= v <= hi:
raise ValueError(f"{name} must be a number from {lo} to {hi}")
rf, ppy = float(risk_free_annual), float(periods_per_year) # 252 trading days/yr: Hull
means = [sum(s) / n for s in data]
mu = [(1 + x) ** ppy - 1 for x in means] # compounded annual mean
cov = [[sum((x - means[i]) * (y - means[j]) for x, y in zip(data[i], data[j]))
/ (n - 1) * ppy for j in range(m)] for i in range(m)]
inv = _efficient_frontier_builder_inverse(cov)
mul = lambda v: [sum(a * b for a, b in zip(row, v)) for row in inv]
def point(w):
ret = sum(a * b for a, b in zip(w, mu))
vol = math.sqrt(max(0.0, sum(w[i] * cov[i][j] * w[j] for i in range(m) for j in range(m))))
return w, ret, vol, (ret - rf) / vol if vol > 0 else 0.0
s1 = mul([1.0] * m)
w_min = point([x / sum(s1) for x in s1]) # Sigma^-1 1 / (1' Sigma^-1 1)
se = mul([x - rf for x in mu]) # Sigma^-1 (mu - rf)
b = sum(se)
w_tan = point([x / b for x in se]) if abs(b) >= 1e-12 else w_min
out = {"n": n, "m": m, "muAnn": mu}
for tag, (w, ret, vol, sharpe) in (("minVar", w_min), ("tangency", w_tan)):
out.update({tag + "Weights": w, tag + "RetAnn": ret, tag + "VolAnn": vol,
tag + "SharpeAnn": sharpe})
out["tangencyIsMaxSharpe"] = b > 0 and rf < w_min[1]
return out
_EFFICIENT_FRONTIER_BUILDER_A = [0.02, -0.01, 0.03, 0.01, -0.02, 0.03]
_EFFICIENT_FRONTIER_BUILDER_B = [0.01, 0.0, 0.01, 0.01, -0.01, 0.01]
EFFICIENT_FRONTIER_BUILDER_CASES = [
({"assets": [_EFFICIENT_FRONTIER_BUILDER_A, _EFFICIENT_FRONTIER_BUILDER_B],
"risk_free_annual": 0.02, "periods_per_year": 12},
{"minVarRetAnn": 0.0308186, "minVarVolAnn": 0.0181224, "tangencySharpeAnn": 1.48925}),
({"assets": [[0.01, -0.01, 0.01, -0.01], [0.01, 0.01, -0.01, -0.01]],
"risk_free_annual": 0.04, "periods_per_year": 12},
{"minVarRetAnn": 0.0, "minVarVolAnn": 0.0282843}),
({"assets": [_EFFICIENT_FRONTIER_BUILDER_A, _EFFICIENT_FRONTIER_BUILDER_B,
[0.01, 0.02, -0.01, 0.0, 0.02, 0.01]],
"risk_free_annual": 0.02, "periods_per_year": 12},
{"minVarRetAnn": 0.0679265, "tangencyRetAnn": 0.0971891, "tangencySharpeAnn": 5.00238}),
]
def efficient_frontier_builder_check(tolerance=1e-3):
for given, want in EFFICIENT_FRONTIER_BUILDER_CASES:
got = efficient_frontier_builder(**given)
for name, value in want.items():
close = abs(got[name] - value) <= tolerance * max(1, abs(value))
assert close, (name, got[name], value)
return "ok"
if __name__ == "__main__":
import json, sys
efficient_frontier_builder_check()
given = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
js = lambda v: v.lstrip("-")[:1].isdigit() or v[:1] in '[{".' or v in ("true", "false", "null")
given = {k: json.loads(v) if js(v) else v for k, v in given.items()}
if given:
print(json.dumps(efficient_frontier_builder(**given))) Weights from past returns, for analysis only, not investment advice.
What it takes
| Input | Meaning | Default | Allowed |
|---|---|---|---|
| assets | 2 to 20 return series of equal length (more rows than assets), each a list of simple periodic returns as decimals or {name, returns} | required | a list |
| risk_free_annual | The current annual risk-free rate as a decimal (0.04 = 4%). No default: it is a dated figure | required | -1 to 1 |
| periods_per_year | Return periods per year: 252 daily, 52 weekly, 12 monthly | 252 | 1 to 366 |
What it returns
| Output | Meaning |
|---|---|
| n, m | Rows per series and number of assets |
| muAnn | Annual expected return of each asset, (1 + mean)^periods − 1 |
| minVarWeights, minVarRetAnn, minVarVolAnn, minVarSharpeAnn | The minimum-variance portfolio: weights in input order, annual return, volatility and Sharpe ratio |
| tangencyWeights, tangencyRetAnn, tangencyVolAnn, tangencySharpeAnn | The tangency portfolio, the same four |
| tangencyIsMaxSharpe | False when the rate is at or above the minimum-variance return, so the tangency formula gives the lowest Sharpe ratio instead |
Where the method comes from
Markowitz (1952) mean-variance analysis chooses portfolio weights by expected return and variance. With short sales allowed and weights summing to one, the frontier has a closed form (Merton 1972): the minimum-variance portfolio is Σ^−1·1 scaled to sum to one, and the tangency portfolio, the one with the highest Sharpe ratio against a risk-free rate, is Σ^−1(μ − r_f) scaled the same way. Here μ annualizes each asset's mean periodic return by compounding, and Σ scales the sample covariance by the periods per year; the default of 252 periods is the trading-day count per year conventional for daily returns (Hull, Options, Futures, and Other Derivatives).
When the risk-free rate is at or above the minimum-variance return, the same formula lands on the inefficient branch and gives the lowest Sharpe ratio, so tangencyIsMaxSharpe is false. Sample means are very noisy, so the tangency weights swing widely with small changes in the data; there is no long-only or leverage limit.
Sources
- Markowitz, Portfolio selection, Journal of Finance 7(1)published 1952
- Merton, An analytic derivation of the efficient portfolio frontier, Journal of Financial and Quantitative Analysis 7(4)published 1972
Tested
Tested 4 Dec 2026: claude-haiku-5-5 was right on 1 of 3 questions without this page and 3 of 3 with it; claude-fable-5-2 was right on 1 of 3 questions without this page and 3 of 3 with it.
Changes
- The risk-free rate has no default any more (the old 4% was undated). Moved from aifinhub.io as Python. Answers unchanged, returned flat (minVarVolAnn instead of minVar.volAnn, tangencyWeights instead of tangency.weights). The swept frontier curve and its steps input, the covariance matrix, the asset names and the echoed rate are no longer returned. The minimum is more rows than assets instead of 60.4 Dec 2026
Cite as: mysi, Efficient frontier, mysi.dev/efficient-frontier-builder, version 1, changed 2026-12-04. Code MIT.