-
Notifications
You must be signed in to change notification settings - Fork 4
/
calculator.py
1811 lines (1675 loc) · 82.4 KB
/
calculator.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
"""
PIT (personal income tax) Calculator class.
"""
# CODING-STYLE CHECKS:
# pycodestyle calculator.py
# pylint --disable=locally-disabled calculator.py
#
# pylint: disable=too-many-lines
# pylintx: disable=no-value-for-parameter,too-many-lines
import csv
import os
import json
import re
import copy
import numpy as np
import pandas as pd
import importlib
# Contrived example of generating a module named as a string
#full_module_name = "taxcalc.functions." + "net_salary_income"
# The file gets executed upon import, as expected.
#mymodule = importlib.import_module(full_module_name)
f = open('global_vars.json')
vars = json.load(f)
if vars['pit']:
#pit_function_names_file = 'taxcalc'+'/'+vars['pit_function_names_filename']
#f = open(pit_function_names_file)
#self.pit_function_names = json.load(f)
pit_oname = vars["pit_functions_filename"][:-3]
pit_imp_statement = "from taxcalc." + pit_oname + " import *"
exec(pit_imp_statement)
"""
from taxcalc.functions import (net_salary_income, net_rental_income,
income_business_profession,
total_other_income, gross_total_income,
itemized_deductions, deduction_10AA,
taxable_total_income,
tax_stcg_splrate, tax_ltcg_splrate,
tax_specialrates, current_year_losses,
brought_fwd_losses, agri_income, pit_liability)
"""
if vars['cit']:
#CIT_VAR_INFO_FILENAME = 'taxcalc/'+vars['cit_records_variables_filename']
#self.max_lag_years = vars['cit_max_lag_years']
cit_function_names_file = 'taxcalc/'+vars['cit_function_names_filename']
f = open(cit_function_names_file)
cit_function_names = json.load(f)
#print('self.cit_function_names ', self.cit_function_names)
cit_oname = vars["cit_functions_filename"][:-3]
cit_imp_statement = "from taxcalc." + cit_oname + " import *"
exec(cit_imp_statement)
"""
from taxcalc.corpfunctions import (total_other_income_cit, depreciation_PM,
corp_income_business_profession,
corp_GTI_before_set_off, GTI_and_losses,
cit_liability)
"""
if vars['vat']:
#vat_function_names_file = 'taxcalc/'+vars['vat_function_names_filename']
#f = open(vat_function_names_file)
#self.vat_function_names = json.load(f)
vat_oname = vars["vat_functions_filename"][:-3]
vat_imp_statement = "from taxcalc." + vat_oname + " import *"
exec(vat_imp_statement)
#print("global in calc ")
from taxcalc.policy import Policy
from taxcalc.records import Records
from taxcalc.corprecords import CorpRecords
from taxcalc.gstrecords import GSTRecords
from taxcalc.growfactors import GrowFactors
# import pdb
class Calculator(object):
"""
Constructor for the Calculator class.
Parameters
----------
policy: Policy class object
this argument must be specified and object is copied for internal use
records: Records class object
this argument must be specified and object is copied for internal use
corprecords: CorpRecords class object
this argument must be specified and object is copied for internal use
gstrecords: GSTRecords class object
this argument must be specified and object is copied for internal use
verbose: boolean
specifies whether or not to write to stdout data-loaded and
data-extrapolated progress reports; default value is true.
sync_years: boolean
specifies whether or not to synchronize policy year and records year;
default value is true.
Raises
------
ValueError:
if parameters are not the appropriate type.
Returns
-------
class instance: Calculator
Notes
-----
The most efficient way to specify current-law and reform Calculator
objects is as follows:
pol = Policy()
rec = Records()
grec = GSTRecords()
crec = CorpRecords()
# Current law
calc1 = Calculator(policy=pol, records=rec, corprecords=crec,
gstrecords=grec)
pol.implement_reform(...)
# Reform
calc2 = Calculator(policy=pol, records=rec, corprecords=crec,
gstrecords=grec)
All calculations are done on the internal copies of the Policy and
Records objects passed to each of the two Calculator constructors.
"""
# pylint: disable=too-many-public-methods
def __init__(self, policy=None, records=None, corprecords=None,
gstrecords=None, verbose=True, sync_years=True):
# pylint: disable=too-many-arguments,too-many-branches
#print("inside init of calc ")
f = open('global_vars.json')
vars = json.load(f)
self.verbose = vars['verbose']
verbose = self.verbose
self.records = records
self.corprecords = corprecords
self.gstrecords = gstrecords
if self.records is not None:
PIT_VAR_INFO_FILENAME = 'taxcalc/'+vars['pit_records_variables_filename']
pit_function_names_file = 'taxcalc'+'/'+vars['pit_function_names_filename']
f = open(pit_function_names_file)
self.pit_function_names = json.load(f)
pit_oname = vars["pit_functions_filename"][:-3]
pit_imp_statement = "import taxcalc." + pit_oname
exec(pit_imp_statement)
"""
from taxcalc.functions import (net_salary_income, net_rental_income,
income_business_profession,
total_other_income, gross_total_income,
itemized_deductions, deduction_10AA,
taxable_total_income,
tax_stcg_splrate, tax_ltcg_splrate,
tax_specialrates, current_year_losses,
brought_fwd_losses, agri_income, pit_liability)
"""
if self.corprecords is not None:
CIT_VAR_INFO_FILENAME = 'taxcalc/'+vars['cit_records_variables_filename']
self.max_lag_years = vars['cit_max_lag_years']
cit_function_names_file = 'taxcalc/'+vars['cit_function_names_filename']
f = open(cit_function_names_file)
self.cit_function_names = json.load(f)
cit_oname = vars["cit_functions_filename"][:-3]
cit_imp_statement = "import taxcalc." + cit_oname
exec(cit_imp_statement)
"""
from taxcalc.corpfunctions import (total_other_income_cit, depreciation_PM,
corp_income_business_profession,
corp_GTI_before_set_off, GTI_and_losses,
cit_liability)
"""
if self.gstrecords is not None:
VAT_VAR_INFO_FILENAME = 'taxcalc/'+vars['vat_records_variables_filename']
vat_function_names_file = 'taxcalc/'+vars['vat_function_names_filename']
f = open(vat_function_names_file)
self.vat_function_names = json.load(f)
vat_oname = vars["vat_functions_filename"][:-3]
vat_imp_statement = "import taxcalc." + vat_oname
exec(vat_imp_statement)
#from taxcalc.gstfunctions import (gst_liability_item)
gfactors=GrowFactors()
self.gfactors = gfactors
if isinstance(policy, Policy):
self.__policy = copy.deepcopy(policy)
else:
raise ValueError('must specify policy as a Policy object')
if self.records is not None:
if isinstance(records, Records):
self.__records = copy.deepcopy(records)
with open(PIT_VAR_INFO_FILENAME) as vfile:
self.vardict = json.load(vfile)
self.ATTRIBUTE_READ_VARS_PIT = list(k for k,
v in self.vardict['read'].items()
if v['attribute'] == 'Yes')
else:
raise ValueError('must specify records as a Records object')
if self.gstrecords is not None:
if isinstance(gstrecords, GSTRecords):
self.__gstrecords = copy.deepcopy(gstrecords)
with open(VAT_VAR_INFO_FILENAME) as vfile:
self.vardict = json.load(vfile)
self.ATTRIBUTE_READ_VARS_VAT = list(k for k,
v in self.vardict['read'].items()
if v['attribute'] == 'Yes')
else:
raise ValueError('must specify records as a GSTRecords object')
if self.corprecords is not None:
if isinstance(corprecords, CorpRecords):
self.__corprecords = copy.deepcopy(corprecords)
#self.max_lag_years
self.CROSS_YEAR_VARS = []
with open(CIT_VAR_INFO_FILENAME) as vfile:
self.vardict = json.load(vfile)
vfile.close()
for k, v in self.vardict["read"].items():
#print("key: ", x, "value: ", y)
if self.vardict["read"][k]["cross_year"]=='Yes':
self.CROSS_YEAR_VARS = self.CROSS_YEAR_VARS + [k]
self.ATTRIBUTE_READ_VARS_CIT = list(k for k,
v in self.vardict['read'].items()
if v['attribute'] == 'Yes')
else:
raise ValueError('must specify records as a CorpRecords object')
if self.records is not None:
#print('self.__policy.current_year ', self.__policy.current_year)
#print('self.__records.data_year ', self.__records.data_year)
#print('self.__records.current_year ', self.__records.current_year)
if self.__policy.current_year < self.__records.data_year:
self.__policy.set_year(self.__records.data_year)
current_year_is_data_year = (
self.__records.current_year == self.__records.data_year)
if sync_years and current_year_is_data_year:
if verbose:
print('You loaded data for ' +
str(self.__records.data_year) + '.')
if self.__records.IGNORED_VARS:
print('Your data include the following unused ' +
'variables that will be ignored:')
for var in self.__records.IGNORED_VARS:
print(' ' +
var)
while self.__records.current_year < self.__policy.current_year:
self.__records.increment_year()
if verbose:
print('Tax-Calculator startup automatically ' +
'extrapolated your data to ' +
str(self.__records.current_year) + '.')
if self.gstrecords is not None:
if self.__policy.current_year < self.__gstrecords.data_year:
self.__policy.set_year(self.__gstrecords.data_year)
current_year_is_data_year = (
self.__gstrecords.current_year == self.__gstrecords.data_year)
if sync_years and current_year_is_data_year:
if verbose:
print('You loaded data for ' +
str(self.__gstrecords.data_year) + '.')
if self.__gstrecords.IGNORED_VARS:
print('Your data include the following unused ' +
'variables that will be ignored:')
for var in self.__gstrecords.IGNORED_VARS:
print(' ' +
var)
while self.__gstrecords.current_year < self.__policy.current_year:
self.__gstrecords.increment_year()
if verbose:
print('Tax-Calculator startup automatically ' +
'extrapolated your data to ' +
str(self.__gstrecords.current_year) + '.')
if self.corprecords is not None:
if self.__policy.current_year < self.__corprecords.data_year:
self.__policy.set_year(self.__corprecords.data_year)
current_year_is_data_year = (
self.__corprecords.current_year == self.__corprecords.data_year)
if sync_years and current_year_is_data_year:
if verbose:
print('You loaded data for ' +
str(self.__corprecords.data_year) + '.')
if self.__corprecords.IGNORED_VARS:
print('Your data include the following unused ' +
'variables that will be ignored:')
for var in self.__corprecords.IGNORED_VARS:
print(' ' +
var)
while self.__corprecords.current_year < self.__policy.current_year:
self.__corprecords.increment_year()
if verbose:
print('Tax-Calculator startup automatically ' +
'extrapolated your data to ' +
str(self.__corprecords.current_year) + '.')
if self.records is not None:
assert self.__policy.current_year == self.__records.current_year
if self.gstrecords is not None:
assert self.__policy.current_year == self.__gstrecords.current_year
if self.corprecords is not None:
assert self.__policy.current_year == self.__corprecords.current_year
self.__stored_records = None
def set_current_year(self, year):
self.current_year = year
if self.records is not None:
self.__records.set_current_year(year)
if self.corprecords is not None:
self.__corprecords.set_current_year(year)
if self.gstrecords is not None:
self.__gstrecords.set_current_year(year)
def increment_year(self):
"""
Advance all embedded objects to next year.
"""
# store the current year values of loss and closing balance of
# fixed assets to be moved to next year
if self.corprecords is not None:
bf_loss={}
for i in range(1, self.max_lag_years):
bf_loss[i] = getattr(self.__corprecords, 'newloss'+str(i))
#bf_loss1 = self.__records.newloss1
#print(bf_loss)
cl_wdv = {}
for var in self.CROSS_YEAR_VARS:
cl_wdv[var] = getattr(self.__corprecords, 'Cl'+var[2:])
#cl_wdv_bld = self.__records.Cl_WDV_Bld
next_year = self.__policy.current_year + 1
self.__policy.set_year(next_year)
if self.records is not None:
self.__records.increment_year()
if self.gstrecords is not None:
self.__gstrecords.increment_year()
if self.corprecords is not None:
self.__corprecords.increment_year()
# populate the opening values of loss and opening balance of
# fixed assets from the previous year
if self.corprecords is not None:
for i in range(1, self.max_lag_years):
setattr(self.__corprecords, 'Loss_lag'+str(i), bf_loss[i])
#self.__records.Loss_lag1 = bf_loss1
for var in self.CROSS_YEAR_VARS:
setattr(self.__corprecords, var, cl_wdv[var])
#self.__records.Op_WDV_Bld = cl_wdv_bld
#self.__records.increment_year()
#self.__gstrecords.increment_year()
#self.__corprecords.increment_year()
def advance_to_year(self, year):
"""
The advance_to_year function gives an optional way of implementing
increment year functionality by immediately specifying the year
as input. New year must be at least the current year.
"""
#print("self.current_year ", self.current_year)
iteration = year - self.current_year
if iteration < 0:
raise ValueError('New current year must be ' +
'greater than current year!')
for _ in range(iteration):
self.increment_year()
assert self.current_year == year
def calc_all(self):
"""
Call all tax-calculation functions for the current_year.
"""
# pylint: disable=too-many-function-args,no-value-for-parameter
# conducts static analysis of Calculator object for current_year
if self.records is not None:
assert self.__records.current_year == self.__policy.current_year
if self.gstrecords is not None:
assert self.__gstrecords.current_year == self.__policy.current_year
if self.corprecords is not None:
assert self.__corprecords.current_year == self.__policy.current_year
if self.records is not None:
self.__records.zero_out_changing_calculated_vars()
if self.gstrecords is not None:
self.__gstrecords.zero_out_changing_calculated_vars()
if self.corprecords is not None:
self.__corprecords.zero_out_changing_calculated_vars()
# For now, don't zero out for corporate
# pdb.set_trace()
# Note that the order of calling these functions is important
# as some functions require values calculated by those before
# Corporate calculations
if self.corprecords is not None:
for i in range(len(cit_function_names)):
func_name = globals()[cit_function_names[str(i)]]
#print(self.cit_function_names[str(i)])
func_name(self.__policy, self.__corprecords)
# Individual calculations
# Note that the order of calling these functions is important
# as some functions require values calculated by those before
#f='net_salary_income("self.__policy", "self.__records")'
if self.records is not None:
for i in range(len(self.pit_function_names)):
#print('function name ', self.pit_function_names[str(i)])
func_name = globals()[self.pit_function_names[str(i)]]
#print(function_names[str(i)])
func_name(self.__policy, self.__records)
# GST calculations
if self.gstrecords is not None:
for i in range(len(self.vat_function_names)):
func_name = globals()[self.vat_function_names[str(i)]]
#print(function_names[str(i)])
func_name(self.__policy, self.__gstrecords)
"""
if self.gstrecords is not None:
# agg_consumption(self.__policy, self.__gstrecords)
# gst_liability_cereal(self.__policy, self.__gstrecords)
# gst_liability_other(self.__policy, self.__gstrecords)
gst_liability_item(self)
# gst_liability_item(self.__policy, self.__gstrecords)
# TODO: ADD: expanded_income(self.__policy, self.__records)
# TODO: ADD: aftertax_income(self.__policy, self.__records)
"""
def weighted_total_pit(self, variable_name):
"""
Return all-filing-unit weighted total of named Records variable.
"""
if self.records is not None:
return (self.array(variable_name) * self.array('weight')).sum()
def weighted_gst(self, variable_name):
"""
Return all-filing-unit weighted total of named GST Records variable.
"""
if self.gstrecords is not None:
return (self.garray(variable_name) * self.garray('weight'))
def weighted_total_gst(self, variable_name):
"""
Return all-filing-unit weighted total of named GST Records variable.
"""
if self.gstrecords is not None:
return (self.garray(variable_name) * self.garray('weight')).sum()
def weighted_cit(self, variable_name):
"""
Return all-filing-unit weighted total of named Corp Records variable.
"""
if self.corprecords is not None:
return (self.carray(variable_name) * self.carray('weight'))
def get_attribute_types(self, tax_type, attribute_index):
"""
Parameters
----------
tax_type : string
tax_type is either 'pit' or 'cit' or 'vat'.
attribute_index : int
This gives the index of the attribute variables to be extracted.
There may be multiple attribute variables and we only select
one of them. For example attributes variables could be 'Sector',
'Region', etc.
Raises
------
ValueError
if the record is not created.
Returns
-------
attribute type list. For example if attribute variable is 'Sector', the
attribute types in the dataset would be 'Banks', 'Oil &Gas', 'Hotels',
etc.
Note that 'All' will always be there as an attribute type if
even if there are no attribute variables
"""
attribute_data = []
if tax_type == 'pit':
if self.records is not None:
if len(self.ATTRIBUTE_READ_VARS_PIT) > 0:
attribute_data = list(getattr(self.__records,
self.ATTRIBUTE_READ_VARS_PIT[attribute_index]))
#print('attribute_data', attribute_data)
attribute_types = list(set(attribute_data))
#print('attribute_types', attribute_types)
else:
attribute_types = []
else:
msg = 'tax type record ="{}" is not initialized'
raise ValueError(msg.format(tax_type))
elif tax_type == 'cit':
if self.corprecords is not None:
if len(self.ATTRIBUTE_READ_VARS_CIT) > 0:
attribute_data = list(getattr(self.__corprecords,
self.ATTRIBUTE_READ_VARS_CIT[attribute_index]))
attribute_types = list(set(attribute_data))
else:
attribute_types = []
else:
msg = 'tax type record ="{}" is not initialized'
raise ValueError(msg.format(tax_type))
elif tax_type == 'vat':
if self.gstrecords is not None:
if len(self.ATTRIBUTE_READ_VARS_VAT) > 0:
attribute_data = list(getattr(self.__gstrecords,
self.ATTRIBUTE_READ_VARS_VAT[attribute_index]))
attribute_types = list(set(attribute_data))
else:
attribute_types = []
else:
msg = 'tax type record ="{}" is not initialized'
raise ValueError(msg.format(tax_type))
else:
msg = 'tax type ="{}" is not valid'
raise ValueError(msg.format(tax_type))
return (['All']+attribute_types, attribute_data)
def weighted_total_tax_dict(self, tax_type, variable_name):
"""
Return all-filing-unit weighted total of named tax variable.
"""
if tax_type == 'pit':
if self.records is not None:
tax_data = self.array(variable_name)
attribute_var = self.ATTRIBUTE_READ_VARS_PIT
(attribute_types, attribute_data) = self.get_attribute_types(tax_type, 0)
else:
msg = 'tax type record ="{}" is not initialized'
raise ValueError(msg.format(tax_type))
elif tax_type == 'cit':
if self.corprecords is not None:
tax_data = self.carray(variable_name)
attribute_var = self.ATTRIBUTE_READ_VARS_CIT
(attribute_types, attribute_data) = self.get_attribute_types(tax_type, 0)
else:
msg = 'tax type record ="{}" is not initialized'
raise ValueError(msg.format(tax_type))
elif tax_type == 'vat':
if self.gstrecords is not None:
tax_data = self.garray(variable_name)
attribute_var = self.ATTRIBUTE_READ_VARS_VAT
(attribute_types, attribute_data) = self.get_attribute_types(tax_type, 0)
else:
msg = 'tax type record ="{}" is not initialized'
raise ValueError(msg.format(tax_type))
else:
msg = 'tax type ="{}" is not valid'
raise ValueError(msg.format(tax_type))
return
if tax_type == 'pit':
wtd_total_tax = {}
wtd_total_tax['All'] = (tax_data * self.array('weight')).sum()
elif tax_type == 'cit':
wtd_total_tax = {}
wtd_total_tax['All'] = (tax_data * self.carray('weight')).sum()
# We have calculated for 'All' so no need to calculate further
attribute_types.remove('All')
if len(attribute_var)>0:
for attribute_value in attribute_types:
attribute_bool = [1 if i==attribute_value else 0 for i in attribute_data]
if tax_type == 'pit':
wtd_total_tax[attribute_value] = (tax_data * self.array('weight') * attribute_bool).sum()
elif tax_type == 'cit':
wtd_total_tax[attribute_value] = (tax_data * self.carray('weight') * attribute_bool).sum()
#print(wtd_total_cit)
return wtd_total_tax
def weighted_total_cit(self, variable_name, attribute_var=None):
"""
Return all-filing-unit weighted total of named Corp Records variable.
"""
if self.corprecords is not None:
if attribute_var is None:
return (self.carray(variable_name) * self.carray('weight')).sum()
else:
attribute_data = list(getattr(self.__corprecords, attribute_var))
attribute_types = set(attribute_data)
wtd_total_cit = {}
for attribute_value in attribute_types:
attribute_bool = [1 if i==attribute_value else 0 for i in attribute_data]
wtd_total_cit['attribute_value'] = (self.carray(variable_name) * self.carray('weight') *
attribute_bool).sum()
return wtd_total_cit
def total_weight_pit(self):
"""
Return all-filing-unit total of sampling weights.
NOTE: var_weighted_mean = calc.weighted_total(var)/calc.total_weight()
"""
if self.records is not None:
return self.array('weight').sum()
def total_weight_gst(self):
"""
Return all-filing-unit total of sampling weights.
NOTE: var_weighted_mean = calc.weighted_total(var)/calc.total_weight()
"""
if self.gstrecords is not None:
return self.garray('weight').sum()
def total_weight_cit(self):
"""
Return all-filing-unit total of sampling weights.
NOTE: var_weighted_mean = calc.weighted_total(var)/calc.total_weight()
"""
if self.corprecords is not None:
return self.carray('weight').sum()
def dataframe(self, variable_list):
"""
Return pandas DataFrame containing the listed variables from embedded
Records object.
"""
assert isinstance(variable_list, list)
arys = [self.array(vname) for vname in variable_list]
#print(arys)
pdf = pd.DataFrame(data=np.column_stack(arys), columns=variable_list)
del arys
return pdf
def dataframe_cit(self, variable_list, attribute_value=None, attribute_var=None):
"""
Return pandas DataFrame containing the listed variables from embedded
Records object.
"""
if attribute_var is not None:
variable_list = variable_list + [attribute_var]
#print('variable_list ', variable_list)
assert isinstance(variable_list, list)
arys = [self.carray(vname) for vname in variable_list]
#print(arys)
#print('attribute_value ', attribute_value)
#print('attribute_var ', attribute_var)
pdf = pd.DataFrame(data=np.column_stack(arys), columns=variable_list)
#print('pdf \n', pdf)
if attribute_var is not None:
if attribute_value != 'All':
pdf = pdf[pdf[attribute_var]==attribute_value]
del arys
return pdf
def dataframe_gst(self, variable_list):
"""
Return pandas DataFrame containing the listed variables from embedded
Records object.
"""
assert isinstance(variable_list, list)
arys = [self.garray(vname) for vname in variable_list]
#print(arys)
pdf = pd.DataFrame(data=np.column_stack(arys), columns=variable_list)
del arys
return pdf
def distribution_table_dataframe(self, tax_type, DIST_VARIABLES, attribute_value=None, attribute_var=None):
"""
Return pandas DataFrame containing the DIST_TABLE_COLUMNS variables
from embedded Records object.
"""
if tax_type == 'pit':
if self.records is not None:
if attribute_var is not None:
if attribute_value == 'All':
return self.dataframe(DIST_VARIABLES)
else:
return self.dataframe(DIST_VARIABLES, attribute_value, attribute_var)
else:
return self.dataframe(DIST_VARIABLES)
elif tax_type == 'cit':
if self.corprecords is not None:
if attribute_var is not None:
if attribute_value == 'All':
return self.dataframe_cit(DIST_VARIABLES)
else:
return self.dataframe_cit(DIST_VARIABLES, attribute_value, attribute_var)
else:
return self.dataframe_cit(DIST_VARIABLES)
elif tax_type == 'vat':
if self.gstrecords is not None:
if attribute_var is not None:
if attribute_value == 'All':
return self.dataframe_gst(DIST_VARIABLES)
else:
return self.dataframe_gst(DIST_VARIABLES, attribute_value, attribute_var)
else:
return self.dataframe_gst(DIST_VARIABLES)
else:
msg = 'tax type ="{}" is not valid'
raise ValueError(msg.format(tax_type))
return
def array(self, variable_name, variable_value=None):
"""
If variable_value is None, return numpy ndarray containing the
named variable in embedded Records object.
If variable_value is not None, set named variable in embedded Records
object to specified variable_value and return None (which can be
ignored).
"""
if self.records is not None:
if variable_value is None:
return getattr(self.__records, variable_name)
assert isinstance(variable_value, np.ndarray)
setattr(self.__records, variable_name, variable_value)
return None
def carray(self, variable_name, variable_value=None):
"""
Corporate record version of array() function.
If variable_value is None, return numpy ndarray containing the
named variable in embedded Records object.
If variable_value is not None, set named variable in embedded Records
object to specified variable_value and return None (which can be
ignored).
"""
if self.corprecords is not None:
if variable_value is None:
return getattr(self.__corprecords, variable_name)
assert isinstance(variable_value, np.ndarray)
setattr(self.__corprecords, variable_name, variable_value)
return None
def garray(self, variable_name, variable_value=None):
"""
GST record version of array() function.
If variable_value is None, return numpy ndarray containing the
named variable in embedded Records object.
If variable_value is not None, set named variable in embedded Records
object to specified variable_value and return None (which can be
ignored).
"""
if self.gstrecords is not None:
if variable_value is None:
return getattr(self.__gstrecords, variable_name)
assert isinstance(variable_value, np.ndarray)
setattr(self.__gstrecords, variable_name, variable_value)
return None
def n65(self):
"""
Return numpy ndarray containing the number of
individuals age 65+ in each filing unit.
"""
vdf = self.dataframe(['age_head', 'age_spouse', 'elderly_dependents'])
return ((vdf['age_head'] >= 65).astype(int) +
(vdf['age_spouse'] >= 65).astype(int) +
vdf['elderly_dependents'])
def incarray(self, variable_name, variable_add):
"""
Add variable_add to named variable in embedded Records object.
"""
assert isinstance(variable_add, np.ndarray)
setattr(self.__records, variable_name,
self.array(variable_name) + variable_add)
def zeroarray(self, variable_name):
"""
Set named variable in embedded Records object to zeros.
"""
setattr(self.__records, variable_name, np.zeros(self.array_len))
def store_records(self):
"""
Make internal copy of embedded Records object that can then be
restored after interim calculations that make temporary changes
to the embedded Records object.
"""
assert self.__stored_records is None
self.__stored_records = copy.deepcopy(self.__records)
def restore_records(self):
"""
Set the embedded Records object to the stored Records object
that was saved in the last call to the store_records() method.
"""
assert isinstance(self.__stored_records, Records)
self.__records = copy.deepcopy(self.__stored_records)
del self.__stored_records
self.__stored_records = None
def records_current_year(self, year=None):
"""
If year is None, return current_year of embedded Records object.
If year is not None, set embedded Records current_year to year and
return None (which can be ignored).
"""
if year is None:
return self.__records.current_year
assert isinstance(year, int)
self.__records.set_current_year(year)
return None
@property
def array_len(self):
"""
Length of arrays in embedded Records object.
"""
if self.records is not None:
return self.__records.array_length
if self.corprecords is not None:
return self.__corprecords.array_length
if self.gstrecords is not None:
return self.__gstrecords.array_length
def policy_param(self, param_name, param_value=None):
"""
If param_value is None, return named parameter in
embedded Policy object.
If param_value is not None, set named parameter in
embedded Policy object to specified param_value and
return None (which can be ignored).
"""
if param_value is None:
#from pprint import pprint
#pprint(vars(self.__policy))
return getattr(self.__policy, param_name)
setattr(self.__policy, param_name, param_value)
return None
@property
def reform_warnings(self):
"""
Calculator class embedded Policy object's reform_warnings.
"""
return self.__policy.parameter_warnings
def policy_current_year(self, year=None):
"""
If year is None, return current_year of embedded Policy object.
If year is not None, set embedded Policy current_year to year and
return None (which can be ignored).
"""
if year is None:
return self.__policy.current_year
assert isinstance(year, int)
self.__policy.set_year(year)
return None
@property
def current_year(self):
"""
Calculator class current assessment year property.
"""
return self.__policy.current_year
@property
def data_year(self):
"""
Calculator class initial (i.e., first) records data year property.
"""
return self.__records.data_year
def diagnostic_table(self, num_years):
"""
Generate multi-year diagnostic table containing aggregate statistics;
this method leaves the Calculator object unchanged.
Parameters
----------
num_years : Integer
number of years to include in diagnostic table starting
with the Calculator object's current_year (must be at least
one and no more than what would exceed Policy end_year)
Returns
-------
Pandas DataFrame object containing the multi-year diagnostic table
"""
assert num_years >= 1
max_num_years = self.__policy.end_year - self.__policy.current_year + 1
assert num_years <= max_num_years
diag_variables = DIST_VARIABLES + ['surtax']
calc = copy.deepcopy(self)
tlist = list()
for iyr in range(1, num_years + 1):
calc.calc_all()
diag = create_diagnostic_table(calc.dataframe(diag_variables),
calc.current_year)
tlist.append(diag)
if iyr < num_years:
calc.increment_year()
del diag_variables
del calc
del diag
return pd.concat(tlist, axis=1)
def distribution_tables_dict(self, tax_type, calc, groupby, distribution_vardict,
income_measure=None,
averages=False, scaling=True,
attribute_var=None):
"""
Get results from self and calc, sort them by GTI into table
rows defined by groupby, compute grouped statistics, and
return tables as a pair of Pandas dataframes.
This method leaves the Calculator object(s) unchanged.
Note that the returned tables have consistent income groups (based
on the self GTI) even though the baseline GTI in self and
the reform GTI in calc are different.
Parameters
----------
calc : Calculator object or None
typically represents the reform while self represents the baseline;
if calc is None, the second returned table is None
groupby : String object
options for input: 'weighted_deciles', 'standard_income_bins'
determines how the columns in resulting Pandas DataFrame are sorted
averages : boolean
specifies whether or not monetary table entries are aggregates or
averages (default value of False implies entries are aggregates)
scaling : boolean
specifies whether or not monetary table entries are scaled to
billions and rounded to three decimal places when averages=False,
or when averages=True, to thousands and rounded to three decimal
places. Regardless of the value of averages, non-monetary table
entries are scaled to millions and rounded to three decimal places
(default value of False implies entries are scaled and rounded)
Return and typical usage
------------------------
dist1, dist2 = calc1.distribution_tables(calc2, 'weighted_deciles')
OR
dist1, _ = calc1.distribution_tables(None, 'weighted_deciles')
(where calc1 is a baseline Calculator object
and calc2 is a reform Calculator object).
Each of the dist1 and optional dist2 is a distribution table as a
Pandas DataFrame with DIST_TABLE_COLUMNS and groupby rows.
NOTE: when groupby is 'weighted_deciles', the returned tables have 3
extra rows containing top-decile detail consisting of statistics
for the 0.90-0.95 quantile range (bottom half of top decile),
for the 0.95-0.99 quantile range, and
for the 0.99-1.00 quantile range (top one percent); and the
returned table splits the bottom decile into filing units with
negative (denoted by a 0-10n row label),
zero (denoted by a 0-10z row label), and
positive (denoted by a 0-10p row label) values of the
specified income_measure.
"""
# nested function used only by this method
def have_same_income_measure(calc1, calc2, imeasure):
"""
Return true if calc1 and calc2 contain the same GTI;
otherwise, return false. (Note that "same" means nobody's
GTI differs by more than one cent.)
"""
if self.records is not None:
im1 = calc1.array(imeasure)
im2 = calc2.array(imeasure)
if self.corprecords is not None:
im1 = calc1.carray(imeasure)
im2 = calc2.carray(imeasure)
if self.gstrecords is not None:
im1 = calc1.garray(imeasure)
im2 = calc2.garray(imeasure)
return np.allclose(im1, im2, rtol=0.0, atol=0.01)
# main logic of method
from taxcalc.utils import create_distribution_table
"""
(DIST_VARIABLES, DIST_TABLE_COLUMNS, DIST_TABLE_LABELS,
DECILE_ROW_NAMES,STANDARD_ROW_NAMES,STANDARD_INCOME_BINS)=dist_variables()
"""
assert calc is None or isinstance(calc, Calculator)
assert (groupby == 'weighted_deciles' or
groupby == 'weighted_percentiles' or
groupby == 'standard_income_bins')
attribute_types = ['All']
if calc is not None:
if self.records is not None:
assert np.allclose(self.array('weight'),
calc.array('weight')) # rows in same order
if attribute_var is not None:
(attribute_types, attribute_data) = self.get_attribute_types(tax_type, 0)
if self.corprecords is not None:
assert np.allclose(self.carray('weight'),
calc.carray('weight'))
if attribute_var is not None:
(attribute_types, attribute_data) = self.get_attribute_types(tax_type, 0)
if self.gstrecords is not None: