liveBook · Manning

Cvxpy

As explained in Build a Robo-Advisor with Python (From Scratch)

CVXPY is a Python library for modeling and solving convex optimization problems with a declarative mathematical syntax.

CVXPY is a Python modeling layer for expressing and solving convex optimization problems with readable mathematical syntax. It sends a formulated problem to a solver rather than implementing the optimization algorithm itself. section 1.4 section 10.1.3

A typical portfolio model defines:

  • Decision variables such as portfolio weights. section 10.2.1
  • An objective, such as minimizing variance or maximizing expected return. section 10.2.1
  • Constraints such as a required return, weights summing to one, nonnegative holdings, or a volatility budget. section 10.2.1

Minimum-risk portfolio

Given expected returns μ and covariance matrix Σ, minimize wᵀΣw subject to μᵀw ≥ μp and the weights summing to one. CVXPY represents the quadratic risk with cp.quad_form(w, Sigma) and the budget with cp.sum(w). Without a long-only constraint, the sample solution includes negative weights; adding w ≥ 0 produces a different portfolio. section 10.2.1

def get_default_inputs():
    tickers = ['VTI', 'VEA', 'VWO', 'AGG', 'BNDX', 'EMB']
    ers = pd.Series([.05, .05, .07, .03, .02, .04], tickers)
    sigma = np.array(
        [[0.0287, 0.0250, 0.0267, 0.0000, 0.0002, 0.0084],
         [0.0250, 0.0281, 0.0288, 0.0003, 0.0002, 0.0092],
         [0.0267, 0.0288, 0.0414, 0.0005, 0.0004, 0.0112],
         [0.0000, 0.0003, 0.0005, 0.0017, 0.0008, 0.0019],
         [0.0002, 0.0002, 0.0004, 0.0008, 0.0010, 0.0011],
         [0.0084, 0.0092, 0.0112, 0.0019, 0.0011, 0.0083]])
    sigma = pd.DataFrame(sigma, tickers, tickers)

    return ers, sigma

Use the supplied inputs to explore six-asset allocation across US, developed-market, and emerging-market stocks and bonds. section 10.3

How Build a Robo-Advisor with Python (From Scratch) covers it

How deep it goes
Defines variables, objectives, constraints, solver delegation, and portfolio formulations, but stops short of implementing solver algorithms.
Examples
Uses scalar quadratic minimization, three-asset mean-variance portfolios, risk-budget formulations, and six-ETF allocation.
What it assumes
Assumes basic Python familiarity and introduces optimization through expected returns, covariance matrices, objectives, and constraints.
What you can do after
Build convex portfolio and rebalancing models in Python, then solve them through a compatible optimization solver.
How it connects
Connects convex optimization with portfolio construction, mean-variance optimization, covariance matrices, expected returns, and rebalancing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Robo-Advisor with Python (From Scratch). The section links point to the parts of the book it draws on.