Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save druce/54e95eae7fd5b499fb1549013c430329 to your computer and use it in GitHub Desktop.
import cvxpy as cp
# compute covariance matrix (df being the dataframe of historical returns)
Sigma = np.cov(df.transpose())
# number of assets
n = Sigma.shape[0]
# average returns
mu = df.mean().values
# asset SDs
asset_vols = np.sqrt(Sigma.diagonal())
# variable to optimize over - portfolio weights
w = cp.Variable(n)
# objectives to optimize
# portfolio return
ret = mu.T @ w
# volatility
vol = cp.quad_form(w, Sigma)
prob = cp.Problem(cp.Minimize(vol), # minimize volatility
[cp.sum(w) == 1, # sum of weights = 1
w >= 0] # weights > 0 (long-only)
)
prob.solve()
wts = [float('%0.4f' % v) for v in w.value]
minvol = vol.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment