# Modified or Macauley Duration in python

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

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

• 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 – Alejandro Serret Oct 13 '17 at 22:47

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

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