views:

501

answers:

2

I am looking for a financial library for Python that will enable me to do a discounted cash flow analysis. I have looked around and found the QuantLib, which is overkill for what I want to do. I just need a small library that I can use to input a series of cash flows and have it output a net present value and internal rate of return. Anyone have something like this or know where I can find it?

+3  A: 

If you really only want to compute net present value (== an inner product of vectors for cashflows and discount factors) and internal rate of return (== a simple iterative root search for one variable) then you can just code it up.

I use R much more than Python so here is an R solution:

R> data <- data.frame(CF=c(rep(2,5), 102), df=1.01^(-(1:6)))
R> data
   CF     df
1   2 0.9901
2   2 0.9803
3   2 0.9706
4   2 0.9610
5   2 0.9515
6 102 0.9420
R> NPV <- sum(data[,1] * data[,2])
R> print(NPV)
[1] 105.8
R> 

This sets up two-column data structure of cash flows and discount factors and computes NPV as the sum of the products. So a (simplistic) six-year bond with a 2% coupon in 1% flat yield curve would be worth 105.80.

For IRR, we do just about the same but make the NPV a function of the rate:

R> irrSearch <- function(rate) { data <- data.frame(CF=c(rep(2,5), 102), 
                                 df=(1+rate/100)^(-(1:6))); 
                                 100 - sum(data[,1] * data[,2]) }
R> uniroot( irrSearch, c(0.01,5) )
R> irr <- uniroot( irrSearch, c(0.01,5) )
R> irr$root
[1] 2
R> 

So the 'root' to the search for the internal rate of return of 2% bond in a flat-curve world is ... unsurprisingly 2%.

Dirk Eddelbuettel
See this library: http://rpy.sourceforge.net/index.html That will allow you to call R from Python without much extra work.
S.Lott
Yup, but that is in maintenance mode. It may be wiser to use the newer RPy2 instead.
Dirk Eddelbuettel
+2  A: 

Just for completeness, since I'm late: numpy has some functions for (very) basic financial calculations. numpy, scipy could also be used, to do the calculations from the basic formulas as in R.

net present value of cashflow

>>> cashflow = 2*np.ones(6)
>>> cashflow[-1] +=100
>>> cashflow
array([   2.,    2.,    2.,    2.,    2.,  102.])
>>> np.npv(0.01, cashflow)
105.79547647457932

get internal rate or return

>>> n = np.npv(0.01, cashflow)
>>> np.irr(np.r_[-n, cashflow])
0.010000000000000231

just the basics:

>>> [f for f in dir(np.lib.financial) if not f[0] == '_']
['fv', 'ipmt', 'irr', 'mirr', 'np', 'nper', 'npv', 'pmt', 'ppmt', 'pv', 'rate']

and it's necessary to watch out what the timing is.