Created
December 20, 2020 22:06
-
-
Save druce/54e95eae7fd5b499fb1549013c430329 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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