I wrote a small utility function to calculate the weights of a maximum sharpe portfolio given the covariance matrix and expected returns. Thought I share it with community. source stackoverflow
def max_sharpe(cov, expected_returns):
n = len(expected_returns)
onesT = np.ones((n,1)).T
covis = np.linalg.inv(cov)
p1 = np.dot(onesT, covis)
p1 = np.dot(p1, expected_returns)
p2 = np.dot(covis, expected_returns)
w = p2 / p1
return np.ravel(w) / np.sum(np.abs(w))