Mean-Variance
Calculate the weights of a mean-variance efficient portfolio. With a target return, it is the portfolio with the lowest volatility that expects that return. Without one, it is the portfolio that maximizes the investor’s utility, the expected return minus half the risk aversion times the variance: w’μ - (λ/2) w’Σw.
A risk aversion of 2 to 4 is typical; 2.5 is the value commonly used for the market as a whole.
For more information, see the following paper:
- Markowitz, H. (1952). “Portfolio Selection.” The Journal of Finance, 7(1), 77-91.
Also known as: Markowitz portfolio, efficient portfolio, quadratic utility portfolio.
Mean-Variance in Python or via the MCP
Install the Finance Toolkit with:
pip install financetoolkit -U
Then call get_mean_variance_weights as shown below.
from financetoolkit import Toolkit
toolkit = Toolkit(
["AAPL", "MSFT", "JNJ", "XOM"],
api_key="FINANCIAL_MODELING_PREP_KEY",
start_date="2021-01-01",
end_date="2025-12-31",
)
toolkit.portfolio.get_mean_variance_weights(target_return=0.15)
Or, after setting up the Finance Toolkit MCP, ask:
Which mix of Apple, Microsoft, Johnson & Johnson and ExxonMobil had the lowest volatility for a 15% expected return, based on 2021 to 2025?
Which returns:
| Weight | Expected Return | Volatility | Sharpe Ratio | Risk Contribution | |
|---|---|---|---|---|---|
| AAPL | 0.0219 | 0.1933 | 0.2786 | 0.5727 | 0.0211 |
| MSFT | 0.2058 | 0.2017 | 0.2572 | 0.6532 | 0.1961 |
| JNJ | 0.6256 | 0.0984 | 0.1673 | 0.3867 | 0.6549 |
| XOM | 0.1467 | 0.291 | 0.2702 | 0.9522 | 0.1279 |
| Portfolio | 1 | 0.15 | 0.1355 | 0.8583 | 1 |
Parameters
get_mean_variance_weights accepts the following parameters.
| Parameter | Type | Description | Example |
|---|---|---|---|
target_return | float | None | The annualized return the portfolio must expect, e.g. 0.12 for 12%. Defaults to None, which uses the risk aversion. | None, which uses the risk aversion |
risk_aversion | float | The investor’s risk aversion λ; higher values give less risky portfolios. Defaults to 2.5. | 2.5 |
period | str | The frequency of the returns (daily, weekly, monthly, quarterly or yearly). Defaults to “daily”. | "weekly" |
minimum_weight | float | The lowest weight an asset may have. Defaults to 0. | 0 |
maximum_weight | float | The highest weight an asset may have. Defaults to 1. | 1 |
include_benchmark | bool | Whether to include the benchmark as an asset. Defaults to False. | True |
rounding | int | None | The number of decimals to round the results to. Defaults to None, which uses the Toolkit’s rounding. | 2 |