-
Notifications
You must be signed in to change notification settings - Fork 0
/
capitalics.js
647 lines (546 loc) · 19.1 KB
/
capitalics.js
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// all money values monthly , netto
// all interest rates yearly in percent, except when explicitly otherwise
/**
* Format value as amount of money, i.e render it with 2 decimals.
*/
export function formatMoney(value) {
return value.toFixed(2);
}
/**
* Create a callback function which expects to get the elapsed months
* and from that calculates the current value by applying the monthlyRate (in %)
* to it.
* Eg. when calling this with initialValue 1000 and giving a monthlyRate of 1 %
* then the callback when called with months=1 will return
* 1000 * 1 %/month * 1 month = 1010 .
*/
export function monthlyRateCallback(initialValue, monthlyRate) {
return function(months) {
return initialValue * Math.pow(1.0 + monthlyRate / 100.0, months);
};
}
/**
* Base class for all financial entities. A financial entity is expected to have a nextMoth method,
* which shall simlulate the development of the financial entity over the period over one more month.
*
* For example if the financial entity is initialized with a state describing "today", then calling
* 12 times nextMonth() on it will result in it beeing in the state today + 1 year.
*
* With the recordState method, the financial entity can record its current state to the recorder
* instance, i.e. by publishing its internal values using the recorder.add method.
*/
export class FinancialEntity {
nextMonth() {
//
}
recordState(recorder) {
//
}
getSummary() {
return null;
}
}
class TimeSeriesRecorder {
constructor() {
this.data = new Object();
this.date = null;
}
setDate(date) {
this.date = date;
}
add(name, value) {
if (!(this.data[name] instanceof Array)) {
this.data[name] = new Array();
}
this.data[name].push({x: this.date, y: value});
}
}
export class Scheduler {
// idea:
// 1. run all actions
// 2. run all accounts (eg. apply interest rates)
// 3. run all transactions
// 4. observe/report the resulting state
constructor(actions, accounts, transactions) {
this.actions = actions;
this.transactions = transactions;
this.accounts = accounts;
this.dataRecorder = new TimeSeriesRecorder();
}
run(years) {
var date = new Date();
for (var month = 0; month < 12 * years; month++) {
date.setMonth(date.getMonth() + 1);
this.dataRecorder.setDate(new Date(date.getTime()));
var all = this.actions.concat(this.accounts, this.transactions);
for (var i = 0; i < all.length; i++) {
all[i].nextMonth();
}
for (var i = 0; i < all.length; i++) {
all[i].recordState(this.dataRecorder);
}
}
return this.dataRecorder.data;
}
}
/**
* An account represents anything where money or debt is lying around.
*/
export class Account extends FinancialEntity {
constructor(name) {
super();
this.name = name;
}
deduct(value) {
//
}
deposit(value) {
//
}
}
export class Spending extends FinancialEntity {
constructor(value) {
super();
this.value = value;
}
}
export var OUT_THE_WINDOW = null;
export var OUT_OF_NOWHERE = null;
/**
* A RegularTransaction deduces a certain amount from some account and
* deposits it in another account every month.
* The amount can either be a fixed value, can be determined by an array
* of At-instances (see also SequenceAction class) with numeric values,
* or it can be computed by invoking a callback function.
* The from parameter can be OUT_OF_NOWHERE (do not deduce the amount from any account,
* but deposit anyway in the account specified by to parameter).
* The to parameter can be OUT_THE_WINDOW (deduce the amount from the from account,
* but do not deposit it in any other account).
*/
export class RegularTransaction extends FinancialEntity {
constructor(name, from, to, value) {
super();
this.name = name;
this.from = from;
this.to = to;
this.monthCounter = 0;
if (value instanceof Array) {
this.mode = "sequence";
this.ats = value;
this.value = null;
// Todo: verify this.ats actually contains At instances with values
} else if (value instanceof Function) {
this.mode = "callback";
this.callback = value;
this.value = null;
} else if (value.toFixed) { // workaround for "is value a number?"
this.mode = "numeric";
this.value = value;
} else {
throw Error("invalid value, need number, array of At instaces or callack");
}
}
nextMonth() {
if (this.mode == "sequence") {
// use value of latest At which is passed
for (var i = this.ats.length - 1; i >= 0; i--) {
var at = this.ats[i];
if (at.passed(this.monthCounter)) {
this.value = at.param;
break;
}
}
} else if (this.mode == "callback") {
this.value = this.callback(this.monthCounter);
}
this.monthCounter++;
if (this.from != OUT_OF_NOWHERE) {
this.from.deduct(this.value);
}
if (this.to != OUT_THE_WINDOW) {
this.to.deposit(this.value);
}
}
recordState(recorder) {
recorder.add(this.name, this.value);
}
}
export class Savings extends Account {
constructor(name, startValue, interestRate) {
super(name);
this.value = startValue;
this.interests = new Interests(interestRate);
this.accumulatedInterests = 0.0;
this.payment = 0.0;
this.minValue = startValue;
}
nextMonth() {
var interests = this.interests.perMonth(this.value);
this.accumulatedInterests += interests;
this.value = this.value + this.payment + interests;
if (this.value < this.minValue) {
this.minValue = this.value;
}
}
deposit(value) {
this.value += value;
}
deduct(value) {
this.value -= value;
}
recordState(recorder) {
recorder.add(this.name, this.value);
}
getSummary() {
return "Interests: " + formatMoney(this.accumulatedInterests) + "\n" +
"Min Value: " + formatMoney(this.minValue);
}
}
/**
* Helper class to represent a interest rate.
*/
export class Interests {
// yearly rate in percent
constructor(ratePerYear) {
this.ratePerYear = ratePerYear;
}
perMonth(value) {
return value * (this.ratePerYear / 100.0 / 12);
}
}
/**
* Specifies a point in time.
*
* Optionally add a value via the param parameter which can be retrieved later
* from the object. With this you can eg. encode the development of a value
* over time, eg. [new At(2050, 1, 123), new At(2050, 6, 321)].
*/
export class At {
constructor(years, months, param) {
this.years = years;
this.months = months;
this.param = param;
}
passed(months) {
// return true if the point in time specified by the months
// parameter is behind the one defined via years and months
// members
return months >= this.years * 12 + this.months;
}
}
/**
* Wrapper to run an other financial entity later, i.e. while the nextMonth method
* of the wrapper is called from the beginning, it will only forward the call to the
* other financial entity once the specified point in time has passed.
*/
export class Timer extends FinancialEntity {
constructor(years, months, other) {
super();
this.start = new At(years, months);
this.other = other;
this.monthCounter = 0;
}
nextMonth() {
if (this.start.passed(this.monthCounter)) {
this.other.nextMonth();
}
this.monthCounter++;
}
recordState(recorder) {
this.other.recordState(recorder);
}
getSummary() {
return this.other.getSummary();
}
}
/**
* Can be hooked into the scheduler like a financial entity, but instead of generating a
* value it runs an action (=callback function) at the specified point in time.
*
* If the once parameter is set to true, the action will only be called once, otherwise
* it will be run every month once the point in time has passed.
*/
export class TimerAction extends FinancialEntity {
constructor(years, months, action, once) {
super();
this.start = new At(years, months);
this.action = action;
this.monthCounter = 0;
this.once = once;
this.happened = false;
}
nextMonth() {
if (this.once && this.happened) {
return;
}
if (this.start.passed(this.monthCounter)) {
this.happened = true;
this.action();
}
this.monthCounter++;
}
}
/**
* Wrapper to only forward the nextMonth call to other when
* the condition (=callback function) returns true.
*/
export class When extends FinancialEntity {
constructor(condition, other) {
this.condition = condition;
this.other = other;
}
nextMonth() {
if (this.condition()) {
this.other.nextMonth();
}
}
getSummary() {
return this.other.getSummary();
}
}
/**
* Can be hooked into the scheduler like any other FinancialEntity,
* but instead of generating a value it will run an action once the condition
* (=callback function) returns true.
* With the once parameter it can be controlled whether the action will only
* be run once and after that, independent of the condition will never be
* executed again.
*/
export class WhenAction extends FinancialEntity {
constructor(condition, action, once) {
super();
this.condition = condition;
this.action = action;
this.once = once;
this.happened = false;
}
nextMonth() {
if (this.once && this.happened) {
return;
}
if (this.condition()) {
this.happened = true;
this.action();
}
}
}
/**
* Allows to specify a sequence of points in time (At instances),
* and a callback function "action" such that the action will be executed
* each month with the latest At instance which has passed.
*
* Note: At instances should be passed as arra in "ats" parameter and should
* be sorted by increasing time.
*/
export class SequenceAction extends FinancialEntity {
constructor(ats, action) {
super();
this.ats = ats;
this.action = action;
this.monthCounter = 0;
}
nextMonth() {
// invoke action with the latest when which is passed
for (var i = this.ats.length - 1; i >= 0; i--) {
var at = this.ats[i];
if (at.passed(this.monthCounter)) {
this.action(at);
break;
}
}
this.monthCounter++;
}
}
/**
* Models a typical credit, i.e. an annuity loan which is granted by the bank as a ammount and then
* has to be payed back with monthly repayments. As long as the credit is not payed back completely,
* the bank will get monthly interests according to a fixed interest rate.
*
* The credit has three states:
* * initial: money not retrieved from the bank yet
* * credit: money retrieved, interests apply, paying back monthly
* * done: everthing payed back
*
* Note: for a credit calling deposit() with a positive amount means, that debt is reduced.
* Since internally the credit class holds the current value as positive number, the deposit function
* will therefore substract from it.
*
* Note: a credit can have fixed costs (eg. entry in the land register) but those can be incorporated in the
* effective yearly interest rate which is usually provided by the bank for a fixed period of time.
*/
export class Credit extends Account {
constructor(name, credit, interestRate, payment) {
super(name);
this.credit = credit;
this.interests = new Interests(interestRate);
this.payment = payment;
this.accumulatedInterests = 0.0;
this.phase = "initial";
this.value = 0.0;
this.lastInterests = 0.0;
}
nextMonth() {
// first time we get nextMonth call, switch to credit phase
if (this.phase == "initial") {
this.phase = "credit";
this.value = this.credit;
}
if (this.phase == "credit") {
this.lastInterests = this.interests.perMonth(this.value);
this.accumulatedInterests += this.lastInterests;
this.value += this.lastInterests;
if (this.value <= 0.0) {
this.phase = "done";
}
} else {
this.value = 0.0;
this.lastInterests = 0.0;
}
}
deposit(value) {
this.value -= value;
if ((this.value <= 0.0) && (this.phase == "credit")) {
this.phase = "done";
this.value = 0.0;
}
}
recordState(recorder) {
recorder.add(this.name, this.value);
recorder.add(this.name + '.interests', this.lastInterests);
}
getPayment() {
if (this.phase == "initial") {
return 0.0;
} else if (this.phase == "credit") {
return this.payment;
} else if (this.phase == "done") {
return 0.0;
} else {
return 0.0;
}
}
getRateTransaction(from) {
return new RegularTransaction(this.name + ".rate", from, this, this.getPayment.bind(this))
}
getDescription() {
return "Credit: " + formatMoney(this.credit) + "\n" +
"Interest rate: " + this.interests.ratePerYear + " %/a\n" +
"Payment: " + formatMoney(this.payment);
}
getSummary() {
return "Cost: " + formatMoney(this.getCost());
}
getCost() {
return this.accumulatedInterests;
}
}
/**
* House savings are a two phase financial product which accounts of
* * a saving phase in which montly savings are payed to the back. The ammount already saved will be granted interest rates by the bank.
* * a credit phase where the saved ammount + an additional credit will be payed out by the bank and future repayments are made for the credit part.
*
* House savings are designed to finance the acquisition of a house, or construction of a house. Typically the house savings is defined by the total sum
* which consists of both the ammount which is targetted to be saved as well as the credit value to be granted by the bank.
*
* Note: house savings are quite complex with many details which are hard to model:
* * the time when the saving phase ends is quite flexible. Either savings are complete, or the credit is needed earlier.
* * the bank does not guarantee a concrete time for the credit phase to start, typically it can be requested once 5% of the savings are there,
* but still the bank decides when it grants the credit.
* * there are monthly costs for house savings
* * there is an initial fee for a house savings contract (eg. 1 .. 2 %)
* * there are incentives by the government
*/
export class HouseSavings extends Account {
constructor(name, totalSum, payment, initialFeeRate, ownInterestRate, ownVsCredit, creditInterestRate) {
super(name);
this.payment = payment;
this.ownVsCredit = ownVsCredit;
this.totalSum = totalSum;
this.ownInterests = new Interests(ownInterestRate);
this.creditInterests = new Interests(creditInterestRate);
this.feeToPay = initialFeeRate / 100.0 * totalSum;
this.remainingFee = this.feeToPay;
this.saved = 0.0;
this.credit = 0.0;
this.accumulatedSavingInterests = 0.0;
this.accumulatedCreditInterests = 0.0;
this.phase = "initial";
this.value = 0.0;
}
nextMonth() {
// first time we get nextMonth call, switch to saving phase
if (this.phase == "initial") {
this.phase = "saving";
}
if (this.phase == "saving") {
var saving = this.payment;
if (this.remainingFee > 0.0) {
if (this.payment < this.remainingFee) {
this.remainingFee -= this.payment;
saving = 0.0;
} else {
saving -= this.remainingFee;
this.remainingFee = 0.0;
}
}
var interests = this.ownInterests.perMonth(this.saved);
this.accumulatedSavingInterests += interests;
this.saved += saving + interests;
this.value = this.saved;
if (this.value >= this.ownVsCredit / 100.0 * this.totalSum) {
this.phase = "credit";
this.credit = (1 - this.ownVsCredit / 100.0) * this.totalSum;
console.log("house savings ready for credit phase");
}
} else if (this.phase == "credit") {
var interests = this.creditInterests.perMonth(this.credit);
this.accumulatedCreditInterests += interests;
this.credit = this.credit - this.payment + this.creditInterests.perMonth(this.credit);
this.value = this.credit;
if (this.credit <= 0.0) {
this.phase = "done";
}
} else {
this.value = 0.0;
}
}
stop(useTotal=false) {
if (this.phase == "initial") {
this.phase = "credit";
this.value = this.remainingFee;
} else if (this.phase == "saving") {
this.phase = "credit"
if (this.remainingFee > 0.0) {
this.value = this.remainingFee;
this.credit = 0;
this.totalSum = 0;
} else {
if (useTotal) {
this.credit = this.totalSum - this.value;
this.value = this.credit;
} else {
this.credit = this.value * (1 - this.ownVsCredit/100.0) / (this.ownVsCredit/100.0)
this.totalSum = this.value + this.credit
this.value = this.credit;
}
}
} else if (this.phase == "done") {
return;
}
}
getDescription() {
return "Total sum: " + formatMoney(this.totalSum) + "\n" +
"Savings interest rate: " + this.ownInterests.ratePerYear + " %/a\n" +
"Credit interest rate: " + this.creditInterests.ratePerYear + " %/a\n" +
"Payment: " + formatMoney(this.payment);
}
getSummary() {
return "Saving interests: " + formatMoney(this.accumulatedSavingInterests) + "\n" +
"Credit interests: " + formatMoney(this.accumulatedCreditInterests) + "\n" +
"Cost: " + formatMoney(this.getCost());
}
getCost() {
return this.feeToPay + this.accumulatedCreditInterests - this.accumulatedSavingInterests;
}
}