Monte Carlo Portfolio Allocation in Python: Random Weights vs an Optimiser

Introduction — Why throw random weights at a solved problem?

Mean-variance portfolio selection is, mathematically, a solved problem: the documentation for PyPortfolioOpt describes it as “a convex optimization problem” that can be solved “using quadratic programming”. So why would anyone throw thousands of random weight vectors at it and keep the best one? Because brute-force simulation is easy to understand, easy to modify, and produces a picture of the whole risk-return landscape rather than a single point — and because a solver is only as good as its inputs. This post covers choosing portfolio weights by simulation and by optimisation; it is distinct from our earlier post on Monte Carlo simulation methodology, which covers trade-order resampling for backtest validation rather than allocation.

Throughout, we stick to what the sources actually say. Where they are silent — and they are silent about more than you might expect — we say so explicitly.

Two Monte Carlo flavours: random weights vs. simulated return paths

“Monte Carlo portfolio allocation” bundles two quite different techniques:

  1. Random weights. Draw candidate weight vectors, score each one, keep the best. The Efficient Frontier – Monte Carlo Portfolio Optimization repository works this way: it “Randomly allocates weights among assets thousands of times” and “Generates up to hundreds of thousands of random portfolio allocations.” The prices feeding the scoring are historical; only the weights are random.
  2. Simulated return paths. Generate synthetic return samples and feed them into an optimiser. PyPortfolioOpt’s General Efficient Frontier documentation explicitly allows this for its risk models: “Suppose we have a sample of T daily returns (these can either be historical or simulated)”.

The second flavour is where the sourcing gets thin. No source reviewed here specifies a path generator — no engine, no calibration, no horizon. How one might build such paths is therefore not established by these sources, and we will only sketch an illustrative generator, clearly labelled, later in the post.

Setup: prices, expected returns, covariance

Every method below shares the same inputs. Mean-variance optimization “requires two things: the expected returns of the assets, and the covariance matrix”, and PyPortfolioOpt’s User Guide provides estimators for both: mean_historical_return(df) for expected returns and CovarianceShrinkage(df).ledoit_wolf() for a shrinkage estimate of the covariance matrix. The documentation is careful to note these are estimates — the inputs live in the expected_returns and risk_models modules precisely because they must be estimated from data.

On the data side, the Monte Carlo repository “Automatically fetches historical data from Yahoo Finance”, so a price DataFrame is the natural starting point for either approach.

Random-weight simulation walkthrough

Sampling candidate weights

The core loop is simple: draw a weight per asset, normalise so the weights sum to one, repeat. The repository “Randomly allocates weights among assets thousands of times”, with the number of draws controlled by a CLI parameter whose README lists “Default: 100000”. One honest caveat before the code: the exact sampling distribution the repo uses is not established by these sources — the README names no distribution, and whether its weights are long-only, fully invested, or bounded is likewise not established by these sources. The uniform-then-normalise scheme below is an illustrative author choice, not a description of the repo’s internals.

import numpy as np
import pandas as pd

# author choice: ticker list
tickers = ["AAPL", "MSFT", "TSLA"]
prices = pd.read_csv("prices.csv", index_col=0, parse_dates=True)[tickers]

returns = prices.pct_change().dropna()
# author choice: trading periods per year used for annualising statistics
periods_per_year = 252
mu = returns.mean() * periods_per_year
cov = returns.cov() * periods_per_year
# author choice: annual risk-free rate
risk_free_rate = 0.05

# author choice: number of random portfolios to draw
n_portfolios = 100_000
# author choice: RNG seed for reproducibility
rng = np.random.default_rng(42)

n_assets = len(tickers)
weights = rng.random((n_portfolios, n_assets))
weights /= weights.sum(axis=1, keepdims=True)  # long-only, fully invested

port_returns = weights @ mu.to_numpy()
port_vols = np.sqrt(np.einsum("ij,jk,ik->i", weights, cov.to_numpy(), weights))
sharpes = (port_returns - risk_free_rate) / port_vols

Scoring each draw: return, risk, Sharpe

Each simulated portfolio is scored on return, risk, and Sharpe ratio. Per the PyPortfolioOpt User Guide, “the portfolio return is equal to each stock’s weight multiplied by its return, i.e w^T μ”, and “The portfolio risk in terms of the covariance matrix Σ is given by w^T Σ w”. The Sharpe ratio “is the portfolio’s return in excess of the risk-free rate, per unit risk (volatility)”, with SR = (R_P - R_f)/σ. The repository’s own annualisation and risk-free conventions are only partially documented: its configuration notes “Trading Days: Set to 252, typical for US markets”, and its CLI exposes --risk_free_rate as “Risk-free rate (annualized). Default: 0.05.” — but precisely how the simulated statistics are annualised, and whether the risk-free rate is subtracted before or after annualisation, is not established by these sources.

Keeping the best draw — and what that means

The final step is an argmax over the simulated Sharpes. The repository “identifies the portfolio with the highest Sharpe Ratio” among its random allocations and “compares its performance to a market benchmark (e.g., SPY)”. The honest framing matters: that portfolio is the best among the simulated draws, not a proven optimum. No source states any convergence guarantee, sample-size threshold, or bound on how far the sampled maximum sits from the true maximum — this is not established by these sources.

best_idx = int(np.argmax(sharpes))
best_weights = dict(zip(tickers, weights[best_idx]))

The closed-form baseline with PyPortfolioOpt

Mean-variance via EfficientFrontier

The optimiser side of the comparison solves the problem directly. The User Guide states the long-only formulation: minimise w^T Σ w subject to w^T μ ≥ μ*, w^T 1 = 1, and w_i ≥ 0 — “a convex optimization problem” solvable “using quadratic programming”. Rather than searching over draws, the docs note that “it often makes more sense to just find the portfolio that maximises the Sharpe ratio”, which “is implemented as the max_sharpe() method in the EfficientFrontier class”.

from pypfopt import EfficientFrontier, expected_returns, risk_models
from pypfopt import objective_functions

df = prices  # DataFrame of prices, one column per ticker

mu = expected_returns.mean_historical_return(df)
S = risk_models.CovarianceShrinkage(df).ledoit_wolf()

ef = EfficientFrontier(mu, S)  # long-only bounds, an author choice; the User Guide does not state this class default
ef.add_objective(objective_functions.L2_reg, gamma=0.1)  # gamma taken from the documentation's example
weights = ef.max_sharpe()
cleaned = ef.clean_weights()  # per the docs, this "truncates tiny weights to zero and rounds the rest"

Constraints, regularisation, tidy-up

The User Guide documents a range of controls: weight_bounds=(-1,1) permits shorting, though within the EfficientFrontier class market-neutral portfolios are “only available for the efficient_risk() and efficient_return() optimization methods for mathematical reasons” (the General Efficient Frontier classes list market_neutral as a method parameter General Efficient Frontier). Adding objective_functions.L2_reg with gamma=0.1 “encourage[s] the optimizer to choose different weights”, pushing toward more diversified solutions. Afterwards, clean_weights() tidies the output and save_weights_to_file() persists it.

Reading the documentation’s example numbers

The User Guide’s worked example calls ef.portfolio_performance(verbose=True) on its sample dataset and prints “Expected annual return: 33.0% / Annual volatility: 21.7% / Sharpe Ratio: 1.43”. These are the documentation’s example output on its sample data — an in-sample figure, not a backtest, and not a result produced for this post. The documentation does not disclose the risk-free rate used in that example, and how any such rate is handled beyond the defaults quoted above is not established by these sources.

Feeding simulated paths to risk-based optimisers

The second Monte Carlo flavour inverts the logic: instead of random weights on historical statistics, you feed simulated return samples into a risk-based optimiser. The General Efficient Frontier page documents EfficientSemivariance, EfficientCVaR, and EfficientCDaR, with methods min_semivariance(), min_cvar(), and min_cdar() respectively. For CVaR, the docs state that with a sample of T daily returns — which “can either be historical or simulated” — the problem “reduces to a linear program”.

Two practical warnings come straight from the documentation. First, scale: semivariance “uses 2T + N optimization variables”, so “for 50 assets and 3 years of data, there are about 1500 variables”, and the docs suggest you “keep EfficientSemivariance problems small and minimally constrained”. Second, interface limits: on EfficientSemivariance the docs note that parent methods “like max_sharpe() and min_volatility() are not applicable to mean-semivariance portfolios, so calling them returns NotImplementedError”; the EfficientCVaR and EfficientCDaR pages simply list no max_sharpe() method. When reporting performance, portfolio_performance(verbose=False, risk_free_rate=0.02) is the documented signature for EfficientSemivariance, with the caveat that “The period of the risk-free rate should correspond to the frequency of expected returns.”

The path generator itself is the unsourced part. The following block is purely illustrative; its scheme is not established by these sources.

# Illustrative only — this path-generation scheme is an author choice,
# not established by these sources.
import numpy as np

# author choice: number of simulated daily return paths
n_paths = 10_000
# author choice: horizon in trading days per path
horizon = 252
# author choice: RNG seed
rng = np.random.default_rng(7)

mu_daily = returns.mean().to_numpy()
cov_daily = returns.cov().to_numpy()
# author choice: multivariate normal draws as a stand-in path generator
sim_returns = rng.multivariate_normal(mu_daily, cov_daily, size=(n_paths, horizon))

Honesty check: what each method assumes vs. guarantees

Method What it assumes What it does not guarantee
Random-weight Monte Carlo (repo README) Historical prices from Yahoo Finance; a risk-free rate input (“annualized”, default 0.05); a draw count (default 100000). The sampling distribution is not established by these sources. That the highest-Sharpe draw is the true optimum; any convergence or accuracy bound; out-of-sample performance — the repo itself warns “Past performance does not guarantee future results.”
PyPortfolioOpt mean-variance / max_sharpe() (User Guide) Expected returns and a covariance matrix, both estimated (mean_historical_return, CovarianceShrinkage().ledoit_wolf()); a convex problem solved by quadratic programming. That the estimates reflect the future; the docs’ own characterisation is that minimum-variance portfolios “consistently outperform maximum Sharpe ratio portfolios out-of-sample … because of the difficulty of forecasting expected returns”.
CVaR / semivariance on historical-or-simulated returns (General Efficient Frontier) A sample of T return observations, which “can either be historical or simulated”; the problem “reduces to a linear program”. Any path-generator methodology — none is specified and any specifics are not established by these sources; also no max_sharpe() method listed, and NotImplementedError is documented for max_sharpe() on EfficientSemivariance only.
Riskfolio-Lib (Documentation index) Only that the library exists and organises its docs into sections such as “Convex Portfolio Models”, “Hierarchical Clustering Models”, and “Backtesting”. Anything at all about its functions or objectives — the provided index page documents no functions or objectives, so any capability claim is not established by these sources.

Note what the table cannot tell you: no head-to-head comparison between the random-weight approach and a closed-form optimiser library exists in these sources. The repo compares its random portfolio to a market benchmark, not to PyPortfolioOpt or Riskfolio-Lib.

Where Riskfolio-Lib fits (and what we can honestly say)

Riskfolio-Lib’s documentation index is the only page available to us, and it is a navigation tree: section headings such as “Convex Portfolio Models”, “Hierarchical Clustering Models”, “Parameters Estimation”, “Risk Functions”, “Reports”, and an “Examples” tree containing “Return Risk Portfolio Optimization Models”, “Risk Parity Models”, “Hierarchical Clustering Portfolio Optimization”, and “Backtesting”. That structure tells you the library’s scope is broad, but the page documents no functions or objectives, so we will not name classes, methods, or defaults for it. Anything more specific would be invention, and specifics about Riskfolio-Lib are not established by these sources.

What These Sources Do Not Establish

This is the most important section of the post. In plain words, the following are not established by these sources:

  • Which approach performs better. No source compares random-weight Monte Carlo against PyPortfolioOpt or Riskfolio-Lib on the same inputs. No head-to-head result exists.
  • Out-of-sample numbers. No source provides out-of-sample return, Sharpe, or drawdown figures for any of these methods. The documentation’s “33.0% / 21.7% / 1.43” is an in-sample example on sample data, not a backtest.
  • Optimality or convergence. Nothing guarantees that the sampled maximum-Sharpe portfolio is optimal, converges to the true optimum, or sits within any stated distance of it.
  • The weight sampling distribution. The repo names no distribution and does not state whether its weights are long-only, fully invested, or bounded.
  • Annualisation and risk-free-rate handling. Beyond the quoted defaults — “Trading Days: Set to 252, typical for US markets”, --risk_free_rate “annualized” at “0.05”, and EfficientSemivariance’s risk_free_rate=0.02 — the conventions are not established by these sources.
  • Return-path generator details. No source specifies an engine, calibration, horizon, or path count; “historical or simulated” is the extent of it.
  • Riskfolio-Lib function names. The index page documents none; naming any would be fabrication.
  • Runtime, stability, and reproducibility. Silent across all sources for both simulation and solver approaches.
  • Transaction costs. Costs, taxes, turnover constraints, and rebalancing frequency are unaddressed everywhere.

From weights to share counts

Weights are not a tradeable artifact until they become share counts. The User Guide documents DiscreteAllocation with da.lp_portfolio() for this, plus get_latest_prices(df) to fetch the most recent prices from your price DataFrame. On the simulation side, the repository saves its artefacts locally: “A PNG file named efficient_frontier_monter_carlo.png is saved locally” and “A CSV file called market_data.csv is saved with the downloaded prices.”

from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices

latest_prices = get_latest_prices(df)
# author choice: total portfolio value in account currency
da = DiscreteAllocation(cleaned, latest_prices, total_portfolio_value=20000)
allocation, leftover = da.lp_portfolio()

Which should you reach for?

We will not pick a winner, because the sources do not support one. Instead, frame the decision around three questions. What are your constraints? If you need shorting bounds, market neutrality (via efficient_risk() or efficient_return() in EfficientFrontier), or custom objectives, the documented optimiser surface in PyPortfolioOpt and its General Efficient Frontier page is explicit about what is supported — including what raises NotImplementedError. What is your objective? Sharpe maximisation, volatility minimisation, semivariance, CVaR, and CDaR are each a documented method call. How much do you trust your estimators? This is the docs’ own concern: they characterise minimum-variance portfolios as “consistently outperform[ing] maximum Sharpe ratio portfolios out-of-sample … because of the difficulty of forecasting expected returns”, and describe Hierarchical Risk Parity as “seems to robustly outperform mean-variance optimization out of sample”. Those are the documentation’s characterisations of research, not our findings — the numbers behind them are not established by these sources.

Whichever route you take, the repository’s disclaimer applies to the whole exercise: “This project is for educational purposes only and is not financial advice.” (repo README)

FAQ

Is the best random portfolio the optimal portfolio? No. It is the best among the simulated draws, not a proven optimum; the repository only claims to “identify the portfolio with the highest Sharpe Ratio” among its allocations, and any convergence guarantee is not established by these sources.

Do I need simulated return paths for random-weight Monte Carlo? No. The repo draws random weights scored against historical statistics; whether it simulates return paths at all is not established by these sources. Simulated paths are a separate technique, documented only as an optional input to CVaR-style optimisers, where samples “can either be historical or simulated” (General Efficient Frontier).

Why does max_sharpe() fail on EfficientSemivariance? Because it is not implemented there — the documentation states that calling it “returns NotImplementedError”. Use min_semivariance() instead.

What risk-free rate should I use? The repo’s CLI default is “0.05” (“annualized”), and EfficientSemivariance’s portfolio_performance defaults to risk_free_rate=0.02 — with the documented caveat that “The period of the risk-free rate should correspond to the frequency of expected returns.” Anything beyond these defaults is not established by these sources (repo; General Efficient Frontier).

Can I short with these tools? PyPortfolioOpt accepts weight_bounds=(-1,1), but market-neutral portfolios are, in the EfficientFrontier class, “only available for the efficient_risk() and efficient_return() optimization methods for mathematical reasons” (User Guide).

The Bottom Line

Random-weight Monte Carlo and closed-form optimisation answer the same allocation question from opposite ends: one searches a cloud of candidate portfolios and keeps the highest-Sharpe draw; the other solves a documented convex problem directly. Both are small amounts of Python, both rest on estimated inputs, and neither comes with a performance verdict in the sources reviewed here — the sampled maximum is not a proven optimum, and the solver’s output is only as good as its expected-return estimate. Use the simulation to see the risk-return landscape, use the optimiser when you need constraints and a precise objective, and treat both as educational starting points rather than answers. “Past performance does not guarantee future results.” (repo README)

How This Guide Was Built

This guide is based on the library documentation and the cited pages only: the PyPortfolioOpt User Guide, its General Efficient Frontier page, the Riskfolio-Lib documentation index, and the Efficient Frontier – Monte Carlo Portfolio Optimization repository README. No backtest or code run was performed by the author; all code blocks are provided for adaptation, and no numeric output in this post comes from our own execution. Where the sources are silent, the post says “not established by these sources” rather than filling the gap.

← Back to all posts