-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
test_calculator.py
858 lines (797 loc) · 31 KB
/
test_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
"""
Tests of Calculator class.
"""
# CODING-STYLE CHECKS:
# pycodestyle test_calculator.py
# pylint --disable=locally-disabled test_calculator.py
#
# pylint: disable=too-many-lines,invalid-name
import os
from io import StringIO
import copy
import pytest
import numpy as np
import pandas as pd
from taxcalc import Policy, Records, Calculator, Consumption
def test_make_calculator(cps_subsample):
"""
Test Calculator class ctor.
"""
start_year = Policy.JSON_START_YEAR
sim_year = 2018
pol = Policy()
assert pol.current_year == start_year
rec = Records.cps_constructor(data=cps_subsample)
consump = Consumption()
consump.update_consumption({'MPC_e20400': {sim_year: 0.05}})
assert consump.current_year == start_year
calc = Calculator(policy=pol, records=rec,
consumption=consump, verbose=True)
assert calc.data_year == Records.CPSCSV_YEAR
assert calc.current_year == Records.CPSCSV_YEAR
# test incorrect Calculator instantiation:
with pytest.raises(ValueError):
Calculator(policy=None, records=rec)
with pytest.raises(ValueError):
Calculator(policy=pol, records=None)
with pytest.raises(ValueError):
Calculator(policy=pol, records=rec, consumption=list())
def test_make_calculator_deepcopy(cps_subsample):
"""
Test deepcopy of Calculator object.
"""
pol = Policy()
rec = Records.cps_constructor(data=cps_subsample)
calc1 = Calculator(policy=pol, records=rec)
calc2 = copy.deepcopy(calc1)
assert isinstance(calc2, Calculator)
def test_make_calculator_with_policy_reform(cps_subsample):
"""
Test Calculator class ctor with policy reform.
"""
rec = Records.cps_constructor(data=cps_subsample)
year = rec.current_year
# create a Policy object and apply a policy reform
pol = Policy()
reform = {
'II_em': {2013: 4000},
'II_em-indexed': {2013: False},
'STD_Aged': {2013: [1600, 1300, 1300, 1600, 1600]},
'STD_Aged-indexed': {2013: False}
}
pol.implement_reform(reform)
# create a Calculator object using this policy reform
calc = Calculator(policy=pol, records=rec)
assert calc.reform_warnings == ''
# check that Policy object embedded in Calculator object is correct
assert calc.current_year == year
assert calc.policy_param('II_em') == 4000
assert np.allclose(calc.policy_param('_II_em'),
np.array([4000] * Policy.DEFAULT_NUM_YEARS))
exp_STD_Aged = [[1600, 1300, 1300,
1600, 1600]] * Policy.DEFAULT_NUM_YEARS
assert np.allclose(calc.policy_param('_STD_Aged'),
np.array(exp_STD_Aged))
assert np.allclose(calc.policy_param('STD_Aged'),
np.array([1600, 1300, 1300, 1600, 1600]))
def test_make_calculator_with_multiyear_reform(cps_subsample):
"""
Test Calculator class ctor with multi-year policy reform.
"""
rec = Records.cps_constructor(data=cps_subsample)
year = rec.current_year
# create a Policy object and apply a policy reform
pol = Policy()
reform = {
'II_em': {2015: 5000, 2016: 6000},
'II_em-indexed': {2015: False},
'STD_Aged': {2016: [1600, 1300, 1600, 1300, 1600]}
}
pol.implement_reform(reform)
# create a Calculator object using this policy-reform
calc = Calculator(policy=pol, records=rec)
# check that Policy object embedded in Calculator object is correct
assert pol.num_years == Policy.DEFAULT_NUM_YEARS
assert calc.current_year == year
assert calc.policy_param('II_em') == 3950
exp_II_em = [3900, 3950, 5000] + [6000] * (Policy.DEFAULT_NUM_YEARS - 3)
assert np.allclose(calc.policy_param('_II_em'),
np.array(exp_II_em))
calc.increment_year()
calc.increment_year()
assert calc.current_year == 2016
assert np.allclose(calc.policy_param('STD_Aged'),
np.array([1600, 1300, 1600, 1300, 1600]))
def test_calculator_advance_to_year(cps_subsample):
"""
Test Calculator advance_to_year method.
"""
rec = Records.cps_constructor(data=cps_subsample)
pol = Policy()
calc = Calculator(policy=pol, records=rec)
calc.advance_to_year(2016)
assert calc.current_year == 2016
with pytest.raises(ValueError):
calc.advance_to_year(2015)
def test_make_calculator_raises_on_no_policy(cps_subsample):
"""
Test Calculator ctor error with no policy argument.
"""
rec = Records.cps_constructor(data=cps_subsample)
with pytest.raises(ValueError):
Calculator(records=rec)
def test_calculator_mtr(cps_subsample):
"""
Test Calculator mtr method.
"""
rec = Records.cps_constructor(data=cps_subsample)
calcx = Calculator(policy=Policy(), records=rec)
calcx.calc_all()
combinedx = calcx.array('combined')
c00100x = calcx.array('c00100')
calc = Calculator(policy=Policy(), records=rec)
recs_pre_e00200p = copy.deepcopy(calc.array('e00200p'))
(mtr_ptx, mtr_itx, mtr_cmb) = calc.mtr(variable_str='e00200p',
zero_out_calculated_vars=True)
recs_post_e00200p = calc.array('e00200p')
assert np.allclose(recs_post_e00200p, recs_pre_e00200p)
assert np.allclose(calc.array('combined'), combinedx)
assert np.allclose(calc.array('c00100'), c00100x)
assert np.array_equal(mtr_cmb, mtr_ptx) is False
assert np.array_equal(mtr_ptx, mtr_itx) is False
with pytest.raises(ValueError):
calc.mtr(variable_str='bad_income_type')
(_, _, mtr_combined) = calc.mtr(variable_str='e00200s',
calc_all_already_called=True)
assert isinstance(mtr_combined, np.ndarray)
(_, _, mtr_combined) = calc.mtr(variable_str='e00650',
negative_finite_diff=True,
calc_all_already_called=True)
assert isinstance(mtr_combined, np.ndarray)
(_, _, mtr_combined) = calc.mtr(variable_str='e00900p',
calc_all_already_called=True)
assert isinstance(mtr_combined, np.ndarray)
(_, _, mtr_combined) = calc.mtr(variable_str='e01700',
calc_all_already_called=True)
assert isinstance(mtr_combined, np.ndarray)
(_, _, mtr_combined) = calc.mtr(variable_str='e26270',
calc_all_already_called=True)
assert isinstance(mtr_combined, np.ndarray)
(_, _, mtr_combined) = calc.mtr(variable_str='e00200p',
calc_all_already_called=True)
assert np.allclose(mtr_combined, mtr_cmb)
assert np.allclose(calc.array('combined'), combinedx)
assert np.allclose(calc.array('c00100'), c00100x)
def test_calculator_mtr_when_PT_rates_differ():
"""
Test Calculator mtr method in special case.
"""
reform = {
'II_rt1': {2013: 0.40},
'II_rt2': {2013: 0.40},
'II_rt3': {2013: 0.40},
'II_rt4': {2013: 0.40},
'II_rt5': {2013: 0.40},
'II_rt6': {2013: 0.40},
'II_rt7': {2013: 0.40},
'PT_rt1': {2013: 0.30},
'PT_rt2': {2013: 0.30},
'PT_rt3': {2013: 0.30},
'PT_rt4': {2013: 0.30},
'PT_rt5': {2013: 0.30},
'PT_rt6': {2013: 0.30},
'PT_rt7': {2013: 0.30}
}
funit = (
'RECID,MARS,FLPDYR,e00200,e00200p,e00900,e00900p,extraneous\n'
'1, 1, 2009, 200000,200000, 100000,100000, 9999999999\n'
)
rec = Records(pd.read_csv(StringIO(funit)))
pol = Policy()
calc1 = Calculator(policy=pol, records=rec)
(_, mtr1, _) = calc1.mtr(variable_str='p23250')
pol.implement_reform(reform)
calc2 = Calculator(policy=pol, records=rec)
(_, mtr2, _) = calc2.mtr(variable_str='p23250')
assert np.allclose(mtr1, mtr2, rtol=0.0, atol=1e-06)
def test_make_calculator_increment_years_first(cps_subsample):
"""
Test Calculator inflation indexing of policy parameters.
"""
# pylint: disable=too-many-locals
# create Policy object with policy reform
pol = Policy()
std5 = 2000
reform = {
'STD_Aged': {2015: [std5, std5, std5, std5, std5]},
'II_em': {2015: 5000,
2016: 6000},
'II_em-indexed': {2016: False}
}
pol.implement_reform(reform)
# create Calculator object with Policy object as modified by reform
rec = Records.cps_constructor(data=cps_subsample)
calc = Calculator(policy=pol, records=rec)
# compare expected policy parameter values with those embedded in calc
irates = pol.inflation_rates()
syr = Policy.JSON_START_YEAR
irate2015 = irates[2015 - syr]
irate2016 = irates[2016 - syr]
std6 = std5 * (1.0 + irate2015)
std7 = std6 * (1.0 + irate2016)
exp_STD_Aged = np.array([[1500, 1200, 1200, 1500, 1500],
[1550, 1200, 1200, 1550, 1550],
[std5, std5, std5, std5, std5],
[std6, std6, std6, std6, std6],
[std7, std7, std7, std7, std7]])
act_STD_Aged = calc.policy_param('_STD_Aged')
assert np.allclose(act_STD_Aged[:5], exp_STD_Aged)
exp_II_em = np.array([3900, 3950, 5000, 6000, 6000])
act_II_em = calc.policy_param('_II_em')
assert np.allclose(act_II_em[:5], exp_II_em)
def test_ID_HC_vs_BS(cps_subsample):
"""
Test that complete haircut of itemized deductions produces same
results as a 100% benefit surtax with no benefit deduction.
"""
recs = Records.cps_constructor(data=cps_subsample)
# specify complete-haircut reform policy and Calculator object
hc_policy = Policy()
hc_reform = {
'ID_Medical_hc': {2013: 1.0},
'ID_StateLocalTax_hc': {2013: 1.0},
'ID_RealEstate_hc': {2013: 1.0},
'ID_Casualty_hc': {2013: 1.0},
'ID_Miscellaneous_hc': {2013: 1.0},
'ID_InterestPaid_hc': {2013: 1.0},
'ID_Charity_hc': {2013: 1.0}
}
hc_policy.implement_reform(hc_reform)
hc_calc = Calculator(policy=hc_policy, records=recs)
hc_calc.calc_all()
hc_taxes = hc_calc.dataframe(['iitax', 'payrolltax'])
del hc_calc
# specify benefit-surtax reform policy and Calculator object
bs_policy = Policy()
bs_reform = {
'ID_BenefitSurtax_crt': {2013: 0.0},
'ID_BenefitSurtax_trt': {2013: 1.0}
}
bs_policy.implement_reform(bs_reform)
bs_calc = Calculator(policy=bs_policy, records=recs)
bs_calc.calc_all()
bs_taxes = bs_calc.dataframe([], all_vars=True)
del bs_calc
# compare calculated taxes generated by the two reforms
assert np.allclose(hc_taxes['payrolltax'], bs_taxes['payrolltax'])
assert np.allclose(hc_taxes['iitax'], bs_taxes['iitax'])
def test_ID_StateLocal_HC_vs_CRT(cps_subsample):
"""
Test that a cap on state/local income and sales tax deductions at 0 percent
of AGI is equivalent to a complete haircut on the same state/local tax
deductions.
"""
rec = Records.cps_constructor(data=cps_subsample)
# specify state/local complete haircut reform policy and Calculator object
hc_policy = Policy()
hc_reform = {'ID_StateLocalTax_hc': {2013: 1.0}}
hc_policy.implement_reform(hc_reform)
hc_calc = Calculator(policy=hc_policy, records=rec)
hc_calc.calc_all()
# specify AGI cap reform policy and Calculator object
crt_policy = Policy()
crt_reform = {'ID_StateLocalTax_crt': {2013: 0.0}}
crt_policy.implement_reform(crt_reform)
crt_calc = Calculator(policy=crt_policy, records=rec)
crt_calc.calc_all()
# compare calculated tax results generated by the two reforms
assert np.allclose(hc_calc.array('payrolltax'),
crt_calc.array('payrolltax'))
assert np.allclose(hc_calc.array('iitax'),
crt_calc.array('iitax'))
def test_ID_RealEstate_HC_vs_CRT(cps_subsample):
"""
Test that a cap on all state, local, and foreign real estate tax deductions
at 0 percent of AGI is equivalent to a complete haircut on the same real
estate tax deductions.
"""
rec = Records.cps_constructor(data=cps_subsample)
# specify real estate complete haircut reform policy and Calculator object
hc_policy = Policy()
hc_reform = {'ID_RealEstate_hc': {2013: 1.0}}
hc_policy.implement_reform(hc_reform)
hc_calc = Calculator(policy=hc_policy, records=rec)
hc_calc.calc_all()
# specify AGI cap reform policy and Calculator object
crt_policy = Policy()
crt_reform = {'ID_RealEstate_crt': {2013: 0.0}}
crt_policy.implement_reform(crt_reform)
crt_calc = Calculator(policy=crt_policy, records=rec)
crt_calc.calc_all()
# compare calculated tax results generated by the two reforms
assert np.allclose(hc_calc.array('payrolltax'),
crt_calc.array('payrolltax'))
assert np.allclose(hc_calc.array('iitax'),
crt_calc.array('iitax'))
RAWINPUT_FUNITS = 4
RAWINPUT_YEAR = 2015
RAWINPUT_CONTENTS = (
'RECID,MARS,unknown\n'
' 1, 2, 9\n'
' 2, 1, 9\n'
' 3, 4, 9\n'
' 4, 3, 9\n'
)
def test_calculator_using_nonstd_input():
"""
Test Calculator using non-standard input records.
"""
# check Calculator handling of raw, non-standard input data with no aging
pol = Policy()
pol.set_year(RAWINPUT_YEAR) # set policy params to input data year
nonstd = Records(data=pd.read_csv(StringIO(RAWINPUT_CONTENTS)),
start_year=RAWINPUT_YEAR, # set raw input data year
gfactors=None, # keeps raw data unchanged
weights=None)
assert nonstd.array_length == RAWINPUT_FUNITS
calc = Calculator(policy=pol, records=nonstd,
sync_years=False) # keeps raw data unchanged
assert calc.current_year == RAWINPUT_YEAR
calc.calc_all()
assert calc.weighted_total('e00200') == 0
assert calc.total_weight() == 0
varlist = ['RECID', 'MARS']
dframe = calc.dataframe(varlist)
assert isinstance(dframe, pd.DataFrame)
assert dframe.shape == (RAWINPUT_FUNITS, len(varlist))
mars = calc.array('MARS')
assert isinstance(mars, np.ndarray)
assert mars.shape == (RAWINPUT_FUNITS,)
exp_iitax = np.zeros((nonstd.array_length,))
assert np.allclose(calc.array('iitax'), exp_iitax)
mtr_ptax, _, _ = calc.mtr(wrt_full_compensation=False)
exp_mtr_ptax = np.zeros((nonstd.array_length,))
exp_mtr_ptax.fill(0.153)
assert np.allclose(mtr_ptax, exp_mtr_ptax)
def test_bad_json_names(tests_path):
"""
Test that ValueError raised with assump or reform do not end in '.json'
"""
csvname = os.path.join(tests_path, '..', 'growfactors.csv')
with pytest.raises(ValueError):
Calculator.read_json_param_objects(csvname, None)
with pytest.raises(ValueError):
Calculator.read_json_param_objects('http://name.json.html', None)
with pytest.raises(ValueError):
Calculator.read_json_param_objects(None, csvname)
with pytest.raises(ValueError):
Calculator.read_json_param_objects(None, 'http://name.json.html')
def test_json_assump_url():
"""
Test reading JSON assumption file using URL.
"""
assump_str = """
{
"consumption": {
// all BEN_*_value parameters have a default value of one
"BEN_housing_value": {"2017": 1.0},
"BEN_snap_value": {"2017": 1.0},
"BEN_tanf_value": {"2017": 1.0},
"BEN_vet_value": {"2017": 1.0},
"BEN_wic_value": {"2017": 1.0},
"BEN_mcare_value": {"2017": 1.0},
"BEN_mcaid_value": {"2017": 1.0},
"BEN_other_value": {"2017": 1.0},
// all MPC_* parameters have a default value of zero
"MPC_e17500": {"2017": 0.0},
"MPC_e18400": {"2017": 0.0},
"MPC_e19800": {"2017": 0.0},
"MPC_e20400": {"2017": 0.0}
},
"growdiff_baseline": {
// all growdiff_baseline parameters have a default value of zero
"ABOOK": {"2017": 0.0},
"ACGNS": {"2017": 0.0},
"ACPIM": {"2017": 0.0},
"ACPIU": {"2017": 0.0},
"ADIVS": {"2017": 0.0},
"AINTS": {"2017": 0.0},
"AIPD": {"2017": 0.0},
"ASCHCI": {"2017": 0.0},
"ASCHCL": {"2017": 0.0},
"ASCHEI": {"2017": 0.0},
"ASCHEL": {"2017": 0.0},
"ASCHF": {"2017": 0.0},
"ASOCSEC": {"2017": 0.0},
"ATXPY": {"2017": 0.0},
"AUCOMP": {"2017": 0.0},
"AWAGE": {"2017": 0.0},
"ABENOTHER": {"2017": 0.0},
"ABENMCARE": {"2017": 0.0},
"ABENMCAID": {"2017": 0.0},
"ABENSSI": {"2017": 0.0},
"ABENSNAP": {"2017": 0.0},
"ABENWIC": {"2017": 0.0},
"ABENHOUSING": {"2017": 0.0},
"ABENTANF": {"2017": 0.0},
"ABENVET": {"2017": 0.0}
},
"growdiff_response": {
// all growdiff_response parameters have a default value of zero
"ABOOK": {"2017": 0.0},
"ACGNS": {"2017": 0.0},
"ACPIM": {"2017": 0.0},
"ACPIU": {"2017": 0.0},
"ADIVS": {"2017": 0.0},
"AINTS": {"2017": 0.0},
"AIPD": {"2017": 0.0},
"ASCHCI": {"2017": 0.0},
"ASCHCL": {"2017": 0.0},
"ASCHEI": {"2017": 0.0},
"ASCHEL": {"2017": 0.0},
"ASCHF": {"2017": 0.0},
"ASOCSEC": {"2017": 0.0},
"ATXPY": {"2017": 0.0},
"AUCOMP": {"2017": 0.0},
"AWAGE": {"2017": 0.0},
"ABENOTHER": {"2017": 0.0},
"ABENMCARE": {"2017": 0.0},
"ABENMCAID": {"2017": 0.0},
"ABENSSI": {"2017": 0.0},
"ABENSNAP": {"2017": 0.0},
"ABENWIC": {"2017": 0.0},
"ABENHOUSING": {"2017": 0.0},
"ABENTANF": {"2017": 0.0},
"ABENVET": {"2017": 0.0}
}
}
"""
assump_url = ('https://raw.githubusercontent.com/PSLmodels/'
'Tax-Calculator/master/taxcalc/assumptions/'
'economic_assumptions_template.json')
params_str = Calculator.read_json_param_objects(None, assump_str)
assert params_str
params_url = Calculator.read_json_param_objects(None, assump_url)
assert params_url
assert params_url == params_str
def test_read_bad_json_assump_file():
"""
Test invalid JSON assumption files.
"""
badassump1 = """
{
"consumption": { // example of incorrect JSON because 'x' must be "x"
'x': {"2014": 0.25}
},
"growdiff_baseline": {},
"growdiff_response": {}
}
"""
with pytest.raises(ValueError):
Calculator.read_json_param_objects(None, badassump1)
with pytest.raises(ValueError):
Calculator.read_json_param_objects(None, 'unknown_file_name')
with pytest.raises(ValueError):
Calculator.read_json_param_objects(None, list())
def test_calc_all():
"""
Test calc_all method.
"""
cyr = 2016
pol = Policy()
pol.set_year(cyr)
nonstd = Records(data=pd.read_csv(StringIO(RAWINPUT_CONTENTS)),
start_year=cyr, gfactors=None, weights=None)
assert nonstd.array_length == RAWINPUT_FUNITS
calc = Calculator(policy=pol, records=nonstd,
sync_years=False) # keeps raw data unchanged
assert calc.current_year == cyr
def test_noreform_documentation():
"""
Test automatic documentation creation.
"""
reform_json = """
{
}
"""
assump_json = """
{
"consumption": {},
"growdiff_baseline": {},
"growdiff_response": {}
}
"""
params = Calculator.read_json_param_objects(reform_json, assump_json)
assert isinstance(params, dict)
actual_doc = Calculator.reform_documentation(params)
expected_doc = (
'REFORM DOCUMENTATION\n'
'Baseline Growth-Difference Assumption Values by Year:\n'
'none: using default growth assumptions\n'
'Response Growth-Difference Assumption Values by Year:\n'
'none: using default growth assumptions\n'
'Policy Reform Parameter Values by Year:\n'
'none: using current-law policy parameters\n'
)
assert actual_doc == expected_doc
def test_reform_documentation():
"""
Test automatic documentation creation.
"""
reform_json = """
{
"II_em-indexed": {
"2016": false,
"2018": true
},
"II_em": {
"2016": 5000,
"2018": 6000,
"2020": 7000
},
"EITC_indiv": {
"2017": true
},
"STD_Aged-indexed": {
"2016": false
},
"STD_Aged": {
"2016": [1600, 1300, 1300, 1600, 1600],
"2020": [2000, 2000, 2000, 2000, 2000]
},
"ID_BenefitCap_Switch": {
"2020": [false, false, false, false, false, false, false]
}
}
"""
assump_json = """
{
"consumption": {},
// increase baseline inflation rate by one percentage point in 2014+
// (has no effect on known policy parameter values)
"growdiff_baseline": {"ACPIU": {"2014": 0.010}},
"growdiff_response": {"ACPIU": {"2014": 0.015}}
}
"""
params = Calculator.read_json_param_objects(reform_json, assump_json)
assert isinstance(params, dict)
second_reform = {'II_em': {2019: 6500}}
doc = Calculator.reform_documentation(params, [second_reform])
assert isinstance(doc, str)
dump = False # set to True to print documentation and force test failure
if dump:
print(doc)
assert 1 == 2
def test_distribution_tables(cps_subsample):
"""
Test distribution_tables method.
"""
pol = Policy()
recs = Records.cps_constructor(data=cps_subsample)
calc1 = Calculator(policy=pol, records=recs)
assert calc1.current_year == 2014
calc1.calc_all()
dt1, dt2 = calc1.distribution_tables(None, 'weighted_deciles')
assert isinstance(dt1, pd.DataFrame)
assert dt2 is None
dt1, dt2 = calc1.distribution_tables(calc1, 'weighted_deciles')
assert isinstance(dt1, pd.DataFrame)
assert isinstance(dt2, pd.DataFrame)
reform = {
'UBI_u18': {2014: 1000},
'UBI_1820': {2014: 1000},
'UBI_21': {2014: 1000}
}
pol.implement_reform(reform)
assert not pol.parameter_errors
calc2 = Calculator(policy=pol, records=recs)
calc2.calc_all()
dt1, dt2 = calc1.distribution_tables(calc2, 'weighted_deciles')
assert isinstance(dt1, pd.DataFrame)
assert isinstance(dt2, pd.DataFrame)
def test_difference_table(cps_subsample):
"""
Test difference_table method.
"""
cyr = 2014
pol = Policy()
recs = Records.cps_constructor(data=cps_subsample)
calc1 = Calculator(policy=pol, records=recs)
assert calc1.current_year == cyr
reform = {'SS_Earnings_c': {cyr: 9e99}}
pol.implement_reform(reform)
calc2 = Calculator(policy=pol, records=recs)
assert calc2.current_year == cyr
calc1.calc_all()
calc2.calc_all()
diff = calc1.difference_table(calc2, 'weighted_deciles', 'iitax')
assert isinstance(diff, pd.DataFrame)
def test_diagnostic_table(cps_subsample):
"""
Test diagnostic_table method.
"""
recs = Records.cps_constructor(data=cps_subsample)
calc = Calculator(policy=Policy(), records=recs)
adt = calc.diagnostic_table(3)
assert isinstance(adt, pd.DataFrame)
def test_mtr_graph(cps_subsample):
"""
Test mtr_graph method.
"""
recs = Records.cps_constructor(data=cps_subsample)
calc = Calculator(policy=Policy(), records=recs)
fig = calc.mtr_graph(calc,
mars=2,
income_measure='wages',
mtr_measure='ptax',
pop_quantiles=False)
assert fig
fig = calc.mtr_graph(calc,
income_measure='agi',
mtr_measure='itax',
pop_quantiles=True)
assert fig
def test_atr_graph(cps_subsample):
"""
Test atr_graph method.
"""
recs = Records.cps_constructor(data=cps_subsample)
calc = Calculator(policy=Policy(), records=recs)
fig = calc.atr_graph(calc, mars=2, atr_measure='itax')
assert fig
fig = calc.atr_graph(calc, atr_measure='ptax')
assert fig
def test_privacy_of_embedded_objects(cps_subsample):
"""
Test privacy of objects embedded in Calculator object.
"""
recs = Records.cps_constructor(data=cps_subsample)
calc = Calculator(policy=Policy(), records=recs)
var1 = var2 = var3 = 0
# pylint: disable=protected-access
with pytest.raises(AttributeError):
var1 = calc.__policy.current_year
with pytest.raises(AttributeError):
var2 = calc.__records.s006
with pytest.raises(AttributeError):
var3 = calc.__consumption.current_year
assert var1 == var2 == var3
def test_n65(cps_subsample):
"""
Test n65 method.
"""
recs = Records.cps_constructor(data=cps_subsample)
calc = Calculator(policy=Policy(), records=recs)
assert calc.n65().sum() > 1500
def test_ce_aftertax_income(cps_subsample):
"""
Test ce_aftertax_income method.
"""
rec = Records.cps_constructor(data=cps_subsample)
pol = Policy()
calc1 = Calculator(policy=pol, records=rec)
pol.implement_reform({'SS_Earnings_c': {2013: 9e99}})
calc2 = Calculator(policy=pol, records=rec)
res = calc1.ce_aftertax_income(calc2)
assert isinstance(res, dict)
@pytest.mark.itmded_vars
@pytest.mark.pre_release
@pytest.mark.requires_pufcsv
@pytest.mark.parametrize('year, cvname, hcname',
[(2018, 'c17000', 'ID_Medical_hc'),
(2018, 'c18300', 'ID_AllTaxes_hc'),
(2018, 'c19200', 'ID_InterestPaid_hc'),
(2018, 'c19700', 'ID_Charity_hc'),
(2018, 'c20500', 'ID_Casualty_hc'),
(2018, 'c20800', 'ID_Miscellaneous_hc'),
(2017, 'c17000', 'ID_Medical_hc'),
(2017, 'c18300', 'ID_AllTaxes_hc'),
(2017, 'c19200', 'ID_InterestPaid_hc'),
(2017, 'c19700', 'ID_Charity_hc'),
(2017, 'c20500', 'ID_Casualty_hc'),
(2017, 'c20800', 'ID_Miscellaneous_hc')])
def test_itemded_component_amounts(year, cvname, hcname, puf_fullsample):
"""
Check that all c04470 components are adjusted to reflect the filing
unit's standard-vs-itemized-deduction decision. Check for 2018
(when current law has no Pease phaseout of itemized deductions and
already has complete haircuts for Casualty and Miscellaneous deductions)
and 2017 (when current law has a Pease phaseout of itemized deductions
and has no haircuts). The calcfunctions.py code makes no attempt to
adjust the components for the effects of Pease-like phaseout or any other
type of limitation on total itemized deductions, so the pre-2018 tests
here use c21060, instead of c04470, as the itemized deductions total.
"""
# pylint: disable=too-many-locals
recs = Records(data=puf_fullsample)
# policy1 such that everybody itemizes deductions and all are allowed
policy1 = Policy()
reform1 = {
'STD_Aged': {year: [0.0, 0.0, 0.0, 0.0, 0.0]},
'STD': {year: [0.0, 0.0, 0.0, 0.0, 0.0]}
}
policy1.implement_reform(reform1)
assert not policy1.parameter_errors
# policy2 such that everybody itemizes deductions but one is disallowed
policy2 = Policy()
reform2 = {
'STD_Aged': {year: [0.0, 0.0, 0.0, 0.0, 0.0]},
'STD': {year: [0.0, 0.0, 0.0, 0.0, 0.0]},
hcname: {year: 1.0}
}
policy2.implement_reform(reform2)
assert not policy2.parameter_errors
# compute tax liability in specified year
calc1 = Calculator(policy=policy1, records=recs, verbose=False)
calc1.advance_to_year(year)
calc1.calc_all()
calc2 = Calculator(policy=policy2, records=recs, verbose=False)
calc2.advance_to_year(year)
calc2.calc_all()
# confirm that nobody is taking the standard deduction
assert np.allclose(calc1.array('standard'), 0.)
assert np.allclose(calc2.array('standard'), 0.)
# calculate different in total itemized deductions
if year == 2017:
# pre-Pease limitation total itemized deductions
itmded1 = calc1.weighted_total('c21060') * 1e-9
itmded2 = calc2.weighted_total('c21060') * 1e-9
elif year == 2018:
# total itemized deductions (no Pease-like limitation)
itmded1 = calc1.weighted_total('c04470') * 1e-9
itmded2 = calc2.weighted_total('c04470') * 1e-9
else:
raise ValueError('illegal year value = {}'.format(year))
difference_in_total_itmded = itmded1 - itmded2
# calculate itemized component amount
component_amt = calc1.weighted_total(cvname) * 1e-9
# confirm that component amount is equal to difference in total deductions
if year == 2017 and cvname == 'c19700':
atol = 0.009
elif year == 2017 and cvname == 'c19200':
atol = 0.010
else:
atol = 0.00001
if not np.allclose(component_amt, difference_in_total_itmded, atol=atol):
txt = '\n{}={:.3f} != {:.3f}=difference_in_total_itemized_deductions'
msg = txt.format(cvname, component_amt, difference_in_total_itmded)
raise ValueError(msg)
def test_qbid_calculation():
"""
Test Calculator's QBID calculations using the six example filing units
specified in Table 1 of this TPC publication: "Navigating the New
Pass-Through Provisions: A Technical Explanation" by William G. Gale
and Aaron Krupkin (January 31, 2018), which is available at this URL:
https://www.taxpolicycenter.org/publications/
navigating-new-pass-through-provisions-technical-explanation/full
"""
# In constructing the TPC example filing units, assume that the taxpayer
# has business income in the form of e26270/e02000 income and no earnings,
# and that the spouse has no business income and only earnings.
TPC_YEAR = 2018
TPC_VARS = (
'RECID,MARS,e00200s,e00200,e26270,e02000,PT_SSTB_income,'
'PT_binc_w2_wages,PT_ubia_property,pre_qbid_taxinc,qbid\n'
)
TPC_FUNITS = (
'1,2, 99000, 99000,75000,75000,1,20000,90000,150000,15000.00\n'
'2,2,349000,349000,75000,75000,1,20000,90000,400000, 1612.50\n'
'3,2,524000,524000,75000,75000,1,20000,90000,575000, 0.00\n'
'4,2, 99000, 99000,75000,75000,0,20000,90000,150000,15000.00\n'
'5,2,349000,349000,75000,75000,0,20000,90000,400000,10750.00\n'
'6,2,524000,524000,75000,75000,0,20000,90000,575000,10000.00\n'
)
# generate actual Calculator pre-qbid taxinc and qbid amounts
tpc_df = pd.read_csv(StringIO(TPC_VARS + TPC_FUNITS))
recs = Records(data=tpc_df, start_year=TPC_YEAR,
gfactors=None, weights=None)
calc = Calculator(policy=Policy(), records=recs)
assert calc.current_year == TPC_YEAR
calc.calc_all()
varlist = ['RECID', 'c00100', 'standard', 'c04470', 'qbided']
tc_df = calc.dataframe(varlist)
# compare actual amounts with expected amounts from TPC publication
act_taxinc = tc_df.c00100 - np.maximum(tc_df.standard, tc_df.c04470)
exp_taxinc = tpc_df.pre_qbid_taxinc
assert np.allclose(act_taxinc, exp_taxinc)
assert np.allclose(tc_df.qbided, tpc_df.qbid)