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:

  1. 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]
    
  2. The numbers you see are the coefficients of the polynomial. Extrapolate ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.