Build an Optimal Stock Portfolio with Markowitz Mean‑Variance Model in Python
This article explains how to model and solve a three‑stock portfolio optimization problem using Markowitz's mean‑variance framework, compute asset statistics with Python, and obtain the optimal allocation via quadratic programming.
Investment returns are evaluated using net present value (NPV) and diversification reduces risk. The Markowitz mean‑variance model (1952) treats asset returns as random variables characterized by mean, variance and covariance.
For three stocks A, B, C with historical prices (1943‑1954) and the S&P 500 index, the article shows how to compute each stock’s expected return, variance and the covariance matrix using Python.
<code>import pandas as pd
data = pd.read_excel('data/马科维兹.xlsx')
stock = data.iloc[:,1:-1]
ER = stock.mean()
COV = stock.cov()
</code>The resulting covariance matrix is presented, and the diagonal entries give the variances of the three stocks while off‑diagonal entries indicate their pairwise covariances.
Quadratic Programming Model
Decision variables represent the proportion of capital allocated to each stock, with the constraint that the sum equals one. The objective is to minimize portfolio variance subject to a target expected return (e.g., at least 15%).
Using the cvxopt.solvers.qp function, the quadratic program is formulated and solved in Python:
<code>from cvxopt import matrix, solvers
P = matrix(2*COV.values)
q = matrix([0.0,0.0,0.0])
G = matrix([ER.values.tolist(),[1.0,1.0,1.0]],(2,3))
h = matrix([-0.15,0.0])
A = matrix([1.0,1.0,1.0],(1,3))
b = matrix([1.0])
result = solvers.qp(P,q,G,h,A,b)
print('x',result['x'])
</code>The optimal solution yields the weight of each stock in the portfolio and the corresponding minimal risk.
Reference: Zhang Jingxin et al., *Mathematical Modeling Algorithms and Programming Implementation*.
Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.