duration = (1/P) ×(C1/(1+r) + 2C2/(1+r)2 + 3C3/(1+r)3 ⋅⋅⋅+ nCn/(1+r)n)
where P is the market price of the bond,
Cx is one of n payments (of interest and principal) and
r is the yield to maturity.
This formula assumes that payments are made at regular intervals.
The value of a bond is the present value of the interest payments and the repayment of the principal. As with any present value, increasing the time before a cashflow is received reduces its value. This means that the duration is a measure of the sensitivity of a bond price to interest rates. The modified duration is a more accurate measure.
Calculating the duration of a bond portfolio is easy as the duration of the portfolio is the sum of the durations of each security multiplied by the proportion of the portfolio in that security.
So if 75% of a portfolio is in a security with a duration of 8, and 25% is in a security with a duration of 12, then the duration of the portfolio is (8 × 0.75) + (12 × 0.25) = 9.