-
Notifications
You must be signed in to change notification settings - Fork 0
/
xirr_test.go
83 lines (69 loc) · 1.39 KB
/
xirr_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package xirr
import (
"encoding/csv"
"io"
"math"
"os"
"strconv"
"testing"
"time"
)
func TestRandom(t *testing.T) {
payments, err := loadPayments("samples/random.csv")
if err != nil {
t.Fatalf("error loading payments: %v", err)
}
actual, err := Compute(payments)
if err != nil {
t.Fatalf("error computing xirr: %v", err)
}
cErr := math.Abs(actual - 0.1266061750083439787)
if cErr > MaxError {
t.Fatalf("expected error to be less than %v but the error is %v", MaxError, cErr)
}
}
func BenchmarkXIRR(b *testing.B) {
payments, err := loadPayments("samples/random.csv")
if err != nil {
b.Fatalf("error loading payments: %v", err)
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, err := Compute(payments)
if err != nil {
b.Fatalf("error computing xirr: %v", err)
}
}
}
func loadPayments(fpath string) (Payments, error) {
f, err := os.Open(fpath)
if err != nil {
return nil, err
}
defer f.Close()
rdr := csv.NewReader(f)
rdr.ReuseRecord = true
var payments Payments
for {
rec, err := rdr.Read()
if err != nil {
if err == io.EOF {
return payments, nil
}
return nil, err
}
amount, err := strconv.ParseFloat(rec[0], 64)
if err != nil {
return nil, err
}
date, err := time.Parse("02/01/06", rec[1])
if err != nil {
return nil, err
}
payments = append(payments, Payment{
Date: date,
Amount: amount,
})
}
}