Skip to content

Instantly share code, notes, and snippets.

@druce
Created December 20, 2020 22:12
Show Gist options
  • Select an option

  • Save druce/e4092f210449bfecebd924405c1f1599 to your computer and use it in GitHub Desktop.

Select an option

Save druce/e4092f210449bfecebd924405c1f1599 to your computer and use it in GitHub Desktop.
po7.py
# number of stocks
n = 1000
# random historical mean returns for each stock
mu = np.random.normal(0.1, 0.2, n)
# number of factors
m = 10
# factor covariance matrix - random symmetrical matrix
SigmaFactor = np.random.randn(m, m)/4
SigmaFactor = SigmaFactor.T @ SigmaFactor
# factor loadings, determine volatility and covariances between stocks
F = np.random.randn(n, m)
# idiosyncratic risk of each stock
D = np.diag(np.random.uniform(0, 0.9, size=n))
ret = mu.T @ w # solve for weights that maximize portfolio return
f = F.T @ w # portfolio factor loading
Lmax = cp.Parameter() # leverage constraint
Lmax.value = 2
# portfolio volatility: factor risk + idiosyncratic risk
risk = cp.quad_form(f, SigmaFactor) + cp.quad_form(w, D)
prob = cp.Problem(cp.Minimize(risk),
[cp.sum(w) == 1,
cp.norm(w, 1) <= Lmax])
prob.solve(solver=cp.OSQP)
minvol = risk.value
minvolret = ret.value
print("Min vol portfolio (return=%.4f, risk=%.4f)" % (minvolret, minvol))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment