Reference 0007

CVXPY Portfolio Template

A minimal single-period portfolio quadratic program with constraints and dual diagnostics.

Model

minimize    0.5 * w' Sigma w - mu' w
subject to  sum(w) = 1
            0 <= w
            w <= cap

Code Skeleton

import cvxpy as cp
import numpy as np

mu = np.array([...])
Sigma = np.array([...])
cap = np.array([...])

w = cp.Variable(len(mu))
objective = cp.Minimize(0.5 * cp.quad_form(w, Sigma) - mu @ w)

constraints = [
    w >= 0,
    w <= cap,
    cp.sum(w) == 1,
]

problem = cp.Problem(objective, constraints)
problem.solve()

weights = w.value
upper_slack = cap - weights
upper_duals = constraints[1].dual_value

Readout Checklist

1. Check status: problem.status
2. Read primal weights: w.value
3. Compute slack: cap - w.value
4. Read upper-cap duals: constraints[1].dual_value
5. Pair each slack with its dual before interpreting economics

Common Mistakes

Reading duals alone

Always pair a dual with slack. The pair tells you whether a constraint is tight and scarce.

Mixing constraints

constraints[1] is only the upper cap if you put w <= cap second. Constraint order matters.

Forgetting convention

This template is minimization form. Portfolio papers may present the equivalent maximization form.

Ignoring tolerance

Treat tiny values such as 1e-8 as numerical zero unless solver settings require tighter accuracy.

Use this page with Lesson 0007 and Reference 0006.