-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
467 lines (392 loc) · 21.8 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Xml;
namespace DepositTermCalc
{
internal class Program
{
class Deposit
{
public DateTime? EndDate { get; set; }
public DateTime? WantedEndDate { get; set; }
public DateTime? StartDate { get; set; }
public bool IsHoldInCash { get; set; }
public decimal Amount { get; set; }
public string Name { get; set; } = "";
public bool WasEndedBecauseOfMaxDurationLimit { get; set; }
public Deposit(decimal amount)
{
Amount = amount;
}
}
static void Main(string[] args)
{
string PreprocessForParsing(string line)
{
int index = line.IndexOf(" --");
if (index != -1)
line = line.Substring(0, index);
else if (line.StartsWith("--")) line = "";
return line;
}
decimal ParsePercent(string s)
{
s = s.Trim();
Trace.Assert(s.EndsWith("%"));
s = s.Substring(0, s.Length - 1);
return decimal.Parse(s);
}
const bool allowMerging = true;
// for unified decimal numbers parsing
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
var dtCulture = CultureInfo.GetCultureInfo("ru-RU");
var lines = File.ReadAllLines(args[0]).Select(PreprocessForParsing).ToList();
var startDt = DateTime.Parse(lines[0], dtCulture);
var diffPerMonth = decimal.Parse(lines[1]);
var startingBalance = decimal.Parse(lines[2]);
var maxDepositDurationMonths = int.Parse(lines[3]);
var taxPercent = ParsePercent(lines[5]);
var annualInflationPercent = ParsePercent(lines[6]);
// do not apply inflation to both deposits and diffPerMonth,
// choose only one,
// for reality diffPerMonth is chosen
var depositPercents = lines[4].Split(new[]{' ' }, StringSplitOptions.RemoveEmptyEntries).Select(ParsePercent).Prepend(0m)
.Select(x =>
(100m + x * (1m - (x == 0 ? 0 : taxPercent / 100m))) - 100m).ToList();
decimal GetAmountWithPercent(Deposit deposit, DateTime? endDate = null)
{
endDate = endDate ?? deposit.EndDate;
if (deposit.StartDate == null || endDate == null || depositPercents.Count == 0)
return deposit.Amount;
var months = GetDepositMonthDiff(endDate.Value, deposit.StartDate.Value);
var annualPercent = depositPercents[Math.Min(months, depositPercents.Count - 1)];
return deposit.Amount * (1m + annualPercent / 100m / 365m * (decimal)(endDate - deposit.StartDate).Value.TotalDays);
}
decimal WithdrawalToInitialAmount(Deposit deposit, decimal amount, DateTime? endDate = null)
{
endDate = endDate ?? deposit.EndDate;
if (deposit.StartDate == null || endDate == null || depositPercents.Count == 0)
return amount;
var months = GetDepositMonthDiff(endDate.Value, deposit.StartDate.Value);
var annualPercent = depositPercents[Math.Min(months, depositPercents.Count - 1)];
return amount / (1m + annualPercent / 100m / 365m * (decimal)(endDate - deposit.StartDate).Value.TotalDays);
}
if (lines[7] != "") throw new ArgumentException();
var oldDeposits = lines.Skip(8).Select(s => s.Split(new[] { ' ' }, 3))
.Select(ss => new Deposit(decimal.Parse(ss[1])) { EndDate = CorrectIfWeekend(DateTime.Parse(ss[0], dtCulture)), Name = ss.Length >= 3 ? ss[2] : ""}).OrderBy(x => x.EndDate)
.ToList();
// output in usual format
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InstalledUICulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InstalledUICulture;
CultureInfo.CurrentCulture = CultureInfo.InstalledUICulture;
CultureInfo.CurrentUICulture = CultureInfo.InstalledUICulture;
decimal newDepositsBalance = 0;
var notReturnedDeposits = new List<Deposit>();
var returnedNewDeposits = new List<Deposit>();
decimal balance = startingBalance;
DateTime dt = startDt;
var oldDepositsSet = oldDeposits.ToHashSet(); // remove deposits while processing
int newDepositsCounter = 0;
DateTime CorrectIfWeekend(DateTime dt)
{
return dt.DayOfWeek switch
{
DayOfWeek.Saturday => dt.AddDays(2),
DayOfWeek.Sunday => dt.AddDays(1),
_ => dt
};
}
decimal InflatedDiffPerMonth() =>
diffPerMonth > 0
? diffPerMonth
: diffPerMonth * (annualInflationPercent / 100m / 365m * (decimal)(dt - startDt).TotalDays + 1m);
void DepositIfOverbalance()
{
var overBalance = balance + InflatedDiffPerMonth();
if (overBalance > -InflatedDiffPerMonth() / 10m) // must keep at least 1 month of cash
{
notReturnedDeposits.Add(new Deposit(overBalance) { StartDate = dt, Name = "new#" + (++newDepositsCounter) });
newDepositsBalance += overBalance;
balance -= overBalance;
}
}
DepositIfOverbalance();
void Rewind(DateTime newDt)
{
balance += InflatedDiffPerMonth() / 30m * (decimal)(newDt - dt).TotalDays;
dt = newDt;
}
while (dt < startDt.AddYears(10))
{
var depositsPool = oldDepositsSet.Concat(notReturnedDeposits)
.Select(deposit => (deposit, end: (DateTime?)CorrectIfWeekend(deposit.EndDate ?? deposit.StartDate.Value.AddDays(30 * maxDepositDurationMonths))))
.OrderBy(x => x.end)
.ToList();
var nextDeposit = depositsPool.FirstOrDefault();
var withdrawalMaxDt = CorrectIfWeekend(dt.AddDays((int)Math.Max(0, (double) ((balance + InflatedDiffPerMonth() / 2) / (-InflatedDiffPerMonth() / 30m)))));
if (nextDeposit.end < withdrawalMaxDt || (nextDeposit.end - withdrawalMaxDt)?.TotalDays <= 7)
{
Rewind(nextDeposit.end.Value);
var amount = nextDeposit.deposit.Amount;
if (nextDeposit.deposit.EndDate == null)
{
// this is our new deposit, apply percents
amount = GetAmountWithPercent(nextDeposit.deposit, dt);
// we keep only initial amount in this balance (no percents taken into account)
newDepositsBalance -= nextDeposit.deposit.Amount;
notReturnedDeposits.Remove(nextDeposit.deposit);
nextDeposit.deposit.EndDate = dt;
nextDeposit.deposit.WasEndedBecauseOfMaxDurationLimit = true;
returnedNewDeposits.Add(nextDeposit.deposit);
}
else oldDepositsSet.Remove(nextDeposit.deposit);
balance += amount;
DepositIfOverbalance();
}
else
{
Rewind(withdrawalMaxDt);
var overBalance = balance + InflatedDiffPerMonth();
// it can't be >= 0 because all previous overbalance we already put into deposits
// and some more time passed after than
Trace.Assert(overBalance <= 0);
decimal left = -overBalance;
var minLeft = -InflatedDiffPerMonth() / 10;
bool earlyExit = false;
while (left > minLeft && newDepositsBalance > 0.001m)
{
var deposit = notReturnedDeposits.First();
DateTime withdrawalDate;
{
int depositDays = (int)(dt - deposit.StartDate.Value).TotalDays;
// try to add more days
int ceil = (depositDays / 30 + 1) * 30;
int cashForDays = Math.Max(0, (int)((balance + InflatedDiffPerMonth() / 30m * 5m) / (-InflatedDiffPerMonth() / 30m)) - 1);
int prevCashForDays;
DateTime endOfCashDate;
do
{
prevCashForDays = cashForDays;
endOfCashDate = CorrectIfWeekend(dt.AddDays(cashForDays));
decimal balanceChangeTillEndOfCash = depositsPool.TakeWhile(x => x.end <= endOfCashDate).Select(x => GetAmountWithPercent(x.deposit, x.end)).DefaultIfEmpty().Sum();
cashForDays = Math.Max(0, (int)((balance + balanceChangeTillEndOfCash + InflatedDiffPerMonth() / 30m * 5m) / (-InflatedDiffPerMonth() / 30m)) - 1);
}
while (cashForDays != prevCashForDays);
// initially I thought to use it for ceil check
// but if we can wait why bother?
if (depositsPool.Count > 0 && endOfCashDate >= depositsPool.First().end)
{
Rewind(depositsPool.First().end.Value);
earlyExit = true;
break;
}
int floor = depositDays / 30 * 30;
if (cashForDays >= ceil - depositDays)
depositDays = ceil;
else
depositDays = floor;
//depositDays = ceil - depositDays <= depositDays - floor && ceil - depositDays <= 10 ? ceil : floor;
withdrawalDate = CorrectIfWeekend(deposit.StartDate.Value.AddDays(depositDays));
}
var incomingTillWithdrawal = depositsPool.TakeWhile(x=>x.end<=withdrawalDate).Select(x => GetAmountWithPercent(x.deposit, x.end)).DefaultIfEmpty().Sum();
var leftThisCycle = left - incomingTillWithdrawal;
if (leftThisCycle >= minLeft)
{
bool isHoldInCash = (withdrawalDate - deposit.StartDate.Value).TotalDays < 30;
decimal depositAmount;
if (isHoldInCash)
{
// can't be a real deposit so better use cash from most recent deposit instead
Trace.Assert(notReturnedDeposits.First().StartDate >= deposit.StartDate);
deposit = notReturnedDeposits.Last();
withdrawalDate = dt;
depositAmount = deposit.Amount;
}
else depositAmount = GetAmountWithPercent(deposit, withdrawalDate);
decimal taken = Math.Min(Math.Min(left, leftThisCycle), depositAmount);
left -= taken;
leftThisCycle -= taken;
if (depositAmount - taken < -InflatedDiffPerMonth() / 10m)
taken = depositAmount; // don't leave small deposits
balance += taken;
var takenWithoutPercent = !isHoldInCash ? WithdrawalToInitialAmount(deposit, taken, withdrawalDate) : taken;
newDepositsBalance -= takenWithoutPercent;
if (taken == depositAmount)
{
notReturnedDeposits.Remove(deposit);
}
else
{
deposit.Amount -= takenWithoutPercent;
deposit = new Deposit(takenWithoutPercent) { StartDate = deposit.StartDate, Name = "new#" + (++newDepositsCounter) };
}
deposit.EndDate = withdrawalDate;
deposit.WantedEndDate = dt;
deposit.IsHoldInCash = isHoldInCash;
var dd = returnedNewDeposits.FirstOrDefault(x => x.StartDate == deposit.StartDate && x.EndDate == deposit.EndDate);
if (dd != null && allowMerging)
{
dd.Amount += deposit.Amount;
if (dd.WantedEndDate != deposit.WantedEndDate)
dd.WantedEndDate = null;
}
else
returnedNewDeposits.Add(deposit);
}
if (incomingTillWithdrawal > 0 && leftThisCycle <= minLeft)
{
Rewind(depositsPool.First().end.Value);
earlyExit = true;
break;
}
}
if (left > minLeft && !earlyExit)
{
if (nextDeposit.deposit == null)
{
Console.WriteLine($"Enough money till {dt.AddDays((double) (balance / (-InflatedDiffPerMonth() / 30m))):d}");
break;
}
else if (nextDeposit.deposit.EndDate < nextDeposit.end.Value)
{
if (balance < 0)
Console.WriteLine($"Gap from {dt:d} {balance:F0}");
}
else
{
var nextDt = nextDeposit.end.Value;
var prevDt = dt;
Rewind(nextDt);
if (balance < 0)
Console.WriteLine($"Gap from {prevDt:d} till {nextDt:d}: {balance:F0}");
}
}
}
}
Debug.Assert(Math.Abs(newDepositsBalance) <= 0.001m);
// if set to false true balances may be different from expected above
// because of different real and wanted deposit end dates
OutputSimulation(false);
void OutputSimulation(bool useWantedEndDate)
{
balance = startingBalance;
dt = startDt;
var events = oldDeposits
.Where(x => x.StartDate != null)
.Concat(returnedNewDeposits)
.Select(d => (start: true, deposit: d, dt: d.StartDate.Value))
.Concat(oldDeposits.Concat(returnedNewDeposits).Select(d => (start: false, deposit: d, dt: (useWantedEndDate ? d.WantedEndDate ?? d.EndDate : d.EndDate).Value)))
.OrderBy(x => x.dt)
.ThenBy(x => x.start ? 1 : 0)
.ToList();
int eventIndex;
for (eventIndex = 0; eventIndex < events.Count; eventIndex++)
{
var ev = events[eventIndex];
var d = ev.deposit;
bool isContinuation = eventIndex > 0 && events[eventIndex - 1].dt == ev.dt;
bool isContinued = eventIndex + 1 < events.Count && events[eventIndex+1].dt==ev.dt;
Rewind(ev.dt);
string dateSpaces = new string(' ', $"{dt:d}".Length);
string DateOrEmpty()
{
if (eventIndex <= 0 || dt != events[eventIndex - 1].dt)
return $"{dt:d}";
else
return dateSpaces;
}
Console.ForegroundColor = !isContinuation && balance < -InflatedDiffPerMonth() / 8 ? ConsoleColor.Red : ConsoleColor.DarkGray;
Console.WriteLine($"{dateSpaces} vv {balance:F0} vv");
Console.ForegroundColor = ConsoleColor.Gray;
if (ev.start)
{
balance -= d.Amount;
Console.ForegroundColor = ConsoleColor.Yellow;
Trace.Assert(d.StartDate==dt);
Console.Write($"{DateOrEmpty()} >> {d.Amount:F0} `{d.Name}`");
if (d.IsHoldInCash)
Console.Write($" [hold in cash {(d.EndDate-d.StartDate).Value.TotalDays} days]");
else
Console.Write($" {GetDepositMonthDiff(d.EndDate.Value, d.StartDate.Value)}m");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
bool first = true;
foreach (var r in oldDeposits.Concat(returnedNewDeposits).Where(x => x != d
&& x.EndDate >= d.EndDate.Value.AddDays(-7)
&& x.EndDate <= d.EndDate.Value.AddDays(7)
&& x.StartDate <= d.StartDate)
.OrderBy(x => x.StartDate))
{
if (first)
{
Console.Write($"{dateSpaces} can be added to deposits: ");
first = false;
}
else Console.Write(", ");
Console.Write(r.StartDate != null
? $"`{r.Name}` {GetDepositMonthDiff(r.EndDate.Value, r.StartDate.Value)}m {r.Amount:F0} {r.StartDate:d} till {r.EndDate:d}"
: $"{r.Amount:F0} till {r.EndDate:d}");
}
if (!first) Console.WriteLine();
}
else
{
balance += d.IsHoldInCash ? d.Amount : GetAmountWithPercent(d, d.EndDate);
Console.ForegroundColor = oldDeposits.Contains(d) ? ConsoleColor.Cyan : ConsoleColor.Green;
Trace.Assert(useWantedEndDate || d.EndDate == dt);
Console.Write($"{DateOrEmpty()} << {d.Amount:F0} `{d.Name}`");
if (d.StartDate != null) Console.Write($" from {d.StartDate:d}");
if (d.IsHoldInCash)
Console.Write($" [hold in cash {(d.EndDate - d.StartDate).Value.TotalDays} days]");
else if (d.StartDate != null)
Console.Write($" ({GetDepositMonthDiff(d.EndDate.Value, d.StartDate.Value)}m)");
if (d.WantedEndDate != null && d.WantedEndDate != d.EndDate)
{
if (useWantedEndDate)
Console.Write($", actual end {d.EndDate:d}");
else
Console.Write($", wanted end {d.WantedEndDate:d}");
}
if (d.WasEndedBecauseOfMaxDurationLimit)
Console.Write($", ended on max duration");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
}
decimal redThreshold = 0.3m;
if (useWantedEndDate) redThreshold = 0.1m;
Console.ForegroundColor =
!isContinued
&& (balance < -InflatedDiffPerMonth() * (1m - redThreshold)
|| balance > -InflatedDiffPerMonth() * (1m + redThreshold * 1.5m))
? ConsoleColor.Red
: ConsoleColor.DarkGray;
Console.WriteLine($"{dateSpaces} ^^ {balance:F0} ^^");
Console.ForegroundColor = ConsoleColor.Gray;
if (!isContinued) Console.WriteLine();
}
}
Console.ReadLine();
}
static int GetDepositMonthDiff(DateTime date1, DateTime date2)
{
double totalDays = (date1 - date2).TotalDays;
var r = (int) (totalDays / 30.0);
if (totalDays >= 28)
return Math.Max(r, GetCelanderMonthDiff2(date1, date2));
return r;
}
static int GetCelanderMonthDiff2(DateTime date1, DateTime date2)
{
return (((date1.Year - date2.Year) * 12) + date1.Month) - date2.Month;
}
}
}