Financial Algorithms Cookbook

Error: Failed to load processor TOC
No macro named [[TOC]] found

Time Value Of Money

Interest

Typical Uses

  • todo

Ingredients

  • todo

Algorithm

def derivative(i, PV, FV, PMT, n, inAdv=False, continious=False):
    nFractionPart,nIntegerPart  = modf(n)
    discount = pow(1.0+i, -nIntegerPart)
    if inAdv:
        PMT *=(1.0+i)
    if continious:
        pvs =pow((1.0+i),nFractionPart) 
    else:
        pvs =(1.0+ i*nFractionPart)
    return PV + ( PMT*((1-discount)/i) + FV*discount)/pvs

def interestRate(estimate, PV, FV, PMT, n, inAdv=False, continous=False):
   stop = PV
   return  100* newton_raphson(derivative,  estimate, PV, FV, PMT, n)

Example

You want to save for your childs collage bills estimated to be 100,000. She will graduate form high school in 8 years time. What annual interest rate will you need to achieve this amount on an investment of 60,000 with quarterly compounding?

FV= 100000
PV=-60000
PMT=0
n=8*4
estimate = 1.2/n
interestRate(estimate/100, PV, FV, n)
>> 1.61

So the annual interest rate is 6.44

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Number of Compounding Periods

Typical Uses

  • To determine the number of periods required for an initial investment to grow to a specified amount
  • To determine the number of periods it will take to repay a loan.

Ingredients

To calculate the number of compounding periods you will need the following:

  • Present value: The value of the load or investment.
  • Periodic Interest rate: This is the interest rate in terms of the basic compounding period, which may be years, months, days, or any other time period. For example, an annual rate of 6% compounded quarterly would be 6*0.25, 1.5%.
  • Periodic Payment. For simple investments, this could be zero.
  • Future Value: Which in a loan that is paid out completely would be zero, otherwise it could be the final balloon payment. For an investment, this would be the final returned value.
  • Payment Mode: Weather in the payments are done in advance, at the beginning of the compounding period, or in arrears, at the end of the compounding period.

Algorithm

def  numberCompoundingPeriods(i, PV, PMT, FV, inAdv=False):
  i /= 100.0
  spmt = -PMT/i
  if inAdv:
    spmt *= (1.0+i)
  c = spmt – FV
  u = (spmt+PV)/c
  n = log(1.0/u)/log(1.0+i)
  return ceil(n)

Example

You are planning to build an extension for your house. You will need $350,000. The current interest rate for a credit line is 13% but your best friend offers you the loan at 10.5%. You agreed to make $3250 dollar payments at the end of each month, how many payments will be required to pay off this loan?

numberCompundingPeriods(10.5/12, 350000, 3250, 0, false)
>> 328.00

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • Kieso, D; Weygandt, Jerry, Intermediate Accounting, 9th Ed., New York, NY:John Wiley & Sons, Inc., 1993
  • BA II Plus Guidebook, Texas Instruments, Inc., 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Annuity Payments

Typical Usage

Payments in Time Value of Money formulas are a series of equal, evenly-spaced cash flows of an annuity such as payments for a mortgage or monthly receipts from a retirement account.

Payments must:

  • be the same amount each period
  • occur at evenly spaced intervals
  • occur exactly at the beginning or end of each period
  • be all inflows or all outflows (payments or receipts)
  • represent the payment during one compounding (or discount) period

Calculate Payments When Present Value Is Known

The Present Value is an amount that you have now, such as the price of property that you have just purchased or the value of equipment that you have leased. When you know the present value, interest rate, and number of periods of an ordinary annuity, you can solve for the payment with this formula:

PMT = PV  /  [(1- (1 / (1 + i)n )) / i]

Where:

  • PV = Present Value of an ordinary annuity (payments are made at the end of each period)
  • i = interest per period
  • n = number of periods

Calculate Payments When Future Value Is Known

The Future Value is an amount that you wish to have after a number of periods have passed. For example, you may need to accumulate $20,000 in ten years to pay for college tuition. When you know the future value, interest rate, and number of periods of an ordinary annuity, you can solve for the payment with this formula:

PMT = FV  /  [((1 + i)n - 1 )  /  i]

Where:

  • FV = Future Value of an ordinary annuity (payments are made at the end of each period)
  • i = interest per period
  • n = number of periods

General Formula To Calculate Payments

0 = PV (1 + i)fractionalPart(n) + (1+iS)PMT[(1-(1+i)-integerPart(n)/i] + FV(1 + i)-integerPart(n)

Where:

  • PV = Present Value of an ordinary annuity (payments are made at the end of each period)
  • FV = Future Value of an ordinary annuity (payments are made at the end of each period)
  • i = interest per period
  • n = number of periods
  • S = True when payments are made in advance.

Ingredients

  • TODO

Algorithm

def paymentAmount(i, PV, FV, n, inAdv=False, continious=False):
    i /= 100.0
    nFractionPart,nIntegerPart  = modf(n)   
    discount = pow(1.0+i, -nIntegerPart)
    if inAdv:
        PMT =1/(1.0+i)
    else:
        PMT =1.0
        
    if continious:
        pvs =pow((1.0+i),nFractionPart) 
    else:
        pvs =(1.0+ i*nFractionPart)
    PMT = -PMT*(FV*discount + PV*pvs)*(i/(1-discount))
    return PMT

Example

You want to save for your retirement 600,000. This will be in 15 years. You open a retirement account with a deposit of 32,000 that pays 9.75 compounded semiannually. You plan to make semiannual deposits starting six months later. What their value be?

FV= 600000
PV -32000
n= 15*2
i = 9.75/2.0
paymentAmount(i, PV, FV, n)
>>-7174.4 

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Future Value

Typical Uses

  • TODO

Future Value Of A Single Amount

Future Value is the amount of money that an investment made today (the present value) will grow to by some future date. Since money has time value, we naturally expect the future value to be greater than the present value. The difference between the two depends on the number of compounding periods involved and the going interest rate.

The relationship between the future value and present value can be expressed as:

FV = PV (1 + i)n

Where:

  • FV = Future Value
  • PV = Present Value
  • i = Interest Rate Per Period
  • n = Number of Compounding Periods

Future Value of Annuities

An annuity is a series of equal payments or receipts that occur at evenly spaced intervals. Leases and rental payments are examples. The payments or receipts occur at the end of each period for an ordinary annuity while they occur at the beginning of each period.for an annuity due. Future Value of an Ordinary Annuity

The Future Value of an Ordinary Annuity (FVoa) is the value that a stream of expected or promised future payments will grow to after a given number of periods at a specific compounded interest.

The Future Value of an Ordinary Annuity could be solved by calculating the future value of each individual payment in the series using the future value formula and then summing the results. A more direct formula is:

FVoa = PMT [((1 + i)n - 1) / i]

Where:

  • FVoa = Future Value of an Ordinary Annuity
  • PMT = Amount of each payment
  • i = Interest Rate Per Period
  • n = Number of Periods

Future Value of an Annuity Due (FVad)

The Future Value of an Annuity Due is identical to an ordinary annuity except that each payment occurs at the beginning of a period rather than at the end. Since each payment occurs one period earlier, we can calculate the present value of an ordinary annuity and then multiply the result by (1 + i).

FVad = FVoa (1+i)

Where:

  • FVad = Future Value of an Annuity Due
  • FVoa = Future Value of an Ordinary Annuity
  • i = Interest Rate Per Period

Ingredients

  • TODO

Putting it all togeather gives us the below algorithm.

Algorithm

def  futureValue(i, PV, PMT, n, inAdv=False, continous=False):
  i /= 100.0
  nFractionPart,nIntegerPart  = modf(n)
  discount = pow(1.0+i, -nIntegerPart)
  if continous:
    pvs =pow((1.0+i),nFractionPart) 
  else:
    pvs =(1.0+ i*nFractionPart) 
  if inAdv:
    PMT *=(1.0+i)
  fv = -(PMT *((1.0-discount)/i)+PV*pvs)/(discount)
  return fv

Example

You are saving 500 a month (at the beginning of each month) into a new deposit account that pays 6.25 annual interest compounded monthly. How much will you have after 2 years?

PV=0
PMT = -500
n= 2*12
i = 6.35/12.0
futureValue(i, PV, PMT, n, inAdv=True)
>>12826.91

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Present Value

Typical Uses

  • TODO

Present Value Of A Single Amount

Present Value is an amount today that is equivalent to a future payment, or series of payments, that has been discounted by an appropriate interest rate. Since money has time value, the present value of a promised future amount is worth less the longer you have to wait to receive it. The difference between the two depends on the number of compounding periods involved and the interest (discount) rate.

The relationship between the present value and future value can be expressed as:

PV = FV [ 1 / (1 + i)n ]

Where:

  • PV = Present Value
  • FV = Future Value
  • i = Interest Rate Per Period
  • n = Number of Compounding Periods

Present Value of Annuities

An annuity is a series of equal payments or receipts that occur at evenly spaced intervals. Leases and rental payments are examples. The payments or receipts occur at the end of each period for an ordinary annuity while they occur at the beginning of each period.for an annuity due. Present Value of an Ordinary Annuity

The Present Value of an Ordinary Annuity (PVoa) is the value of a stream of expected or promised future payments that have been discounted to a single equivalent value today. It is extremely useful for comparing two separate cash flows that differ in some way.

PV-oa can also be thought of as the amount you must invest today at a specific interest rate so that when you withdraw an equal amount each period, the original principal and all accumulated interest will be completely exhausted at the end of the annuity.

The Present Value of an Ordinary Annuity could be solved by calculating the present value of each payment in the series using the present value formula and then summing the results. A more direct formula is:

PV = PMT [(1 - (1 / (1 + i)n)) / i]

Where:

  • PV = Present Value of an Ordinary Annuity
  • PMT = Amount of each payment
  • i = Discount Rate Per Period
  • n = Number of Periods

Present Value of an Annuity Due (PVad)

The Present Value of an Annuity Due is identical to an ordinary annuity except that each payment occurs at the beginning of a period rather than at the end. Since each payment occurs one period earlier, we can calculate the present value of an ordinary annuity and then multiply the result by (1 + i).

PVad = PV (1+i)

Where:

  • PVad = Present Value of an Annuity Due
  • PV = Present Value of an Ordinary Annuity
  • i = Discount Rate Per Period

Ingredients

  • TODO

Putting it all togeather gives us the below algorithm.

Algorithm

def  presentValue(i, FV, PMT, n, inAdv=False, continous=False):
    i /= 100.0
    nFractionPart,nIntegerPart  = modf(n)
    discount = pow(1.0+i, -nIntegerPart)
    if inAdv:
        SPMT *=(1.0+i)
    else:
        SPMT =1.0
    if continous:
        pvs =pow((1.0+i),nFractionPart) 
    else:
        pvs =(1.0+ i*nFractionPart)
    PV = (-PMT/((i/(1-discount))*SPMT)-FV*discount)/pvs
    return PV

Example

You want a boat whose price is 50,000. You found financing with help of a loan shark that wants 15%. The deal requires you to make a down payment of 15,000 and monthly payments of 1500 over four years. What is the real price of this boat?

FV= 0
PMT = -1500
n= 4*12
i = 15.0/12.0
presentValue(i, FV, PMT, n) + 15000
>>68897.22

So the real cost of this boat will be 68897.20.

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Cash Flow Algorithms

Cash flow analysis is an extension of the basic TVM concepts applied to compound interest problems when payments occur in regular periods and do not have the same value. Any financial investment can be represented as an initial investment of money and a series of cash flows that occur in regular periods of time. Each flow of money can be positive (received) or negative (paid out) and considered as a cash flow. Common cash flow problems usually involve the calculation of the Internal Rate of Return (IRR) or the Net Present Value (NPV).

Present Value Of a Series of Cashflows

Typical Uses

  • TODO

Ingredients

  • TODO

The PV expresses the summation of t the present value of each anticipated cash flow calculated to the time it occured. Hence

http://finance.bi.no/~bernt/gcc_prog/recipes/recipes/img20.png

Where:

  • Ct is the cashflow at time t.
  • Pt is the price one would pay today for the right to recive one dollar at a future date t.

Obtaining the value of Pt is not always practicle. A typical solution is to use a flat term structure, that is calculate the cash flows based on one interest rate from the time of the initial investment, the Discount Factor:

http://finance.bi.no/~bernt/gcc_prog/recipes/recipes/img23.png

So the Present Value is:

http://finance.bi.no/~bernt/gcc_prog/recipes/recipes/img24.png

To work out the Net Present Value, all you have to do is include the initial investment as cashflow C0.

Putting it all togeather gives us the below algorithm.

Algorithm

def  cashFlowPV(i, cashFlows):
    discountFactor = 1+i/100.0
    Pt = 1.0
    pv =cashFlows[0]
    for Ct in cashFlows[1:]:
        Pt *=  discountFactor 
        pv += Ct/Pt
    return pv

Example

You want to invest in development project that will return over 15%. You find a building that will cost 3.7 million, and will take a year to convert into appartments costing 1.2m. You would like to rent it for four years before selling it at 9.2 million.

C0C1C2C3C4C5C6
PurchaseRefurbish costsNet RentNet RentNet RentNet RentSold
3.7m1.2m300k315k330K347k9.2m
cashflows = [-3700000,-1200000,300000,315000,330000,347000,9200000]
i = 15
cashFlowPV(i, cashflows )
>>29,095.23

Thats good, but you now been offered by a friend a proposition of 15.8% for a similar investment.

i = 15.8
cashFlowPV(i, cashflows )
>>-144165.55

Clearly your friends investment is a better choice.

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Internal Rate of Return Of a Series of Cashflows

Typical Uses

  • TODO

Ingredients

  • TODO

Internal Rate of Return is the discount rate that if applied to all future cash flows causes NPV = 0.

http://finance.bi.no/~bernt/gcc_prog/recipes/recipes/img20.png

The algoithm uses Newton-Raphsons method for solving equations. It needs to take an estimate of the answer. Of course you could implement this algorithm with a sensible built in value.

Algorithm

def  IRR(estimate, cashFlows):
    def irr_f(estimate, cashFlows):
        t=0
        irr=0.0
        discountFactor = 1.0
        irr_i = estimate+1
        for Ct in cashFlows[1:]:
            irr += Ct *(1.0/discountFactor)
            discountFactor *= irr_i
        irr *= (1-(1/irr_i))/estimate
        irr += cashFlows[0]
        return irr
    return newton_raphson(irr_f, estimate, cashFlows)

Example

You want to invest in development project that will return over 15%. You find a building that will cost 3.7 million, and will take will a year to to convert into appartments costing 12m. You would like to rent it for four years before selling it at 9.2 million. What is this investments Internal Rate of Return ?

C0C1C2C3C4C5C6
PurchaseRefurbish costsNet RentNet RentNet RentNet RentSold
3.7m1.2300k315k330K347k9.2
cashflows = [-3700000,-1200000,300000,315000,330000,347000,9200000]
estimate = 10
IRR(estimate, cashflows )
>>15.13

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Modified Internal Rate of Return

Typical Uses

The traditional IRR has the following problems:

  • It assumes that all the cash flows are reinvested or discounted at the computed yield rate. This is only releistic if the spread between reinvested and borrowing is narrow.
  • It is sensitive to the number of times the sign of the cash flow changes. For each change from positive to negative or visa versa there is a possible extra solution. This solution is mathematically correct, but of not much finacial use.

MIRR avoids both these problems by discounting the negative and positive cash flows seperately and using differnet reinvestment and borrowing rates. Typically negative cash flows are discounted at a safe rate such as the T_Bill or Overnight rate. While positive cash flows are reinvested at a rate that reflects the a risk similar to the investment in question.

Ingredients

  • TODO

Algorithm

#Algorithm:
#
#1. Find FV of the positive cash flows at the reinvestment rate.
#2. Find PV of the negative cash flows at the safe rate.
# having PV, FV, and n solve for i.

def  MIRR(safeRate, reinvestmentRate, cashFlows):
    poscf =[]
    negcf =[]
    for cf in cashFlows:
        if cf > 0.0:
            poscf.append(cf)
            negcf.append(0.0)
        else:
            negcf.append(cf)
            poscf.append(0.0)    
    pv = NPV.netPresentValue(reinvestmentRate, poscf)
    pv = -pv
    n = len(cashFlows)-1
    NFV = FV.futureValue(reinvestmentRate, pv, 0, n)
    pv = NPV.netPresentValue(safeRate, negcf)
    return i.interestRate(safeRate/100, pv, NFV, 0, n)

Example

Using the follwoing cash flows:

Group # of Months Cash Flows
0 1 -180,000
1 5 100,000
2 5 -100,000
3 9 0
4 1 200,000
cashFlows =  [-180000,
               100000, 100000, 100000, 100000, 100000,
              -100000, -100000, -100000, -100000, -100000,
               0,0,0,0,0,0,0,0,0,
               200000]
>> safeRate = 6.0/12
>> reinvestmentRate = 10.0/12
>> MIRR(6.0/12, 10.0/12,cashFlows)
>> 0.81  

That is an annual of 9.7

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994

Amortization

Typical Uses

Amortization is a method for repaying a loan in equal installments. Part of each payment goes toward interest due for the period and the remainder is used to reduce the principal (the loan balance). As the balance of the loan is gradually reduced, a progressively larger portion of each payment goes toward reducing principal.

Use amort to calculate the sums applied towards the priciple and to the interest from a single or series of payments.

Ingredients

  • TODO

Algorithm

#Algorithm:

def round(x):
    return x
    r = floor(100.0*fabs(x)+0.5)        
    r /=100.0
    return r*(fabs(x)/x)

def amort(i, PV, PMT, n):
    i /=100.0
    sign = int(PMT/fabs(PMT))
    i *=sign
    interestPaid =0
    principlePaid =0
    remainingPrinciple=PV
    period=1
    forInterest = remainingPrinciple * i
    forPrinciple =  PMT - forInterest
    remainingPrinciple += forPrinciple
    interestPaid +=forInterest
    principlePaid += forPrinciple
    period +=1
    while period <= n:
        forInterest = remainingPrinciple * i
        forPrinciple =  PMT - forInterest
        remainingPrinciple += forPrinciple
        interestPaid +=forInterest
        principlePaid += forPrinciple
        period +=1
    return fabs(interestPaid), fabs(principlePaid), PV-fabs(principlePaid)

Example

You have mortgage for $500,000 at a fixed annual interest of 13.25%. Your payments are 5733.5 per at the end of each month. Find the amount that you would have paid to interest and to the principle after second year.

>> PV=500000
>> i=13.25/12 
>> PMT = 5733.50
>> n = 24
>> amort(i, PV, PMT, n)
>> (131230.45596198068, 6373.5440380193058, 493626.45596198068)

If you need an An amortization schedule use the following snippet:

>> pvj = PV
>> j =1
>> while j <= n:
    intj, prnj, pvj = amort3(1.10, pvj, -573.35, 1)
    j +=1
>> 

Here is the schedual of the first year from the above example:

Period (j) Interest Paid Principle Paid Principle Remaining
1 5500.00 233.50 499766.50
2 5497.43 236.07 499530.43
3 5494.83 238.67 499291.77
4 5492.21 241.29 499050.48
5 5489.56 243.94 498806.53
6 5486.87 246.63 498559.90
7 5484.16 249.34 498310.56
8 5481.42 252.08 498058.48
9 5478.64 254.86 497803.62
10 5475.84 257.66 497545.96
11 5473.01 260.49 497285.47
12 5470.14 263.36 497022.11

References

  • Gallager, T; Andrew Jr., J., Financial Management: Principals and Practices, Upper Saddle River, NJ: Prentice Hall, 1996
  • HP-12C Business Calculator Owner's Manual, Hewlett Packard, 1984
  • HP-10B Business Calculator Owner's Manual, Hewlett Packard, 1994