0

I'm trying to run the code below but I get a NameError when running the code. The issue is that q seems not to be defined but this should not be true.

class SimpleNamespace():
    pass

#Question 1 

#i)
#Defining the parameters using SimpleNameSpace. par = Parameters
par = SimpleNamespace()
par.y = 1 #assets
par.p = 0.2 #probability
par.theta = -2 #elasticity 

#Defining utility function for agent
def utility(z,par):
    return (z**(1+par.theta))/(1+par.theta)

#Defining premium
def premium(q,par):
    return par.p*q

#Defining expected value
#Note that z_1, z_2 represents first and second part of the objective function - just in a compressed version
def exp_value (i,q,par):
    z_1 = par.y-i+q-premium(q,par)
    z_2 = par.y-premium(q,par)
    return par.p*utility(z_1,par)+(1-par.p)*utility(z_2,par)

def opt_q(i,q,par):
    obj = lambda q: -exp_value(i,q,par) #defining the objective function
    solution = optimize.minimize_scalar(obj, bounds=(0,0.9), method="bounded") #bounded solution within [0.01, 0.9] 
    q = solution.x 
    return q

for i in np.linspace(0.01,0.9,num=100):
    res = opt_q(i,q,par)
    print(res)
1
  • Can you also include the whole traceback of error Commented Mar 21, 2022 at 10:23

1 Answer 1

1

You are getting the NameError because you are not passing the q to opt_q in the last for-loop. Since it is already defined inside opt_q just remove q from its arguments and don't pass it in the for-loop as well as follows:

def opt_q(i,par):
    obj = lambda q: -exp_value(i,q,par) #defining the objective function
    solution = minimize_scalar(obj, bounds=(0,0.9), method="bounded") #bounded solution within [0.01, 0.9]
    q = solution.x
    return q

for i in np.linspace(0.01,0.9,num=100):
    res = opt_q(i,par)
    print(res)

This resolves your issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.