Time for action – fitting to polynomials
The NumPy polyfit
function can fit 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, let's 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, int(sys.argv[1])) print "Polynomial fit", poly
The polynomial fit (in this example, a cubic polynomial was chosen):
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 we got from the fit:print "Next value", np.polyval(poly, t[-1] + 1)
The next value we predict will be:
Next value 57.9743076081
Ideally, the difference between...