Quantitative Finance Stack Exchange is a question and answer site for finance professionals and academics. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

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)

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

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)

    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
share|improve this question
Hi Wade Bratz, welcome to Quant.SE! Thank you for asking your question here. – Bob Jansen Jul 19 '14 at 8:43

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.
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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