|
| 1 | +import pytest, random, math, numpy, time, functools |
| 2 | +import irr |
| 3 | + |
| 4 | + |
| 5 | +def run_many(case): |
| 6 | + @functools.wraps(case) |
| 7 | + def wrapped(): |
| 8 | + for test in range(1000): |
| 9 | + d, r = case() |
| 10 | + assert irr.irr(d) == pytest.approx(r) |
| 11 | + return wrapped |
| 12 | + |
| 13 | + |
| 14 | +@run_many |
| 15 | +def test_simple_bond(): |
| 16 | + r = math.exp(random.gauss(0, 1)) - 1 |
| 17 | + x = random.gauss(0, 1) |
| 18 | + d = [x / (1 + r), -x] |
| 19 | + return d, r |
| 20 | + |
| 21 | + |
| 22 | +@run_many |
| 23 | +def test_slightly_longer_bond(n=10): |
| 24 | + r = math.exp(random.gauss(0, 1)) - 1 |
| 25 | + x = random.gauss(0, 1) |
| 26 | + d = [x] + [0.0] * (n-2) + [-x * (1+r)**(n-1)] |
| 27 | + return d, r |
| 28 | + |
| 29 | + |
| 30 | +@run_many |
| 31 | +def test_more_nonzero(n=10): |
| 32 | + r = math.exp(random.gauss(0, 1)) - 1 |
| 33 | + d = [random.random() for i in range(n-1)] |
| 34 | + d.append(-sum([x * (1+r)**(n-i-1) for i, x in enumerate(d)])) |
| 35 | + return d, r |
| 36 | + |
| 37 | + |
| 38 | +def test_performance(): |
| 39 | + us_times = [] |
| 40 | + np_times = [] |
| 41 | + ns = [10, 20, 50, 100] |
| 42 | + for n in ns: |
| 43 | + k = 100 |
| 44 | + sums = [0.0, 0.0] |
| 45 | + for j in range(k): |
| 46 | + r = math.exp(random.gauss(0, 1.0 / n)) - 1 |
| 47 | + x = random.gauss(0, 1) |
| 48 | + d = [x] + [0.0] * (n-2) + [-x * (1+r)**(n-1)] |
| 49 | + |
| 50 | + results = [] |
| 51 | + for i, f in enumerate([irr.irr, numpy.irr]): |
| 52 | + t0 = time.time() |
| 53 | + results.append(f(d)) |
| 54 | + sums[i] += time.time() - t0 |
| 55 | + |
| 56 | + if not numpy.isnan(results[1]): |
| 57 | + assert results[0] == pytest.approx(results[1]) |
| 58 | + for times, sum in zip([us_times, np_times], sums): |
| 59 | + times.append(sum/k) |
| 60 | + |
| 61 | + try: |
| 62 | + from matplotlib import pyplot |
| 63 | + import seaborn |
| 64 | + except ImportError: |
| 65 | + return |
| 66 | + |
| 67 | + pyplot.plot(ns, us_times, label='Our library') |
| 68 | + pyplot.plot(ns, np_times, label='Numpy') |
| 69 | + pyplot.xlabel('n') |
| 70 | + pyplot.ylabel('time(s)') |
| 71 | + pyplot.yscale('log') |
| 72 | + pyplot.savefig('plot.png') |
| 73 | + |
| 74 | + |
0 commit comments