Python for Finance: Analyze Big Financial Data

(Elle) #1

Since we do not have a closed formula for the efficient frontier or the first derivative of it,


we have to solve the system of equations in Equation 11-4 numerically. To this end, we


define a Python function that returns the values of all three equations given the parameter


set p = (a,b,x):


In  [ 70 ]: def equations(p,    rf=0.01):
eq1 = rf - p[ 0 ]
eq2 = rf + p[ 1 ] * p[ 2 ] - f(p[ 2 ])
eq3 = p[ 1 ] - df(p[ 2 ])
return eq1, eq2, eq3

The function fsolve from scipy.optimize is capable of solving such a system of


equations. We provide an initial parameterization in addition to the function equations.


Note that success or failure of the optimization might depend on the initial


parameterization, which therefore has to be chosen carefully — generally by a


combination of educated guesses with trial and error:


In  [ 71 ]: opt =   sco.fsolve(equations,   [0.01,  0.5,    0.15])

The numerical optimization yields the following values. As desired, we have a = rf = 0.01:


In  [ 72 ]: opt
Out[72]: array([ 0.01 , 1.01498858, 0.22580367])

The three equations are also, as desired, zero:


In  [ 73 ]: np.round(equations(opt),     6 )
Out[73]: array([ 0., -0., -0.])

Figure 11-14 presents the results graphically: the star represents the optimal portfolio from


the efficient frontier where the tangent line passes through the riskless asset point (0,rf =


0.01). The optimal portfolio has an expected volatility of 20.5% and an expected return of


17.6%. The plot is generated with the following code:


In  [ 74 ]: plt.figure(figsize=( 8 ,     4 ))
plt.scatter(pvols, prets,
c=(prets - 0.01) / pvols, marker=‘o’)
# random portfolio composition
plt.plot(evols, erets, ‘g’, lw=4.0)
# efficient frontier
cx = np.linspace(0.0, 0.3)
plt.plot(cx, opt[ 0 ] + opt[ 1 ] * cx, lw=1.5)
# capital market line
plt.plot(opt[ 2 ], f(opt[ 2 ]), ‘r*’, markersize=15.0)
Free download pdf