简体   繁体   中英

Python : How to interpolate the missing rates and plot the interpolated curve to compare the original curve?

data = {'tenor_yrs': [.1, .2, .3, .5, 1, 3, 5, 10, 15, 20, 25, 30,40,50], 'rates': [NaN, NaN, NaN, NaN, 2.01, 3, 1.99, 2.05, 3.19, 1.99, 3.16, 2.54, 3.5, 2.79]}

df = pd.DataFrame(data)

Please suggest how to interpolate the missing years rates in python to build this curve with linear interpolation and plot the same. The number in decimals in tenor are months.

You can set tenor_years as the index, reindex and interpolate to fill the missing values with a linear interpolation:

(df.set_index('tenor_yrs')
   .reindex(range(int(df.tenor_yrs.max())))
   .interpolate()
   .reset_index())

   tenor_yrs  rates
0          0    NaN
1          1  2.010
2          2  2.505
3          3  3.000
4          4  2.495
5          5  1.990
6          6  1.990
7          7  1.990
8          8  1.990
...

Update -

To include decimal places as steps, use:

start = int(df.tenor_yrs.min())
end = int(df.tenor_yrs.max())
step = df.loc[df.tenor_yrs>0, 'tenor_yrs'].min()

import numpy as np

(df.set_index('tenor_yrs')
   .reindex(np.arange(start, end, step))
   .interpolate()
   .reset_index())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM