Before discussing how to generate an optimal portfolio, it is necessary to study a few optimization functions. In the following example, we minimize our objective function of y:
First, let's look at the graph of this objective function, see the following code:
import scipy as sp import matplotlib.pyplot as plt x=sp.arange(-5,5,0.01) a=3.2 b=5.0 y=a+b*x**2 plt.plot(x,y) plt.title("y= "+str(a)+"+"+str(b)+"x^2") plt.ylabel("y") plt.xlabel("x") plt.show()
The graph is shown here:
To make the program more general, two coefficients of a
and b
are generated. Apparently, since the power of x
is 2, y
is minimized only when x
is 0. The Python code for minimization is as follows:
from scipy.optimize import minimize def myFunction(x): return (3.2+5*x**2) x0=100 res = minimize(myFunction,x0,method='nelder-mead',options={'xtol':1e-8,'disp': True})
In the preceding program, the major function used is called the scipy.optimize.minimize()
function. The first input is our objective...