Adding a weight constraint to Max Sharpe Ratio function in python

*爱你&永不变心* 提交于 2021-01-29 07:33:10

问题


I have the following formula to calculate Max Sharpe Ratio for a given set of returns:

def msr(riskfree_rate, er, cov):
"""
Returns the weights of the portfolio that gives you the maximum sharpe ratio
given the riskfree rate and expected returns and a covariance matrix
"""
n = er.shape[0]
init_guess = np.repeat(1/n, n)
bounds = ((0.0, 1.0),) * n # an N-tuple of 2-tuples!
# construct the constraints
weights_sum_to_1 = {'type': 'eq',
                    'fun': lambda weights: np.sum(weights) - 1
}
def neg_sharpe(weights, riskfree_rate, er, cov):
    """
    Returns the negative of the sharpe ratio
    of the given portfolio
    """
    r = portfolio_return(weights, er)
    vol = portfolio_vol(weights, cov)
    return -(r - riskfree_rate)/vol

weights = minimize(neg_sharpe, init_guess,
                   args=(riskfree_rate, er, cov), method='SLSQP',
                   options={'disp': False},
                   constraints=(weights_sum_to_1,),
                   bounds=bounds)
return weights.x

Modifying functions like this is way above my skill level, so I was hoping somebody here might be able to advise on the following. The given formula takes a set of returns as a base:

        Food    Beer    Smoke   Games
1926-07 0.86    -5.36   1.67    2.31
1926-08 3.7     19.25   5.01    2.53
1926-09 1.38    5.63    3.1     4.13
1926-10 -4.7    -6.08   -1.63   -5.76

I want it to take one more argument - weight matrix of 0 and 1 where 0 means that company should be excluded from the portfolio in a given month, whereas the rest of the weights should be distributed as per msr function.

Weight matrix example is below, meaning in 1926-08 "Smoke" weight should be zero, in 1926-09 and 1926-10 "Games" weight should be zero:

        Food    Beer    Smoke   Games
1926-07 1       1       1       1
1926-08 1       1       0       1
1926-09 1       1       1       0
1926-10 1       1       1       0

Could somebody suggest how I can incorporate this into the above function? Thank you in advance!

来源:https://stackoverflow.com/questions/64958844/adding-a-weight-constraint-to-max-sharpe-ratio-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!