Skip to content

Instantly share code, notes, and snippets.

@micycle1
Created October 10, 2023 16:33
Show Gist options
  • Save micycle1/4e1a42eed42311543fd70653584bb0e9 to your computer and use it in GitHub Desktop.
Save micycle1/4e1a42eed42311543fd70653584bb0e9 to your computer and use it in GitHub Desktop.
Bond duration, convexity and return
def modified_duration(y, m):
"""
Approximates the modified duration of a risk-free bond at par value.
:param y: Yield-to-maturity in decimal terms
:param m: Maturity in years
:return: Modified duration of a risk-free bond
"""
return (1-(1/(1+0.5*y)**(2*m)))/(y)
def convexity(y, m):
"""
Approximates the convexity of a par bond.
:param y: Yield-to-maturity in decimal terms
:param m: Remaining maturity in years
:return: The convexity of a bond
"""
return (2/(y**2))*(1-(1/(1+0.5*y)**(2*m)))-(2*m)/((y)*(1+0.5*y)**(2*m+1))
def bond_return(y, m, prev_y, mod_dur, convexity, months=1):
"""
Calculates the return on a bond.
:param y: Current yield (t)
:param m: Maturity in years
:param prev_y: Previous yield (t-1)
:param mod_dur: Modified duration
:param convexity: Convexity of bond
:param months: Number of months between current yield and previous yield, default is 1
:return: Return on bond
"""
return -mod_dur*(y-prev_y)+0.5*convexity*(y-prev_y)**2+((1+prev_y)**(months/12)-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment