-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsavings_rate.py
1237 lines (1065 loc) · 40.8 KB
/
savings_rate.py
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MMM Savings Rate is an application that can parse spreadsheets and
# use the data to calculate and plot a user's savings rate over time.
# The application was inspired by Mr. Money Mustache and it uses his
# methodology to make the calculations.
# Copyright (C) 2016 Brad Busenius
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <https://www.gnu.org/licenses/gpl-3.0.html/>.
import configparser
import csv
import datetime
import json
import os
from collections import OrderedDict
from decimal import Decimal, InvalidOperation
import fi
import pandas as pd
import requests
from bokeh.embed import components
from bokeh.models import ColumnDataSource, DatetimeTickFormatter, HoverTool
from bokeh.plotting import figure, output_file, show
from dateutil import parser
from file_parsing import are_numeric, clean_strings, is_number_of_some_sort
REQUIRED_INI_ACCOUNT_OPTIONS = {'Users': ['self']}
REQUIRED_INI_USER_OPTIONS = {
'Sources': [
'pay',
'pay_date',
'gross_income',
'employer_match',
'taxes_and_fees',
'savings',
'savings_accounts',
'savings_date',
'war',
],
}
class SRConfig:
"""
Class for loading configurations to pass to the
savings rate object.
Args:
user_conf_dir: path to a directory of user .ini
configuration files.
user_conf: a string name of a user .ini file.
user: optional, an integer representing the
unique id of a user. This is only needed when
running as part of an application connected to
a database. Not necessary when running with
csv files.
enemies: optional, a list of integers representing
the unique ids of user enemies. Like the above, this
is only needed when running as part of an application
connected to a database. Not necessary when running
with csv files.
test: boolean, defaults to False. Set
to True for testing the account-config.ini
under a different name.
test_file: string, name of an .ini to test.
Defaults to None and should only be set if
test=True.
"""
def __init__(
self,
user_conf_dir=None,
user_conf=None,
user=None,
enemies=None,
test=False,
test_file=None,
):
self.user_conf_dir = user_conf_dir
self.user_ini = user_conf_dir + user_conf
self.is_test = test
self.test_account_ini = test_file
self.load_account_config()
self.fred_api_key = ''
self.fred_url = ''
self.notes = ''
self.percent_fi_notes = ''
self.show_average = True
self.goal = False
self.fi_number = False
self.total_balances = False
self.load_user_config()
# Set the date format to use
self.date_format = '%Y-%m-%d'
def load_account_config(self):
"""
Wrapper function, loads configurations from
ini files.
"""
return self.load_account_config_from_ini()
def load_user_config(self):
"""
Wrapper function, load the user configurations
from .ini files or the db
"""
config = self.load_user_config_from_ini()
return config
def load_user_config_from_ini(self):
"""
Get user configurations from .ini files.
"""
# Get the user configurations
self.user_config = configparser.RawConfigParser()
config = self.user_config.read(self.user_ini)
# Raise an exception if a user config
# cannot be found
if config == []:
raise FileNotFoundError(
'The user config is an empty []. Create a user config file and make sure it\'s referenced in account-config.ini.'
)
# Validate the configparser config object
self.validate_user_ini()
# Source of and file type of savings data (.xlsx of .csv)
self.savings_source = self.user_config.get('Sources', 'savings')
self.savings_source_type = self.file_extension(self.savings_source)
# Source and file type of income data (.xlsx of .csv)
self.pay_source = self.user_config.get('Sources', 'pay')
self.pay_source_type = self.file_extension(self.pay_source)
# Set war mode
self.war_mode = self.user_config.getboolean('Sources', 'war')
# Other spreadsheet columns we care about
self.gross_income = self.user_config.get('Sources', 'gross_income')
self.employer_match = self.user_config.get('Sources', 'employer_match')
self.taxes_and_fees = self.user_config.get('Sources', 'taxes_and_fees')
self.savings_accounts = self.user_config.get('Sources', 'savings_accounts')
self.pay_date = self.user_config.get('Sources', 'pay_date')
self.savings_date = self.user_config.get('Sources', 'savings_date')
# Required columns for spreadsheets
# Column names set in the config must exist in the .csv when we load it
# These values are used later to ensure mappings to the .csv are correct
self.required_income_columns = set(
[self.gross_income, self.employer_match, self.pay_date]
).union(clean_strings(set(self.taxes_and_fees.split(','))))
self.required_savings_columns = set([self.savings_date]).union(
set(clean_strings(self.savings_accounts.split(',')))
)
self.load_fred_url_config()
self.load_fred_api_key_config()
self.load_notes_config()
self.load_show_average_config()
self.load_goal_config()
self.load_fi_number_config()
self.load_total_balances_config()
def load_notes_config(self):
"""
Loads the notes config from an .ini if it exists.
"""
try:
self.notes = self.user_config.get('Sources', 'notes')
except (configparser.NoOptionError):
self.notes = ''
try:
self.percent_fi_notes = self.user_config.get('Sources', 'percent_fi_notes')
except (configparser.NoOptionError):
self.percent_fi_notes = ''
def load_total_balances_config(self):
"""
Loads the config for a header column where users store
their total account balances.
"""
try:
self.total_balances = self.user_config.get('Sources', 'total_balances')
except (configparser.NoOptionError):
self.total_balances = False
def load_fred_url_config(self):
"""
Loads the config from .ini if it exists.
"""
try:
self.fred_url = self.user_config.get('Sources', 'fred_url')
except (configparser.NoOptionError):
self.fred_url = ''
def load_fred_api_key_config(self):
"""
Loads the config from .ini if it exists.
"""
try:
self.fred_api_key = self.user_config.get('Sources', 'fred_api_key')
except (configparser.NoOptionError):
self.fred_api_key = ''
def has_fred(self):
"""
Test if the needed config exists to enable FRED.
Returns:
bool
"""
return bool(self.fred_api_key and self.fred_url)
def load_goal_config(self):
"""
Savings rate goal the user is trying to hit.
Args:
None
Returns:
None
"""
try:
goal = self.user_config.get('Sources', 'goal')
try:
self.goal = float(goal)
except (ValueError):
print('The value for \'goal\' should be numeric, e.g. 65.')
except (configparser.NoOptionError):
self.goal = False
def load_show_average_config(self):
"""
Loads the config from .ini if it exists.
"""
try:
self.show_average = self.user_config.getboolean('Sources', 'show_average')
except (configparser.NoOptionError):
pass
def load_fi_number_config(self):
"""
FI number the user is trying to hit.
Args:
None
Returns:
None
"""
try:
fi_number = self.user_config.get('Sources', 'fi_number')
try:
self.fi_number = float(fi_number)
except (ValueError):
print('The value for \'fi_number\' should be numeric, e.g. 1000000.')
except (configparser.NoOptionError):
self.fi_number = False
def validate_user_ini(self):
"""
Minimum validation for the user
config.ini when running in 'ini' mode.
"""
# Required section and options
for section in REQUIRED_INI_USER_OPTIONS:
assert self.user_config.has_section(section), (
'[' + section + '] is a required section in the user config.ini.'
)
for option in REQUIRED_INI_USER_OPTIONS[section]:
assert self.user_config.has_option(section, option), (
'The "'
+ option
+ '" option is required in the ['
+ section
+ '] section of config.ini.'
)
def load_account_config_from_ini(self):
"""
Get the configurations from an .ini file.
Throw an exception if the file is lacking
required data.
"""
# Load the ini
self.account_config = configparser.RawConfigParser()
if not self.is_test:
account_config = self.account_config.read(
self.user_conf_dir + 'account-config.ini'
)
else:
try:
account_config = self.account_config.read(
self.user_conf_dir + self.test_account_ini
)
except (TypeError):
raise RuntimeError(
'If test=True, a test .ini must be provided. You must provide a value for test_file.'
)
# Raise an exception if the account_config comes back empty
if account_config == []:
raise FileNotFoundError(
'The account_config is an empty []. A file named, "account-config.ini" was not found. This file must exist.'
)
# Validate the ini file.
self.validate_account_ini()
# Crosswalk data for the main player if it
# exists, otherwise throw an exception.
self.user = self.account_config.get('Users', 'self').split(',')
# If enemies isn't in the account-config.ini
# set it to None.
try:
self.user_enemies = [
enemy.split(',')
for enemy in self.account_config.get('Users', 'enemies').split('|')
]
except (KeyError, configparser.NoOptionError):
self.user_enemies = None
# Set a log file (optional)
self.log = (
self.account_config.get('Dev', 'logfile')
if self.account_config.has_section('Dev')
else None
)
# Validate the data loaded from account-config.ini
self.validate_loaded_account_data()
def validate_account_ini(self):
"""
Minimum validation for account-config.ini.
"""
# Required sections
assert self.account_config.has_section(
'Users'
), '[Users] is a required section in account-config.ini.'
# Required options
assert self.account_config.has_option(
'Users', 'self'
), 'The "self" option is required in the [Users] section of account-config.ini.'
def validate_loaded_account_data(self):
"""
Validate the data loaded from
account-config.ini.
"""
assert (
len(self.user) == 3
), 'The "self" option in the [Users] section should have an id, name, and path to user config separated by commas.'
user_ids = set([])
main_user_id = self.user[0]
user_ids.add(main_user_id)
if self.user_enemies:
i = 1 # Self, already added
for enemy in self.user_enemies:
user_ids.add(enemy[0])
assert (
len(enemy) == 3
), 'The "enemies" option in account-config.ini is not set correctly.'
i += 1
assert len(user_ids) == i, 'Every user ID must be unique.'
def file_extension(self, string):
"""
Gets a file extension from a string that ends in a file name.
Args:
string (str): File name, e.g. foobar.txt.
Returns:
str: File extension, e.g. .txt.
"""
return os.path.splitext(string)[1]
class SavingsRate:
"""
Class for getting and calculating a monthly savings rate
based on information about monthly pay and spending.
"""
def __init__(self, config):
"""
Initialize the object with settings from the config file.
Args:
config: object
"""
# Load the configurations
self.config = config
# Load income and savings information
self.get_pay()
self.get_savings()
def test_columns(self, row, spreadsheet):
"""
Make sure the required columns are present for different
types of spreadsheets, ensure that what was mapped in the
config.ini exists as a column header in the spreadsheet.
Args:
row: a set representing column headers from a spreadsheet.
spreadsheet: string, the type of spreadsheet to validate.
Possible values are "income" or "savings".
Returns:
None, throws an AssertionError if spreadsheet column names
don't match what was set in the configuration. Raises a
ValueError if a bad argument is passed.
"""
required = {
'income': self.config.required_income_columns,
'savings': self.config.required_savings_columns,
}
if spreadsheet in required:
val = row.issuperset(required[spreadsheet])
else:
msg = (
'You passed an improper spreadsheet type to test_columns(). '
+ 'Possible values are "income" and "savings"'
)
raise ValueError(msg)
assert val is True, (
'The '
+ spreadsheet
+ ' spreadsheet is missing a column header. '
+ 'The following columns were configured: '
+ str(required[spreadsheet])
+ ' '
+ 'but these column headings were found in the spreadsheet: '
+ str(row)
)
def get_pay(self):
"""
Loads payment data from a .csv fle.
Args:
None
Returns:
"""
ext = self.config.pay_source_type
if ext == '.csv':
return self.load_pay_from_csv()
elif ext == '.xlsx':
return self.load_pay_from_xlsx()
else:
raise RuntimeError('Problem loading income information!')
def clean_num(self, number):
"""
Looks at numeric values to determine if they are numeric.
Converts empty strings and null values to 0.0. Acceptable
arguments are None, empty string, int, float, or decimal.
Args:
number: Float, int, decimal, empty string, or null value.
Returns:
float, int, or decimal
"""
try:
number = number.strip()
except (AttributeError):
pass
if number is None or number == '':
retval = 0.0
elif is_number_of_some_sort(number):
retval = number
else:
raise TypeError(
'A numeric value was expected. The argument passed was non-numeric.'
)
return retval
def load_pay_from_csv(self):
"""
Loads a paystub from a .csv file.
Args:
None
Returns:
None
"""
with open(self.config.pay_source) as csvfile:
retval = OrderedDict()
reader = csv.DictReader(csvfile)
count = 0
for row in reader:
# Make sure required columns are in the spreadsheet
self.test_columns(set(row.keys()), 'income')
date_string = row[self.config.pay_date]
unique_id = self.unique_id_from_date(date_string, count)[0]
retval[unique_id] = row
count += 1
self.income = retval
def load_pay_from_xlsx(self):
"""
Loads a paystub from an Excel stylesheet. Converts rows into a
format similar to what we get in csv.DictReader before crosswalking
them into the needed format.
Args:
None
Returns
None
"""
retval = OrderedDict()
df = pd.read_excel(self.config.pay_source, dtype=str, na_filter=False)
self.test_columns(set(df.columns.to_list()), 'income')
count = 0
for row in df.itertuples():
date_string = row.__getattribute__(self.config.pay_date)
unique_id = self.unique_id_from_date(date_string, count)[0]
columns = list(df.columns)
row_dict = dict(zip(columns, row[1:]))
retval[unique_id] = row_dict
count += 1
self.income = retval
def get_savings(self):
"""
Get savings data from designated source.
Args:
None
"""
ext = self.config.pay_source_type
if ext == '.csv':
return self.load_savings_from_csv()
elif ext == '.xlsx':
return self.load_savings_from_xlsx()
else:
raise RuntimeError('Problem loading savings information!')
def load_savings_from_csv(self):
"""
Loads savings data from a .csv file.
Args:
None
Returns:
None
"""
with open(self.config.savings_source) as csvfile:
retval = OrderedDict()
reader = csv.DictReader(csvfile)
count = 0
for row in reader:
# Make sure required columns are in the spreadsheet
self.test_columns(set(row.keys()), 'savings')
date_string = row[self.config.savings_date]
unique_id = self.unique_id_from_date(date_string, count)[0]
retval[unique_id] = row
count += 1
self.savings = retval
def unique_id_from_date(self, date_string, count):
"""
Dates are important when calculating monthly savings rates.
This function formats the date and generates a unique id. Both
of these are used to keep track of and organize savings and
income related data.
Args:
date_string: date string.
count: int
Returns:
tuple(str, str): where the first item is a unique id and the
second item is a date string.
"""
dt_obj = parser.parse(date_string)
date = dt_obj.strftime(self.config.date_format)
unique_id = date + '-' + str(count)
return (unique_id, date)
def load_savings_from_xlsx(self):
"""
Loads savings data from an Excel stylesheet. Converts rows into a
format similar to what we get in csv.DictReader before crosswalking
them into the needed format.
Args:
None
Returns
None
"""
sdata = OrderedDict()
df = pd.read_excel(self.config.savings_source, dtype=str, na_filter=False)
self.test_columns(set(df.columns.to_list()), 'savings')
count = 0
for row in df.itertuples():
date_string = row.__getattribute__(self.config.savings_date)
unique_id = self.unique_id_from_date(date_string, count)[0]
columns = list(df.columns)
row_dict = dict(zip(columns, row[1:]))
sdata[unique_id] = row_dict
count += 1
self.savings = sdata
def get_tax_headers_for_parsing(self):
"""
Get the .csv column headers used for tracking taxes and fees
in the income related spreadsheet.
Args:
None
Returns:
Set of accounts used for tracking savings.
"""
return set(self.config.user_config.get('Sources', 'taxes_and_fees').split(','))
def get_monthly_data(self):
"""
Crosswalk the data for income and spending into a structure
representing one month time periods. Returns an OrderedDict.
Args:
None
Returns:
OrderedDict
Example return data:
OrderedDict([
('2015-02', {'income': [Decimal('4833.34')],
'employer_match': [Decimal('120.84')],
'taxes_and_fees': [Decimal('814.70')],
'notes': {''},
'savings': [Decimal('1265.85')],
'percent_fi_notes': {''},
'percent_fi': [4.450954]}),
('2015-03', {'income': [Decimal('4833.34')],
'employer_match': [Decimal('120.84')],
'taxes_and_fees': [Decimal('814.70')],
'notes': {''},
'savings': [Decimal('1115.85')],
'percent_fi_notes': {''},
'percent_fi': [4.500051999999999]}),
"""
income = self.income.copy()
savings = self.savings.copy()
# For this data structure
date_format = '%Y-%m'
# Column headers used for tracking taxes and fees
taxes = self.get_tax_headers_for_parsing()
# Dataset to return
sr = OrderedDict()
# Loop over income and savings
for payout in income:
# Structure the date
date_string = str(income[payout][self.config.pay_date])
date_string_obj = parser.parse(date_string)
new_date_string = date_string_obj.strftime(self.config.date_format)
pay_dt_obj = datetime.datetime.strptime(
new_date_string, self.config.date_format
)
pay_month = pay_dt_obj.strftime(date_format)
# Get income data for inclusion, cells containing blank
# strings are converted to zeros.
income_gross = (
0
if income[payout][self.config.gross_income] == ''
else income[payout][self.config.gross_income]
)
income_match = (
0
if income[payout][self.config.employer_match] == ''
else income[payout][self.config.employer_match]
)
income_taxes = [
0 if income[payout][val] == '' else income[payout][val]
for val in clean_strings(self.config.taxes_and_fees.split(','))
]
# Validate income spreadsheet data
assert are_numeric([income_gross, income_match]) is True
assert are_numeric(income_taxes) is True
# If the data passes validation, convert it (strings to Decimal objects)
gross = Decimal(income_gross)
employer_match = Decimal(income_match)
taxes = sum([Decimal(tax) for tax in income_taxes])
# ---Build the datastructure---
# Set main dictionary key, encapsulte data by month
sr.setdefault(pay_month, {})
# Set income related qualities for the month
sr[pay_month].setdefault('income', []).append(gross)
sr[pay_month].setdefault('employer_match', []).append(employer_match)
sr[pay_month].setdefault('taxes_and_fees', []).append(taxes)
# Add an income note if there is one
try:
inote = income[payout][self.config.notes]
except (KeyError):
inote = ''
sr[pay_month].setdefault('notes', set()).add(inote)
if 'savings' not in sr[pay_month]:
for transfer in savings:
tran_date_string = str(savings[transfer][self.config.savings_date])
tran_date_string_obj = parser.parse(tran_date_string)
tran_month = tran_date_string_obj.strftime(date_format)
if tran_month == pay_month:
# Define savings data for inclusion
bank = [
savings[transfer][val]
for val in clean_strings(
self.config.savings_accounts.split(',')
)
if savings[transfer][val] != ''
]
# Validate savings spreadsheet data
assert are_numeric(bank) is True
# If the data passes validation, convert it (strings to Decimal objects)
money_in_the_bank = sum(
[Decimal(investment) for investment in bank]
)
# Set spending related qualities for the month
sr[pay_month].setdefault('savings', []).append(
money_in_the_bank
)
# Add a savings note if there is one
try:
snote = savings[transfer][self.config.notes]
except (KeyError):
snote = ''
sr[pay_month].setdefault('notes', set()).add(snote)
# % FI note
try:
pfi_note = savings[transfer][self.config.percent_fi_notes]
except (KeyError):
pfi_note = ''
sr[pay_month].setdefault('percent_fi_notes', set()).add(
pfi_note
)
# Calculate % FI
if self.config.total_balances:
total_balances = savings[transfer][
self.config.total_balances
]
if total_balances and self.config.fi_number:
percent_fi = fi.get_percentage(
total_balances, self.config.fi_number
)
sr[pay_month].setdefault('percent_fi', []).append(
percent_fi
)
else:
sr[pay_month].setdefault('percent_fi', []).append(
float('nan')
)
return sr
def get_monthly_savings_rates(self, test_data=False):
"""
Calculates the monthly savings rates over a period of time.
Args:
test_data: OrderedDict or boolean, for passing in test data.
Defaults to false.
Returns:
list: a list of tuples where each tuple contains:
- datetime object: python date object.
- Decimal: The savings rate for the month.
- set: strings, optional notes or event.
- float: % FI if enabled.
- set: string note related to the % FI plot.
"""
if not test_data:
monthly_data = self.get_monthly_data()
else:
monthly_data = test_data
monthly_savings_rates = []
for month in monthly_data:
pay = fi.take_home_pay(
sum(monthly_data[month]['income']),
sum(monthly_data[month]['employer_match']),
monthly_data[month]['taxes_and_fees'],
)
savings = (
sum(monthly_data[month]['savings'])
if 'savings' in monthly_data[month]
else 0
)
try:
note = monthly_data[month]['notes']
except (KeyError):
note = ''
spending = pay - savings
try:
srate = fi.savings_rate(pay, spending)
except (InvalidOperation):
srate = Decimal(0)
try:
percent_fi = monthly_data[month]['percent_fi']
except (KeyError):
percent_fi = None
try:
pfi_note = monthly_data[month]['percent_fi_notes']
except (KeyError):
pfi_note = ''
date = datetime.datetime.strptime(month, '%Y-%m')
monthly_savings_rates.append((date, srate, note, percent_fi, pfi_note))
return monthly_savings_rates
def get_us_average(self, monthly_rates, timeout=4):
"""
Get the average monthly savings rates. The data is
pulled from the Federal Reserve Economic Data, FRED
by the Research Department at the Federal Reserve
Bank of St. Louis
Args:
monthly_rates: a list of tuples where the
first item in each tupal is a python date
object and the second item in each tuple
is the savings rate for that month. These
are the savings rates that belong to the
user.
timeout: float or int.
Returns:
A list of tuples where the first item in each
tupal is a python date object and the second
item in each tuple is the savings rate for
that month.
"""
if self.config.has_fred():
start_date = (
monthly_rates[0:1][0][0]
.replace(day=1)
.strftime(self.config.date_format)
)
end_date = (
monthly_rates[-1:][0][0]
.replace(day=1)
.strftime(self.config.date_format)
)
url = self.config.fred_url
params = {
'api_key': self.config.fred_api_key,
'observation_start': start_date,
'observation_end': end_date,
}
try:
response = requests.get(f'{url}', params=params, timeout=timeout)
except (
requests.exceptions.MissingSchema,
requests.exceptions.InvalidSchema,
) as e:
print(f'Bad url for fred_url. {str(e)}')
return []
try:
if response.status_code == 400 or response.status_code == 404:
raise requests.exceptions.HTTPError()
response_json = response.json()
except (
AttributeError,
json.decoder.JSONDecodeError,
requests.exceptions.HTTPError,
requests.exceptions.Timeout,
):
print('Could not retrieve a valid response from FRED.')
if response.text:
response_txt = response.text.replace('\\', '')
print(f'Bad request: {response_txt}')
return []
average_us_savings_rates = []
for row in response_json['observations']:
date_obj = datetime.datetime.strptime(
row['date'], self.config.date_format
)
savings_rate = Decimal(row['value'])
monthly_rate = (date_obj, savings_rate)
average_us_savings_rates.append(monthly_rate)
return average_us_savings_rates
return []
def average_monthly_savings_rates(self, monthly_rates):
"""
Calculates the average monthly savings rate
for a period of months.
Args:
monthly_rates: a list of tuples where the
first item in each tupal is a python date
object and the second item in each tuple
is the savings rate for that month.
Returns:
float
"""
nums = [rate[1] for rate in monthly_rates]
return float(Decimal(sum(nums)) / len(nums))
class Plot:
"""
A class for plotting the monthly savings rates for an individual
and his or her enemies.
"""
def __init__(self, user):
"""
Initialize the object.
"""
# Load the user as a savings_rate object
self.user = user
# Colors for plotting enemy graphs
self.colors = [
'#B30000',
'#E34A33',
'#8856a7',
'#4D9221',
'#404040',
'#9E0142',
'#0C2C84',
'#810F7C',
]
def plot_savings_rates(self, monthly_rates, embed=False):
"""
Plots the monthly savings rates for a period of time.
Args:
monthly_rates: a list of tuples where the first item in each