1
$\begingroup$

I want to run the newton method on a large dataset to calculate bond yield. Below is the code I created using a loop. I need to run it on ~50 million lines and the loop is quite unwieldy. Is there a more efficient way to run it using Pandas/Numpy/ect?

In:
from pandas import *
from pylab import *
import pandas as pd
import pylab as plt
import numpy as np
from scipy import *
import scipy

df = DataFrame(list([100,2,34.1556,9,105,-100]))
df = DataFrame.transpose(df)
df = df.rename(columns={0:'Face',1:'Freq',2:'N',3:'C',4:'Mkt_Price',5:'Yield'})
df2= df
df = concat([df, df2])
df = df.reset_index(drop=True)
df

Out:
    Face    Freq    N        C Mkt_Price  Yield
0    100     2   34.1556     9   105    -100
1    100     2   34.1556     9   105    -100

In:
def Px(Rate):
    return Mkt_Price - (Face * ( 1 + Rate / Freq ) ** ( - N ) + ( C / Rate ) * ( 1 - (1 + ( Rate / Freq )) ** -N ) )

for count, row in df.iterrows():
        Face = row['Face']
        Freq = row['Freq']
        N = row['N']
        C = row['C']
        Mkt_Price = row['Mkt_Price']
        row['Yield'] = scipy.optimize.newton(Px, .1, tol=.0001, maxiter=100)
df

Out:
    Face    Freq   N         C  Mkt_Price   Yield
0    100     2   34.1556     9   105       0.084419
1    100     2   34.1556     9   105       0.084419
$\endgroup$
  • $\begingroup$ Hi Wade Bratz, welcome to Quant.SE! Thank you for asking your question here. $\endgroup$ – Bob Jansen Jul 19 '14 at 8:43
1
$\begingroup$

As far as I know the Newton method is the preferred method for yield calculation.

Two ideas to optimize the loop spring to mind:

  1. Run the loop in parallel.
  2. Use the last yield as starting value. If you have a good guess the number of iterations necessary per optimization is reduced significantly. How to get the most out of the previously calculated yield depends on the structure of your data. If comparable bonds are close in your data set this should work. If this is not the case you could do a stable sort on the attributes so similar bonds will be grouped together.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.