investments 2.5.1

Helps you with managing your investments
Documentation
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use std::iter::FromIterator;

use chrono::Datelike;

use crate::core::GenericResult;
#[cfg(test)] use crate::currency;
use crate::types::{Date, Decimal};

pub struct DepositEmulator {
    date: Date,
    end_date: Date,

    monthly_capitalization: bool,
    interest_periods: Vec<InterestPeriod>,
    interest_period: Option<ActiveInterestPeriod>,

    daily_interest: Decimal,
    assets: Decimal,
}

impl DepositEmulator {
    pub fn new(start_date: Date, end_date: Date, interest: Decimal) -> DepositEmulator {
        assert!(start_date <= end_date);

        let mut interest_periods = Vec::new();
        if start_date != end_date {
            interest_periods.push(InterestPeriod::new(start_date, end_date));
        }

        DepositEmulator {
            date: start_date,
            end_date: end_date,

            monthly_capitalization: true,
            interest_periods: interest_periods,
            interest_period: None,

            daily_interest: interest / dec!(100) / dec!(365),
            assets: dec!(0),
        }
    }

    pub fn with_monthly_capitalization(mut self, monthly_capitalization: bool) -> DepositEmulator {
        self.monthly_capitalization = monthly_capitalization;
        self
    }

    pub fn with_interest_periods(mut self, custom_interest_periods: &[InterestPeriod]) -> DepositEmulator {
        self.interest_periods = Vec::from_iter(custom_interest_periods.iter().rev().cloned());
        self
    }

    pub fn emulate(mut self, transactions: &[Transaction]) -> Decimal {
        self.select_interest_period();

        for transaction in transactions {
            self.process_transaction(transaction);
        }

        self.process_to(self.end_date);
        assert!(self.interest_period.is_none());

        self.assets
    }

    fn select_interest_period(&mut self) {
        assert!(self.interest_period.is_none());

        let period = match self.interest_periods.last() {
            Some(period) => *period,
            None => return,
        };

        assert!(self.date <= period.start);
        if self.date != period.start {
            return
        }

        self.interest_periods.pop().unwrap();

        let mut interest_period = ActiveInterestPeriod {
            start_date: period.start,
            monthly_capitalization: self.monthly_capitalization,
            next_capitalization_date: period.start,
            accumulated_income: dec!(0),
            end_date: period.end,
        };
        interest_period.set_next_capitalization_date();

        self.interest_period = Some(interest_period);
    }

    fn process_transaction(&mut self, transaction: &Transaction) {
        self.process_to(transaction.date);
        self.assets += transaction.amount;
    }

    fn process_to(&mut self, date: Date) {
        assert!(self.date <= date);

        while self.date < date {
            if let Some(interest_period) = self.interest_period {
                // We're inside of the interest period

                if date >= interest_period.next_capitalization_date {
                    self.accumulate_income_to(interest_period.next_capitalization_date);

                    if self.date == interest_period.end_date {
                        self.close_interest_period();
                    } else {
                        self.capitalize();
                    }
                } else {
                    self.accumulate_income_to(date);
                }
            } else {
                // We're outside of the interest period

                if let Some(next_period) = self.interest_periods.last() {
                    assert!(self.date < next_period.start);

                    if date < next_period.start {
                        self.date = date;
                    } else {
                        self.date = next_period.start;
                        self.select_interest_period();
                    }
                } else {
                    self.date = date;
                }
            }
        }

        assert_eq!(self.date, date);
    }

    fn accumulate_income_to(&mut self, date: Date) {
        let interest_period = self.interest_period.as_mut().unwrap();

        assert!(self.date <= date);
        assert!(interest_period.start_date <= self.date);
        assert!(date <= interest_period.next_capitalization_date);

        if self.assets.is_sign_positive() {
            let days = (date - self.date).num_days();
            let income = self.assets * self.daily_interest * Decimal::from(days);
            interest_period.accumulated_income += income;
        }

        self.date = date;
    }

    fn capitalize(&mut self) {
        let interest_period = self.interest_period.as_mut().unwrap();
        assert_eq!(self.date, interest_period.next_capitalization_date);

        self.assets += interest_period.accumulated_income;
        interest_period.accumulated_income = dec!(0);

        interest_period.set_next_capitalization_date();
    }

    fn close_interest_period(&mut self) {
        let interest_period = self.interest_period.take().unwrap();
        assert_eq!(self.date, interest_period.end_date);
        self.assets += interest_period.accumulated_income;

        self.select_interest_period();
    }
}

#[cfg_attr(test, derive(Clone, Copy))]
pub struct Transaction {
    pub date: Date,
    pub amount: Decimal,
}

impl Transaction {
    pub fn new(date: Date, amount: Decimal) -> Transaction {
        Transaction {
            date: date,
            amount: amount,
        }
    }
}

#[derive(Clone, Copy)]
pub struct InterestPeriod {
    pub start: Date,
    pub end: Date,
}

impl InterestPeriod {
    pub fn new(start: Date, end: Date) -> InterestPeriod {
        assert!(start < end);
        InterestPeriod { start, end }
    }

    pub fn days(&self) -> u32 {
        let days = (self.end - self.start).num_days();
        cast::u32(days).unwrap()
    }
}

#[derive(Clone, Copy)]
struct ActiveInterestPeriod {
    start_date: Date,
    monthly_capitalization: bool,
    next_capitalization_date: Date,
    accumulated_income: Decimal,
    end_date: Date,
}

impl ActiveInterestPeriod {
    fn set_next_capitalization_date(&mut self) {
        assert!(self.next_capitalization_date < self.end_date);

        if self.monthly_capitalization {
            self.next_capitalization_date = get_next_capitalization_date(
                self.next_capitalization_date, self.start_date.day()).unwrap();

            if self.next_capitalization_date > self.end_date {
                self.next_capitalization_date = self.end_date;
            }
        } else {
            self.next_capitalization_date = self.end_date;
        }
    }
}

fn get_next_year_month(mut year: i32, mut month: u32) -> (i32, u32) {
    if month == 12 {
        year += 1;
        month = 1;
    } else {
        month += 1;
    }

    (year, month)
}

fn get_next_capitalization_date(current: Date, capitalization_day: u32) -> GenericResult<Date> {
    if current.day() != capitalization_day && !(
        current.day() < capitalization_day && current.succ().month() != current.month()
    ) {
        return Err!(
            "Got an unexpected current capitalization date for the specified capitalization day");
    }

    let (year, month) = get_next_year_month(current.year(), current.month());

    Ok(match Date::from_ymd_opt(year, month, capitalization_day) {
        Some(date) => date,
        None => {
            let (year, month) = get_next_year_month(year, month);
            let date = Date::from_ymd(year, month, 1).pred();
            let days = (date - current).num_days();
            assert!(days >= 28 && days <= 31);
            date
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn real_deposit() {
        let open_date = date!(28, 7, 2018);
        let interest = dec!(7);
        let transactions = vec![Transaction::new(open_date, dec!(600_000))];

        for &(capitalization_date, expected_assets) in &[
            (date!(28,  7, 2018), dec!(600_000.00)),
            (date!(28,  8, 2018), dec!(603_567.12)),
            (date!(28,  9, 2018), dec!(607_155.45)),
            (date!(28, 10, 2018), dec!(610_648.68)),
            (date!(28, 11, 2018), dec!(614_279.11)),
            (date!(28, 12, 2018), dec!(617_813.32)),
            (date!(28,  1, 2019), dec!(621_486.34)),
        ] {
            let result = DepositEmulator::new(open_date, capitalization_date, interest)
                .emulate(&transactions);
            assert_eq!(currency::round(result), expected_assets);

            {
                // Test deposit closing

                let mut transactions = transactions.clone();
                transactions.push(Transaction::new(capitalization_date, -expected_assets));

                let result = DepositEmulator::new(open_date, capitalization_date, interest)
                    .emulate(&transactions);
                assert_eq!(currency::round(result), dec!(0));
            }
        }
    }

    #[test]
    fn real_deposit_with_contributions() {
        let open_date = date!(31, 1, 2019);
        let interest = dec!(7);
        let transactions = vec![
            Transaction::new(open_date, dec!(190_000)),
            Transaction::new(date!( 5, 2, 2019), dec!(60_000)),
            Transaction::new(date!(21, 2, 2019), dec!(50_000)),
        ];

        for &(capitalization_date, expected_assets) in &[
            (date!(28, 2, 2019), dec!(301_352.05)),
            (date!(31, 3, 2019), dec!(303_143.65)),
            (date!(30, 4, 2019), dec!(304_887.77)),
            (date!(31, 5, 2019), dec!(306_700.39)),
            (date!(30, 6, 2019), dec!(308_464.97)),
            (date!(31, 7, 2019), dec!(310_298.85)),
        ] {
            let result = DepositEmulator::new(open_date, capitalization_date, interest)
                .emulate(&transactions);
            assert_eq!(currency::round(result), expected_assets);
        }
    }

    #[test]
    fn joint_deposits() {
        let open_date = date!(1, 1, 2018);
        let interest = dec!(7);

        // Some assets without interest
        let mut transactions = vec![Transaction::new(open_date, dec!(200_000))];
        let mut interest_periods = Vec::new();

        // First deposit
        transactions.push(Transaction::new(date!(28, 7, 2018), dec!(400_000)));
        interest_periods.push(InterestPeriod::new(date!(28, 7, 2018), date!(28, 1, 2019)));
        let result = DepositEmulator::new(open_date, date!(28, 1, 2019), interest)
            .with_interest_periods(&interest_periods)
            .emulate(&transactions);
        assert_eq!(currency::round(result), dec!(621_486.34));

        // A pause with no interest
        transactions.push(Transaction::new(date!(28, 1, 2019), dec!(100_000) - result));
        transactions.push(Transaction::new(date!(31, 1, 2019), dec!(90_000)));
        let result = DepositEmulator::new(open_date, date!(31, 1, 2019), interest)
            .with_interest_periods(&interest_periods)
            .emulate(&transactions);
        assert_eq!(currency::round(result), dec!(190_000));

        // Second deposit
        interest_periods.push(InterestPeriod::new(date!(31, 1, 2019), date!(31, 7, 2019)));
        let result = DepositEmulator::new(open_date, date!(31, 7, 2019), interest)
            .with_interest_periods(&interest_periods)
            .emulate(&transactions);
        assert_eq!(currency::round(result), dec!(196_691.45));

        transactions.push(Transaction::new(date!(5, 2, 2019), dec!(60_000)));
        let result = DepositEmulator::new(open_date, date!(31, 7, 2019), interest)
            .with_interest_periods(&interest_periods)
            .emulate(&transactions);
        assert_eq!(currency::round(result), dec!(258_745.30));

        transactions.push(Transaction::new(date!(21, 2, 2019), dec!(50_000)));
        let result = DepositEmulator::new(open_date, date!(31, 7, 2019), interest)
            .with_interest_periods(&interest_periods)
            .emulate(&transactions);
        assert_eq!(currency::round(result), dec!(310_298.85));

        // Some activity with no interest
        transactions.push(Transaction::new(date!(31, 7, 2019), dec!(100_000) - result));
        let result = DepositEmulator::new(open_date, date!(1, 1, 2020), interest)
            .with_interest_periods(&interest_periods)
            .emulate(&transactions);
        assert_eq!(currency::round(result), dec!(100_000));
    }

    #[test]
    fn deposit_without_monthly_capitalization() {
        let open_date = date!(28, 7, 2018);
        let interest = dec!(6);

        let transactions = vec![
            Transaction::new(open_date, dec!(100_000)),
            Transaction::new(date!(10, 8, 2018), dec!(100_000)),
        ];

        for &(capitalization_date, expected_assets) in &[
            (date!(28,  8, 2018), dec!(200_805.48)),
            (date!(28,  9, 2018), dec!(201_824.66)),
            (date!(28, 10, 2018), dec!(202_810.96)),
            (date!(28, 11, 2018), dec!(203_830.14)),
            (date!(28, 12, 2018), dec!(204_816.44)),
            (date!(28,  1, 2019), dec!(205_835.62)),
        ] {
            let result = DepositEmulator::new(open_date, capitalization_date, interest)
                .with_monthly_capitalization(false)
                .emulate(&transactions);
            assert_eq!(currency::round(result), expected_assets);

            {
                // Test deposit closing

                let mut transactions = transactions.clone();
                transactions.push(Transaction::new(capitalization_date, -expected_assets));

                let result = DepositEmulator::new(open_date, capitalization_date, interest)
                    .with_monthly_capitalization(false)
                    .emulate(&transactions);
                assert_eq!(currency::round(result), dec!(0));
            }
        }
    }

    #[test]
    fn next_capitalization_date() {
        // Dec -> Jan
        for day in 1..32 {
            assert_eq!(get_next_capitalization_date(date!(day, 12, 2018), day).unwrap(),
                       date!(day, 1, 2019));
        }

        // Jan -> Feb
        for day in 1..29 {
            assert_eq!(get_next_capitalization_date(date!(day, 1, 2019), day).unwrap(),
                       date!(day, 2, 2019));
        }
        for day in 29..32 {
            assert_eq!(get_next_capitalization_date(date!(day, 1, 2019), day).unwrap(),
                       date!(28, 2, 2019));
        }

        // Feb -> Mar
        for day in 1..29 {
            assert_eq!(get_next_capitalization_date(date!(day, 2, 2019), day).unwrap(),
                       date!(day, 3, 2019));
        }
        for day in 28..32 {
            assert_eq!(get_next_capitalization_date(date!(28, 2, 2019), day).unwrap(),
                       date!(day, 3, 2019));
        }
        for day in 1..28 {
            assert!(get_next_capitalization_date(date!(28, 2, 2019), day).is_err());
        }
    }
}