Efficient Frontier in Python: Plot Optimal Portfolios with scipy

Plot the efficient frontier in Python by simulating random portfolios, solving for minimum-variance portfolios with scipy.optimize.minimize, and marking the max-Sharpe and minimum-volatility portfolios.

To plot an efficient frontier in Python, take the expected returns and covariance matrix of your assets, find for each target return the long-only weights with the lowest volatility using scipy.optimize.minimize(method="SLSQP"), and plot volatility against return. A cloud of random portfolios behind the line shows what is achievable, and the frontier is its upper-left edge: the most return for each level of risk.

Quick Example

To keep the post reproducible the inputs are stated directly: annual expected returns, volatilities and correlations for six asset classes, which are turned into a covariance matrix. These are illustrative numbers, not forecasts. With real data, replace mu and cov with returns.mean() * 252 and returns.cov() * 252.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize

assets = ["US Stocks", "Intl Stocks", "Emerging", "Bonds", "Real Estate", "Gold"]
mu = pd.Series([0.085, 0.075, 0.090, 0.035, 0.070, 0.050], index=assets)      # annual expected return
vol = pd.Series([0.16, 0.17, 0.23, 0.06, 0.19, 0.15], index=assets)          # annual volatility
corr = pd.DataFrame(np.eye(6), index=assets, columns=assets)
for (a, b), c in {("US Stocks", "Intl Stocks"): 0.80, ("US Stocks", "Emerging"): 0.70, ("US Stocks", "Bonds"): 0.05,
                  ("US Stocks", "Real Estate"): 0.70, ("US Stocks", "Gold"): 0.05, ("Intl Stocks", "Emerging"): 0.80,
                  ("Intl Stocks", "Bonds"): 0.10, ("Intl Stocks", "Real Estate"): 0.65, ("Intl Stocks", "Gold"): 0.10,
                  ("Emerging", "Bonds"): 0.05, ("Emerging", "Real Estate"): 0.60, ("Emerging", "Gold"): 0.15,
                  ("Bonds", "Real Estate"): 0.25, ("Bonds", "Gold"): 0.20, ("Real Estate", "Gold"): 0.10}.items():
    corr.loc[a, b] = corr.loc[b, a] = c
cov = corr.values * np.outer(vol, vol)
rf = 0.02
n = len(assets)

def stats(w):
    return w @ mu.values, np.sqrt(w @ cov @ w)            # return, volatility

# 1. Random long-only portfolios
rng = np.random.default_rng(7)
W = rng.dirichlet(np.ones(n), 6000)
rand_ret = W @ mu.values
rand_vol = np.sqrt(np.einsum("ij,jk,ik->i", W, cov, W))
rand_sharpe = (rand_ret - rf) / rand_vol

# 2. Minimum-volatility weights for a target return (long only, fully invested)
def min_vol(target=None):
    cons = [{"type": "eq", "fun": lambda w: w.sum() - 1}]
    if target is not None:
        cons.append({"type": "eq", "fun": lambda w: w @ mu.values - target})
    res = minimize(lambda w: w @ cov @ w, np.ones(n) / n, bounds=[(0, 1)] * n, constraints=cons, method="SLSQP")
    return res.x

w_minvol = min_vol()
targets = np.linspace(stats(w_minvol)[0], mu.max(), 40)
frontier = np.array([stats(min_vol(t)) for t in targets])      # columns: return, volatility

# 3. Maximum Sharpe ratio (the tangency portfolio)
res = minimize(lambda w: -(w @ mu.values - rf) / np.sqrt(w @ cov @ w), np.ones(n) / n, bounds=[(0, 1)] * n,
               constraints=[{"type": "eq", "fun": lambda w: w.sum() - 1}], method="SLSQP")
w_sharpe = res.x

fig, ax = plt.subplots(figsize=(10, 6.5))
sc = ax.scatter(rand_vol, rand_ret, c=rand_sharpe, cmap="plasma", s=9, alpha=0.7)
ax.plot(frontier[:, 1], frontier[:, 0], color="black", lw=2.2, label="Efficient frontier")
ax.scatter(*stats(w_minvol)[::-1], marker="*", s=300, color="#1f77b4", edgecolor="white", zorder=5, label="Minimum volatility")
ax.scatter(*stats(w_sharpe)[::-1], marker="*", s=300, color="#d62728", edgecolor="white", zorder=5, label="Maximum Sharpe")
ax.scatter(vol, mu, marker="D", s=40, color="white", edgecolor="black", zorder=4)
for name in assets:
    ax.annotate(name, (vol[name], mu[name]), xytext=(6, -3), textcoords="offset points", fontsize=9)
fig.colorbar(sc, label="Sharpe ratio")
ax.xaxis.set_major_formatter("{x:.1%}")
ax.yaxis.set_major_formatter("{x:.1%}")
ax.set_xlim(0.04, 0.26)
ax.set_xlabel("Volatility (annual)")
ax.set_ylabel("Expected return (annual)")
ax.legend(loc="lower right")
plt.show()

Scatter of 6000 random portfolios colored by Sharpe ratio, a black efficient frontier curve along their upper edge, and stars marking the minimum volatility and maximum Sharpe portfolios, with the six single assets as diamonds

The frontier starts at the minimum-volatility portfolio (5.6% volatility, 4.1% return) and ends at 100% Emerging, the highest-return asset, at 23.0% volatility. Emerging is the only single asset on the frontier, US Stocks sits just under it and the other four are well inside, so a mix beats each of them. The best of the 6,000 random portfolios has a Sharpe ratio of 0.477, and the optimizer finds 0.487, which shows why random search alone is not enough: the optimum sits on the edge of the cloud, where few random draws land.

The two highlighted portfolios, with weights printed by the next block's code:

Return Volatility Sharpe Largest weights
Minimum volatility 4.07% 5.62% 0.37 Bonds 84%, US Stocks 9%, Gold 7%
Maximum Sharpe 5.51% 7.22% 0.49 Bonds 50%, US Stocks 36%, Gold 14%

The Sharpe ratio here is (return - rf) / volatility with rf = 2%. The best single asset, US Stocks, has a Sharpe ratio of 0.41, so mixing it with bonds and gold improves the return per unit of risk.

What are the weights along the frontier?

A point on the frontier says how much risk and return, but not what to hold. Plot the weights of each frontier portfolio as a stacked area, ordered from the minimum-volatility end to the highest-return end:

weights = pd.DataFrame([min_vol(t) for t in targets], columns=assets)
weights.index = frontier[:, 1]                          # label each portfolio by its volatility

fig, ax = plt.subplots(figsize=(10, 5))
ax.stackplot(weights.index, weights.T.values, labels=assets,
             colors=["#264653", "#2a9d8f", "#8ab17d", "#e9c46a", "#f4a261", "#e76f51"])
ax.xaxis.set_major_formatter("{x:.1%}")
ax.set_xlabel("Portfolio volatility (annual)")
ax.set_ylabel("Weight")
ax.set_xlim(weights.index.min(), weights.index.max())
ax.set_ylim(0, 1)
ax.legend(loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()
print(pd.concat([pd.Series(w_minvol, index=assets), pd.Series(w_sharpe, index=assets)], axis=1,
                keys=["Min volatility", "Max Sharpe"]).round(3).to_string())

Stacked area chart of portfolio weights along the efficient frontier, starting mostly in bonds at low volatility and shifting to stocks and emerging markets at high volatility

             Min volatility  Max Sharpe
US Stocks             0.094       0.360
Intl Stocks           0.000       0.000
Emerging              0.000       0.001
Bonds                 0.839       0.500
Real Estate           0.000       0.000
Gold                  0.068       0.138

At the low-risk end the portfolio is mostly bonds. As the target return rises, bonds are replaced by US Stocks, and bonds are gone by about 13% volatility. Past 16% volatility (where US Stocks is 84% of the portfolio) the optimizer swaps US Stocks for Emerging until it holds only Emerging at 23%. Intl Stocks and Real Estate are never used: their expected return is lower than US Stocks while their correlation with it is high (0.80 and 0.70), so they add risk without enough extra return. That is a result of these inputs, not a general fact about those assets.

How do I add the capital market line?

If you can also hold the risk-free asset, the best portfolios lie on the line from the risk-free rate through the max-Sharpe portfolio. Its slope is the Sharpe ratio. Draw it past the tangency point to show portfolios bought with borrowed money:

ret_s, vol_s = stats(w_sharpe)
sharpe_max = (ret_s - rf) / vol_s
xs = np.linspace(0, 0.20, 50)

fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(frontier[:, 1], frontier[:, 0], color="black", lw=2.2, label="Efficient frontier")
ax.plot(xs, rf + sharpe_max * xs, color="#d62728", lw=1.8, ls="--", label=f"Capital market line (slope {sharpe_max:.2f})")
ax.scatter(vol_s, ret_s, marker="*", s=300, color="#d62728", edgecolor="white", zorder=5, label="Maximum Sharpe")
ax.scatter(0, rf, color="#d62728", zorder=5)
ax.annotate(f"Risk-free {rf:.0%}", (0, rf), xytext=(8, -14), textcoords="offset points")
ax.xaxis.set_major_formatter("{x:.1%}")
ax.yaxis.set_major_formatter("{x:.1%}")
ax.set_xlabel("Volatility (annual)")
ax.set_ylabel("Expected return (annual)")
ax.set_xlim(0, 0.20)
ax.set_ylim(0, 0.11)
ax.legend(loc="lower right")
plt.show()

Efficient frontier curve with a dashed capital market line from the risk-free rate touching it at the maximum Sharpe portfolio

The line leaves the risk-free rate (2%) and touches the frontier at the max-Sharpe portfolio. Anywhere on the line to the left of the star is a mix of cash and that portfolio, and anywhere to the right is that portfolio bought with borrowed money (it assumes you can borrow at the risk-free rate, which most investors cannot). At 15% volatility the line offers 9.3% against 8.3% on the long-only frontier, so if you could borrow cheaply you would not hold the high-volatility frontier portfolios at all.

How much do the results depend on the inputs?

The optimizer takes mu as given, and expected returns are the hardest input to estimate. Nudge each by a random amount of up to 1 percentage point (a small error for annual return forecasts) and re-solve for the max-Sharpe weights:

rng2 = np.random.default_rng(2)
rows = {}
for k in range(4):
    mu_noisy = mu.values + rng2.uniform(-0.01, 0.01, n)
    r = minimize(lambda w: -(w @ mu_noisy - rf) / np.sqrt(w @ cov @ w), np.ones(n) / n, bounds=[(0, 1)] * n,
                 constraints=[{"type": "eq", "fun": lambda w: w.sum() - 1}], method="SLSQP")
    rows[f"Try {k + 1}"] = r.x
sens = pd.concat([pd.Series(w_sharpe, index=assets, name="Original"), pd.DataFrame(rows, index=assets)], axis=1)
print(sens.round(2).to_string())
             Original  Try 1  Try 2  Try 3  Try 4
US Stocks        0.36   0.42   0.29   0.31   0.34
Intl Stocks      0.00   0.00   0.00   0.00   0.00
Emerging         0.00   0.09   0.02   0.00   0.00
Bonds            0.50   0.21   0.62   0.54   0.49
Real Estate      0.00   0.00   0.00   0.00   0.00
Gold             0.14   0.28   0.07   0.14   0.17

With the same covariance matrix and each expected return off by at most one percentage point, the bond weight in the max-Sharpe portfolio ranges from 21% to 62% and gold from 7% to 28%. The risk model is unchanged, but the portfolio picked jumps around. This is the main practical weakness of mean-variance optimization: the weights are very sensitive to the return estimates, so use constraints (a maximum weight per asset), shrink the estimates toward a common value, or treat the weights as a starting point.

Practical Tips

  • Use annualized inputs consistently. Daily returns times 252 for the mean, daily covariance times 252 for the covariance. Mixing units shifts the whole frontier.
  • Long-only needs bounds. bounds=[(0, 1)] * n forbids shorting. Without them the optimizer can return negative weights and a frontier far above the random cloud.
  • Sample means are noisy. Historical average returns carry large estimation error. Treat the frontier as a way to see diversification, not as a forecast, and consider constraints such as a maximum weight per asset.
  • Check res.success. minimize returns a result object even when it did not converge, with success=False and a message. Print res.message if a frontier point looks off, especially for targets near the highest-return asset.
  • Libraries exist for the full workflow. PyPortfolioOpt and cvxpy add constraints, shrinkage covariance estimators and transaction costs. This post sticks to NumPy and scipy so every step is visible.

Similar Topics