I have the following app that optimize the following pb. The code works but i found it a little bit slow. Any idea of performance improvements ( without writing c code ) that can be done to better use python, numpy and scipy? It seems me that the interpolate function is the main time consuming part.
from scipy.optimize import leastsq
from scipy.interpolate import interp1d
import timeit
class Bond(object):
def __init__(self, years, cpn):
self.years = years
self.coupon = cpn
self.cashflows = [(0.0, -1.0)]
self.cashflows.extend([(float(i),self.coupon) for i in range(1,self.years)])
self.cashflows.append((float(self.years), 1.0 + self.coupon))
def pv(self, market):
return sum([cf[1] * market.df(cf[0]) for cf in self.cashflows])
class Market(object):
def __init__(self, instruments):
self.instruments = sorted(
instruments, key=lambda instrument : instrument.cashflows[-1][0])
self.knots = [0.0]
self.knots.extend([inst.cashflows[-1][0] for inst in self.instruments])
self.dfs = [1.0]
self.dfs.extend([1.0] * len(self.instruments))
self.interp = interp1d(self.knots, self.dfs)
def df(self, day):
return self.interp(day)
def calibrate(self):
leastsq(self.__target, self.dfs[1:])
def __target(self, x):
self.dfs[1:] = x
self.interp = interp1d(self.knots, self.dfs)
return [bond.pv(self) for bond in self.instruments]
def main():
instruments = [Bond(i, 0.02) for i in xrange(1, numberOfInstruments + 1)]
market = Market(instruments)
market.calibrate()
print('CALIBRATED')
numberOfTimes = 10
numberOfInstruments = 50
print('%.2f' % float(timeit.timeit(main, number=numberOfTimes)/numberOfTimes))