Skip to content

Instantly share code, notes, and snippets.

@javiergarciad
Created April 28, 2016 03:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javiergarciad/f8627bd932ec1ad6f9f4bf5c3524e7ee to your computer and use it in GitHub Desktop.
Save javiergarciad/f8627bd932ec1ad6f9f4bf5c3524e7ee to your computer and use it in GitHub Desktop.
Some financial functios
'''
Created on Mar 28, 2016
@author: Javier Garcia
'''
import numpy as np
from datetime import date
from scipy.optimize import newton
def vpn(rate, cashflows):
'''
Valor presente neto de una serie de pagos
'''
total = 0.0
for i, cashflow in enumerate(cashflows):
total += cashflow / (1 + rate)**i
return total
# http://stackoverflow.com/questions/6892900/what-is-the-numerical-method-used-in-this-implementation-of-irr
# http://en.wikipedia.org/wiki/Fixed_point_iteration
def tir(cashflows, iterations=100):
'''
TIR para pagos regulares
'''
rate = 1.00
investment = cashflows[0]
for i in range(1, iterations+1):
rate *= (1 - vpn(rate, cashflows) / investment)
return rate
def _discf(rate, pmts, dates):
dcf=[]
for i,cf in enumerate(pmts):
d=dates[i]-dates[0]
dcf.append(cf*(1+rate)**(-d.days/365.))
return np.add.reduce(dcf)
def xtir(cf, dates, guess=.10):
'''
TIR funcion que acepta pagos irregulares
el resultado es la solucion de
Sumatoria{cf/[(1+xtir)^[(date_t-date_0)/365]]} = 0
'''
for i,dt in enumerate(dates):
dates[i]=date(*dt)
f = lambda x: _discf(x, cf, dates)
#http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html
return newton(f, guess)
if __name__ == '__main__':
dates=[[2008,2,5],[2008,7,5],[2019,1,5]]
cf=[-2750,1000,2500]
print(tir(cf))
print(xtir(cf,dates))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment