-4
$\begingroup$

are there any existing python modules that can calculate Modified and/or Macauley Duration of a bond.

$\endgroup$
2
$\begingroup$

I calculate duration in Python using numpy, it's nice and simple:

def durations(cfs, rates, price, ytm, no_coupons):
    import numpy as np 
    mac_dur = np.sum([cfs[i]*(i+1)/np.power(1+rates[i],i+1) for i in range(len(cfs))])/price
    mod_dur = mac_dur/(1+ytm/no_coupons)
    return mac_dur, mod_dur
$\endgroup$
  • $\begingroup$ You have an error in your calculation your range function should start in 1 but because you are iterating in an array this will cause index out of range, when you say cfs[i]*i should be * (i+1) because the first i is 0 and you are loosing then the first number the same in your power method $\endgroup$ – Alejandro Serret Oct 13 '17 at 22:47
1
$\begingroup$

Go talk to Fincad. Here is their page on integrating with scripting languages:

http://www.fincad.com/news-events/assets/pdfs/mar07/using-fincad-developer-scripting-languages.pdf

Their analytics libraries include bond analytics, and they have a spreadsheet product so you can test methods and results before implementing them.

Disclaimer: I work for a company who is a customer of Fincad's analytics.

$\endgroup$
1
$\begingroup$
You can use my script:

def Duration (timetomaturity,nominalvalue,yieldrate,couponrate):
import math as m
yld=yieldrate/100
cpnr=couponrate/100
t=list(range(1,timetomaturity+1))
cfi=nominalvalue*cpnr
cfN=nominalvalue*cpnr+nominalvalue
cfl=[cfi]*(len(t)-1)+[cfN]
B=0 # B is the bond's present value
for k in range(0,timetomaturity):
B=B+cfl[k]*(m.exp(-yld*t[k]))
D=0 # D is the duration
for i in range(0,timetomaturity):
D+=(t[i]*cfl[i]*m.exp(-yld*t[i]))/B
return round(D,2),round(B,2)

#Duration(5,100,1,1)
#By Tural Valiyev
$\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.