Book Image

Python for Finance

By : Yuxing Yan
Book Image

Python for Finance

By: Yuxing Yan

Overview of this book

Table of Contents (20 chapters)
Python for Finance
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Interpolation in SciPy


In the following code example, x can be viewed as the x axis with a set of values from 0 to 10, while the vertical axis is y, where y = exp(-x/3). We intend to interpolate between different y(i) values by applying two methods: linear and cubic. The following lines of code are an example from SciPy Reference Guide:

>>>import numpy as np
>>>import matplotlib.pyplot as plt
>>>from scipy.interpolate import interp1d
>>>x = np.linspace(0, 10, 10)
>>>y = np.exp(-x/3.0)
>>>f = interp1d(x, y)
>>>f2 = interp1d(x, y, kind='cubic')
>>>xnew = np.linspace(0, 10, 40)
>>>plt.plot(x,y,'o',xnew,f(xnew),'-', xnew, f2(xnew),'--')
>>>plt.legend(['data', 'linear', 'cubic'], loc='best')
>>>plt.show()

In the preceding program, we use the np.linspace() function to generate evenly spaced numbers—40 values—over a specified interval, from 0 to 10 in this case. The related output is shown as follows...