Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

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 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 will be this:

    Next value 57.9743076081
    
  3. Ideally, the difference...