Python for Finance: Analyze Big Financial Data

(Elle) #1
def Eu((s,  b)):
return -(0.5 * sqrt(s * 15 + b * 5 ) + 0.5 * sqrt(s * 5 + b * 12 ))

#   constraints
cons = ({‘type’: ‘ineq’, ‘fun’: lambda (s, b): 100 - s * 10 - b * 10 })
# budget constraint
bnds = (( 0 , 1000 ), ( 0 , 1000 )) # uppper bounds large enough

We have everything we need to use the minimize function — we just have to add an initial


guess for the optimal parameters:


In  [ 66 ]: result  =   spo.minimize(Eu,    [ 5 ,    5 ],   method=‘SLSQP’,
bounds=bnds, constraints=cons)
In [ 67 ]: result
Out[67]: status: 0
success: True
njev: 5
nfev: 21
fun: -9.700883611487832
x: array([ 8.02547122, 1.97452878])
message: ‘Optimization terminated successfully.’
jac: array([-0.48508096, -0.48489535, 0. ])
nit: 5

The function returns a dict object. The optimal parameters can be read out as follows:


In  [ 68 ]: result[‘x’]
Out[68]: array([ 8.02547122, 1.97452878])

The optimal function value is (changing the sign again):


In  [ 69 ]: -result[‘fun’]
Out[69]: 9.700883611487832

Given the parameterization for the simple model, it is optimal for the investor to buy about


eight units of security a and about two units of security b. The budget constraint is


binding; i.e., the investor invests his/her total wealth of 100 USD into the securities. This


is easily verified through taking the dot product of the optimal parameter vector and the


price vector:


In  [ 70 ]: np.dot(result[‘x’], [ 10 ,   10 ])
Out[70]: 99.999999999999986
Free download pdf