Time for action – fitting to polynomials
The NumPy polyfit()
function fits a set of data points to a polynomial, even if the underlying function is not continuous:
- Continuing with the price data of BHP and VALE, look at the difference of their close prices and fit it to a polynomial of the third power:
bhp=np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True) vale=np.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True) t = np.arange(len(bhp)) poly = np.polyfit(t, bhp - vale, 3) print("Polynomial fit", poly)
The polynomial fit (in this example, a cubic polynomial was chosen) is as follows:
Polynomial fit [ 1.11655581e-03 -5.28581762e-02 5.80684638e-01 5.79791202e+01]
- The numbers you see are the coefficients of the polynomial. Extrapolate to the next value with the
polyval()
function and the polynomial object that we got from the fit:print("Next value", np.polyval(poly, t[-1] + 1))
The next value we predict...