Introduction

An investor prefers higher expected return and lower risk, but the two often conflict since higher expected return generally comes with higher risk. Thus, their goal is to obtain the greatest expected return available at each level of risk.

Risk and Return

Computing the returns

Given the price series of
th security, the corresponding return series can be computed as follows
where
is the price of the
th security at time

How to measure the risk

In the context of investment, the risk of a security is measured by how much its returns vary over time. Higher variability tends to mean larger potential losses, though it also means the stock can move further to the upside. Because variance captures this spread in both directions, we use it to quantify risk.

Modern Portfolio Theory

Often, the investor holds multiple securities simultaneously so as to reduce the overall risk they bear. The specific combination of
securities an investor holds is referred to as a portfolio and is mathematically represented by a vector
of weights that sum to 1.

Mean-Variance Analysis

Portfolio Expected Return

A portfolio’s return is given by the weighted sum of the returns of its
securities.
where
is the random variable representing the return of the
th security. Then, the expected return is just a weighted sum of the mean returns of the individual securities held by the portfolio.
Compute the sample mean of a portfolio return
In[]:=
portfolioMeanReturn[portfolioWeights_List,sampleMeanReturns_List]:=portfolioWeights.sampleMeanReturns

Portfolio Risk

Just as in the case of a single security, the risk of a portfolio is quantified by the variance of its return
Thus, quantifying the risk of a portfolio reduces to computing the sample covariance matrix
of the
securities’ returns. We estimate it from the return data matrix
where each column is the return time series of one security and each row is a single period’s cross-section. Then, we compute the sample covariance matrix on the centered data,
.
Compute the sample portfolio variance
In[]:=
portfolioVariance[covarianceMatrix_?MatrixQ,portfolioWeights_List]:=​​ portfolioWeights.covarianceMatrix.portfolioWeights

Diversification reduces the risk

As we’ve shown above, the variance of a portfolio return can be decomposed into the part specific to an individual security and the part common to multiple securities. In finance theory, we refer to each as the specific and systematic risk.
Note that positive covariance among the securities increases the overall portfolio risk while the negative covariance decreases the overall portfolio risk.
To understand why diversification reduces the overall risk of a portfolio, we can consider an equally weighted portfolio with
for each
. If we define the average variance and average covariance as follows
then, we can rewrite the variance of the portfolio return using the average variance and covariance terms.
As the number of securities in a portfolio increases, the variance of the portfolio tends to the average covariance among the securities.
This means for a well-diversified portfolio, the investor is more concerned about the systematic risk measured by the average covariance rather than individual stocks’ risks that are diversified away.
To graphically demonstrate this, consider the set of S&P 500 stocks. The plan is to estimate the covariance structure of a large, real set of stocks, and observe how the variance of the equal-weight portfolio changes as we add securities. Firstly, we take the current members of the index, pull three years of daily returns for each, and reduce them to a single return panel with one column per stock and one row per trading day.
Retrieve the tickers of the stocks in S&P 500
In[]:=
allTickers=FinancialData["^SPX","Members"];
Retrieve the return time series of each S&P 500 stock
In[]:=
returnTimeSeries=MonitorAssociation​​Tableticker->FinancialDataticker,"Return",
Tue 28 Jul 2026
-Quantity[3,"Years"],
Tue 28 Jul 2026
,{ticker,allTickers}​​,ticker;
Find missing data
In[]:=
Select[returnTimeSeries,MissingQ]
Out[]=

Delete missing data
In[]:=
returnTimeSeries=DeleteMissing[returnTimeSeries];​​allTickers=Keys[returnTimeSeries];
In[]:=
Length[allTickers]
Out[]=
499
The stocks differ in how far back their data goes, so we first find the the date span over which the bulk of them are available.
In[]:=
Counts[DateDifference[#["FirstDate"],#["LastDate"]]&/@returnTimeSeries]
Out[]=

1092
days
229,
1093
days
203,
1089
days
52,
586
days
1,
921
days
1,
665
days
1,
1001
days
1,
1036
days
1,
1066
days
1,
846
days
2,
798
days
1,
353
days
1,
265
days
1,
528
days
1,
748
days
1,
1048
days
1,
1018
days
1
In[]:=
dateRange=Commonest[Values[DateDifference[#["FirstDate"],#["LastDate"]]&/@returnTimeSeries]​​][[1]]
Out[]=
1092
days
Keep only the stocks whose history spans the full three-year window
In[]:=
filteredReturnTimeSeries=Select[returnTimeSeries,DateDifference[#["FirstDate"],#["LastDate"]]>=dateRange&​​];
The set of all tickers in the time window
In[]:=
selectedTickers=Keys[filteredReturnTimeSeries];
Find the intersection of all dates in each time series object
In[]:=
commonDates=Intersection@@(#["Dates"]&/@Values[filteredReturnTimeSeries]);
Construct the return data matrix
In[]:=
returnDataMatrix=Transpose[​​Table[​​With[{ts=filteredReturnTimeSeries[ticker]},​​UnitConvert/@(AssociationThread[ts["Dates"]->ts["Values"]]/@commonDates)​​],{ticker,selectedTickers}​​]​​];
From the return panel, we estimate the covariance matrix
, which is what the equal-weight variance formula requires.
Compute the covariance matrix
In[]:=
σ=Covariance[returnDataMatrix];​​Dimensions[σ]
Average the equal-weight portfolio standard deviations over many random samples of each size
Compute the minimum of the portfolio standard deviations
Compute the square root of the average covariance

Portfolio Optimization

How should we choose the best weights? As discussed in the preceding section, a portfolio can be characterized by its expected return and risk, which means we can represent each portfolio as a point in a risk-return space. Then, finding the portfolios that
minimize the risk for a specified level of expected returns can be formulated as the following constrained optimization problem.
Compute mean return vector for stocks in S&P 500
Find the portfolio weights that minimize the risk for a specified level of expected return
Compute the standard deviation and mean return for each of the above portfolios
When we plot the mean portfolio return against the corresponding portfolio standard deviation for the above portfolios, we obtain the portfolio frontier or the minimum variance boundary. Therefore, all feasible portfolios lie inside bullet shaped region surrounded by the portfolio frontier.
Visualize the portfolio frontier.
Find the global minimum variance portfolio
Compute the mean return of the GMVP
Visualize the efficient portfolio frontier
Among the portfolios that lie on the frontier, those that have the highest expected return for their level of risk, or equivalently the lowest risk for their level of expected return, are called efficient portfolios. These portfolios form the efficient frontier, which is the red upper part of the curve in the above plot. A mean-variance optimizing investor will hold a portfolio on the efficient frontier to maximize the expected return for a given level of risk.

The Capital Market Line and the Market Portfolio

The Tangency Portfolio

The Efficient Frontier with a Risk-Free Security

For the risk-free rate we use the 3-month Treasury bill yield, averaged over the same three-year window as our return data. A short maturity keeps the security riskless over our holding period, and the averaging keeps the rate comparable to the sample mean returns.
Obtain the risk-free interest rate for the time span of our data
Find the optimal portfolio weights that minimize the variance
Compute the standard deviation and mean return for each of the above portfolios
Visualize the portfolio space
From this visualization, we can observe that the efficient frontier with a risk-free asset is a line tangent to the bullet-shaped frontier. The point of tangency is the tangency portfolio, and the line is known as the capital market line (CML) represented by the following equation:

The Market Portfolio

If every investor optimizes as we did, they all end up holding the same portfolio of risky securities, the tangency portfolio, combined with a risk-free asset. Now, every share of every company is owned by someone. So if we add up what all investors hold, we get the whole stock market, where each company takes up a share proportional to its total value. And if every investor holds the same mix, that mix has to be the market’s own proportions. The tangency portfolio is therefore the market portfolio.
To construct this line, we use the S&P 500 index return data to estimate the market portfolio return and standard deviation.
Obtain the market return data
Compute the mean market return
Compute the standard deviation of the market return
Capital market line
Visualize the capital market line
Compute the Sharpe ratio of the market portfolio

Comparing the Two Portfolios

Compute the Sharpe ratio of the tangency portfolio
The tangency portfolio computed from our sample attains a Sharpe ratio of 3.56, while the S&P 500 index (the market portfolio) over the same time window attains 0.847. In theory, the tangency portfolio and the market portfolio are the same portfolio, so their Sharpe ratios should agree. However, the data do not show this.

References

◼
  • Lo, A. (2008). Lecture 13–14: Risk Analytics and Portfolio Theory : Risk Analytics and Portfolio Theory. 15.401 Finance Theory I, Fall 2008. MIT OpenCourseWare. https://ocw.mit.edu/courses/15-401-finance-theory-i-fall-2008/resources/mit15_401f08_lec13/
  • ◼
  • Haugh, M. (2016). Mean-variance optimization and the CAPM. IEOR E4706: Foundations of Financial Engineering, Columbia University. https://www.columbia.edu/~mh2078/FoundationsFE/MeanVariance-CAPM.pdf
  • ◼
  • Brealey, R. A., Myers, S. C., Allen, F., & Edmans, A. (2023). Principles of corporate finance (14th ed.). McGraw Hill.
  • CITE THIS NOTEBOOK

    A computational exploration of the modern portfolio theory​
    by Junseo Lee​
    Wolfram Community, STAFF PICKS, July 30, 2026
    https://community.wolfram.com/groups/-/m/t/3770513