CVX Finance Slides
CVX Finance Slides
Stanford University
2
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
3
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
4
Optimization problem
minimize f0 (x)
subject to fi (x) ≤ 0, i = 1, . . . , m
gi (x) = 0, i = 1, . . . , p
5
Convex optimization problem
minimize f0 (x)
subject to fi (x) ≤ 0, i = 1, . . . , m
Ax = b
▶ variable x ∈ Rn
▶ equality constraints are linear
▶ f0 , . . . , fm are convex: for 𝜃 ∈ [0, 1] ,
6
Why
7
Modeling languages
8
CVXPY
9
Example
CVXPY specification:
import cvxpy as cp
x = cp.Variable(n)
cost = cp.sum_squares(A@x-b) + gamma*cp.norm(x,1)
prob = cp.Problem(cp.Minimize(cost),[cp.norm(x,"inf")<=1])
opt_val = prob.solve()
solution = x.value
▶ A, b, gamma are constants, gamma nonnegative
▶ solve method converts problem to standard form, solves, assigns value attributes
10
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
11
Mean-variance (Markowitz) optimization
maximize 𝜇T w
subject to wT Σw ≤ (𝜎 tar ) 2 , 1T w = 1
w = cp.Variable(n)
objective = mu.T @ w
constraints = [cp.quad_form(w, Sigma) <= sigma**2, cp.sum(w) == 1]
prob = cp.Problem(cp.Maximize(objective), constraints)
prob.solve()
12
Adding practical constraints and objective terms
13
Factor covariance model
Σ = FΣf F T + D
14
Exploiting a factor model
▶ with factor model, cost of portfolio optimization reduced from O(n3 ) to O(nk2 ) flops
[Boyd and Vandenberghe, 2004]
▶ easily exploited in CVXPY
▶ timings for Clarabel open source solver:
15
Backtesting
16
Robustifying Markowitz
17
Example
▶ S&P 100, simulated but realistic 𝜇, target annualized risk 10%
▶ hyper-parameters tuned each year based on previous two years
▶ out-of-sample portfolio performance for basic Markowitz and robust Markowitz
▶ Sharpe ratios 0.2 and 4.6 (using the same mean and covariance)
18
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
19
Expected utility maximization
20
Sample based approximation
21
Sample based approximation in CVXPY
def U(x):
return (x**(1-rho) - 1)/(1-rho)
w = cp.Variable(n)
22
Example
▶ optimize portfolio of one underlying, one call, and one put, both at-the-money
▶ underlying with 1 + r log-normal
▶ CRRA utility with relative risk aversion 𝜌 , W = {w | 1T w = 1}
▶ sample approximation with N = 105 samples
23
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
24
Sparse inverse covariance estimation
25
Sparse inverse covariance estimation in CVXPY
log_likelihood = cp.sum(cp.hstack(
[cp.log_det(Theta) - cp.quad_form(r, Theta) for r in returns]
))
mask = np.triu(np.ones((n, n)), k=1).astype(bool)
objective = log_likelihood - alpha * cp.norm1(Theta[mask])
prob = cp.Problem(cp.Maximize(objective))
prob.solve()
26
Example
▶ daily returns of US, Europe, Asia, and Africa stock indices from 2009 to 2024
▶ figure shows yearly sparsity pattern of inverse covariance; white boxes denote zero entries
2009 2010 2011 2012 2013 2014 2015 2016
27
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
28
Worst-case portfolio risk
29
Worst-case portfolio risk in CVXPY
30
Example
▶ portfolio weights and uncertain covariance
0.5
0.2 + + ±
0.25 + 0.1 − −
w = , Σ = ,
−0.05 + − 0.3 +
0.3
± − + 0.1
▶ + means nonnegative, − means nonpositive, and ± means unknown sign
▶ worst-case risk is 0.18 (volatility 42%)
▶ risk with diagonal covariance matrix is 0.07 (volatility 26%)
▶ worst-case covariance is
0.20
0.14 −0.24 0.14
0.14
0.10 −0.17 0.10
−0.24 −0.17 0.30 −0.17
0.14
0.10 −0.17 0.10
31
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
32
Investment arbitrage
33
Fundamental theorem of asset pricing
34
Check for arbitrage in CVXPY
pi = cp.Variable(m, nonneg=True)
prob = cp.Problem(cp.Minimize(0), [V.T @ pi == p])
prob.solve()
if prob.status == 'optimal':
print('No arbitrage exists')
elif prob.status == 'infeasible':
print('Arbitrage exists')
35
Option price bounds
minimize/maximize pn
subject to V T 𝜋 = p, 𝜋 ≥ 0, 1T 𝜋 = 1
36
Option price bounds in CVXPY
pi = cp.Variable(m, nonneg=True)
p_n = cp.Variable()
p = cp.hstack([p_known, p_n])
37
Example
▶ n = 7 assets:
– a risk-free asset with price 1 and payoff 1
– an underlying asset with price 1 and uncertain payoff
– four vanilla options on the underlying with known (market) prices
▶ m = 200 possible outcomes for the underlying asset, uniformly between 0.5 and 2
▶ we seek price bounds on a collar option with floor 0.9 and cap 1.15
▶ solving optimization problem gives the arbitrage-free collar price range [−0.015, 0.033]
38
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
39
Currency exchange problem
40
Currency exchange in CVXPY
41
Example
▶ USD, EUR, CAD, SEK, with initial and required holdings (in $106 )
0.5
USD EUR CAD SEK
42
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
43
Purchase execution and risk
pt = pt−1 + 𝜉t , t = 2, . . . , T,
E(pT q) = p1 Q, var(pT q) = qT Σq
44
Market impact
T
∑︁ T
∑︁
𝜎𝜋t1/2 qt = 𝜎 q3/2 1/2
t /vt
t=1 t=1
45
Optimal execution
▶ trade off risk and transaction cost, with participation rate limit
Í 3/2 1/2
minimize 𝜎 Tt=1 qt /vt + 𝛾qT Σq
subject to q ≥ 0, 1 q = Q, qt /vt ≤ 𝜋 max ,
T t = 1, . . . , T,
46
Optimal execution in CVXPY
q = cp.Variable(T, nonneg=True)
pi = q / v
47
Example
▶ purchase 10 million Apple shares over 10 trading days (Feb 8–22, 2024)
▶ participation rate limit 𝜋 max = 5%
48
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
49
Merton consumption-investment dynamics
50
Merton consumption-investment problem
T −t
!
𝛽 𝜌 1 ∑︁ 𝜌
E kT + c
𝜌 𝜌 t=0 t
51
Deterministic wealth dynamics
(1 − 𝜌) hTt Σht
kt+1 = kt − ct + yt + 𝜇T ht −
2 kt + vt
▶ vt is the present value of future labor income discounted at the risk-free rate 𝜇rf
T
∑︁−1
vt = y 𝜏 exp(−𝜇rf (𝜏 − t))
𝜏=t
52
Certainty equivalent convex optimization formulation
53
Certainty equivalent Merton problem in CVXPY
k = cp.Variable(T + 1)
h = cp.Variable((n, T))
c = cp.Variable(T, nonneg=True)
Sigma_half = np.linalg.cholesky(Sigma)
54
Example
▶ plan over 80 years (age 25–105), with initial wealth k0 = 10, 000 USD
▶ n = 5 assets, utility parameter 𝜌 = −4, bequest parameter 𝛽 = 10
▶ five asset classes, with long only portfolio constraint ht ≥ 0
▶ salary grows until age 50, then is constant, then drops to 50% at age 65
55
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
56
Alternative investments
57
Alternative investment dynamics
pt = 𝛾 call ut , dt = 𝛾 dist nt
58
Alternative investment planning
59
Alternative investment planning in CVXPY
tracking = cp.mean((n-n_des)**2)
smoothing = lmbda * cp.mean(cp.diff(c)**2)
60
Example
▶ T = 32 (eight years), rt = 0.04 (4% quarterly return), 𝛾 call = .23, 𝛾 dist = .15
▶ planning parameters: cmax = 4, umax = 10, ndes = 15, and 𝜆 = 5
61
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
62
Blending forecasts
K
∑︁
x̂t+1 = 𝜋tk x̂t+1
k
k=1
63
Blending forecasts using convex optimization
with variable 𝜋 ∈ RK
▶ ℓ is prediction loss, rsm penalizes weight change, rpri penalizes deviation from prior
▶ we assume ℓ, rsm , rpri are convex in 𝜋
▶ idea: use blending weights that would have worked well over the last M periods
64
Blending forecasts in CVXPY
pi = cp.Variable(K, nonneg=True)
x_hat = X_hat @ pi
65
Example
▶ predict log of daily trading volume of Apple, 1982–2024
▶ K = 3 predictors: 5-day (fast), 21-day (medium), and 63-day (slow) moving medians
▶ absolute loss ℓ(x̂ 𝜏 , x 𝜏 ) = |x̂ 𝜏 − x 𝜏 | ; M = 250 trading days
66
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
67
Bond price model
T
∑︁
p= ct exp(−t(yt + s)),
t=1
68
Matrix pricing problem
Ín 2
pi − Tt=1 ci,t exp(−t(yt + sri ))
Í
minimize i=1
subject to 0 ≤ s1 ≤ · · · ≤ sK
69
Matrix pricing in CVXPY
▶ use CVXPY to automatically linearize the exponential term as p current + Delta hat
▶ would add trust penalty to the iterates in practice
▶ code below computes first iteration
y = cp.Variable(T, value=y_init)
s = cp.Variable(K, value=S_init, nonneg=True)
a = cp.Variable(a.size, values=a_init)
70
Example
▶ consider n = 1000 bonds, with a maturity of up to 30 years
▶ bonds are rated AAA, AA, A, BBB, BB
▶ used data from 1990 to 2024 to fit basis functions, latest yields, and spread to price bonds
▶ fit yields and spreads to bond prices gives $0.03 RMSE (2.9 bps)
iteratively fitted yields for rating AAA rating spreads (vs. AAA)
71
Outline
Convex optimization
Markowitz portfolio construction
Maximum expected utility portfolio construction
Sparse inverse covariance estimation
Worst-case risk analysis
Option pricing
Currency exchange
Optimal execution
Optimal consumption
Alternative investment planning
Blending forecasts
Bond pricing
Model predictive control
72
Stochastic control
T −1
!
∑︁
J=E gt (xt , ut ) + gT (xT )
t=0
73
Solution via dynamic programming
74
Model predictive control
mpc
to evaluate 𝜋t (xt ) :
▶ forecast: predict stochastic future values wt , . . . , wT −1 as ŵt|t , . . . , ŵT −1|t
▶ plan: solve certainty equivalent problem assuming forecasts are correct
ÍT −1
minimize 𝜏=t gt (x̂ 𝜏 |t , ut ) + gT (x̂T |t )
subject to x̂ 𝜏+1|t = f (x 𝜏 |t , u 𝜏 |t , ŵ 𝜏 |t ), 𝜏 = t, . . . , T − 1, x̂t|t = xt
75
Model predictive control
▶ when f is linear in x, u and gt are convex, planning problem is convex, hence tractable
▶ MPC is optimal in a few special cases, but often performs extremely well
▶ used in many industries, e.g., guiding SpaceX’s Falcon first stages to their landings
[Blackmore, 2016]
76
Example: Order execution via MPC
▶ purchase 10 million Apple shares over 10 trading days (Feb 8–22, 2024)
▶ participation rate limit 𝜋 max = 5%
▶ forecasts:
– v̂ 𝜏 |t is 5-day trailing median of volumes, 𝜏 = t, . . . , T
– 𝜎𝜏 |t is 21-day trailing standard deviation, 𝜏 = t, . . . , T
▶ transaction cost is 1.881B USD for fixed schedule and 1.877B USD for MPC
▶ MPC saves us 4M USD, about 20 bps
77
Example: Order execution via MPC
78