Home > Software design >  Missing arguments in a nested function
Missing arguments in a nested function

Time:09-17

I follow a python course on finance about portfolio theory. I have to create a function with a nested function in it.

My problem is I have a error message of "neg_sharpe_ratio() missing 2 required positional arguments: 'er' and 'cov'" whereas to my mind 'er' and 'cov' are already defined in my function msr below. So I understand how they are missing.

from scipy.optimize import minimize
def msr(riskfree_rate, er, cov):
    
    n= er.shape[0]
    init_guess= np.repeat(1/n, n)
    bounds=((0.00, 1.0),)*n
    weights_sum_to_1 = {
        'type' :'eq' , #
        'fun' : lambda weights: np.sum(weights) - 1 ## 
    } 
    def neg_sharpe_ratio(weights,riskfree_rate, er, cov):
        r = erk.portfolio_return(weights, er)
        vol = erk.portfolio_vol(weights,cov)
        return -(r-riskfree_rate)/vol

    results = minimize( neg_sharpe_ratio, init_guess, 
                args=(cov,), method="SLSQP", 
                options={'disp': False},
                constraints=( weights_sum_to_1),
                bounds=bounds
                      )
    return results.x

TypeError: neg_sharpe_ratio() missing 2 required positional arguments: 'er' and 'cov'

CodePudding user response:

The function neg_sharpe_ratio is able to reference any of the variables passed in and made by the function msr without needing those same variables passed into it itself. Therefore you should be able to remove the paramters riskfree_rate, er, and cov from the neq_sharpe_ratio function definition and have it work, as those variables are passed into its parent function, leaving you with: def neg_sharpe_ratio(weights):

CodePudding user response:

For those who might be interested, I find my mistake.. Indeed, I forgot to define correctly the arguments of my function neg_share_ratio in my function minimize.

Here is the code amended:

from scipy.optimize import minimize def msr(riskfree_rate, er, cov):

n= er.shape[0]
init_guess= np.repeat(1/n, n)
bounds=((0.00, 1.0),)*n
weights_sum_to_1 = {
    'type' :'eq' , #
    'fun' : lambda weights: np.sum(weights) - 1 ## 
} 
def neg_sharpe_ratio(weights,riskfree_rate, er, cov):
    r = erk.portfolio_return(weights, er)
    vol = erk.portfolio_vol(weights,cov)
    return -(r-riskfree_rate)/vol

results = minimize( neg_sharpe_ratio, init_guess, 
            args=(weights,riskfree_rate,er,cov), method="SLSQP", 
            options={'disp': False},
            constraints=( weights_sum_to_1),
            bounds=bounds
                  )
return results.x code here
  • Related