Immunization
As we saw, there is interest rate risk for bonds that we can measure with duration. The way to eliminate this risk is to get a portfolio where the total duration is equal to 0.
Let’s say we still have that bond with face value of 1000 from before, and we also have a bond with a price of 900 and duration of 6. What amount would we need to short to make our total portfolio have a duration of 0?
1*p1*d1-x*p2*d2 = 0 for this to happen, so let’s run the numbers to solve for x.
print((p1*d)/(900*6))
print((p1*d)/(6))
So if we allocate 0.4875188402851868 as much, or 438.76695625666815 we will hedge interest rate risk.
This is not perfect though, you would need to rebalance after changes, duration isn’t exact.
Source Code