-
Notifications
You must be signed in to change notification settings - Fork 0
/
Data_load_IRS990_Sample_Dan_Amare.py
1434 lines (1197 loc) · 59.6 KB
/
Data_load_IRS990_Sample_Dan_Amare.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
from irsx.xmlrunner import XMLRunner
from datetime import datetime
from logging import getLogger
from irsx.settings import INDEX_DIRECTORY
from irsx.settings import WORKING_DIRECTORY
from irsx.settings import IRSX_CACHE_DIRECTORY
import csv
import os
import numpy as np
import pandas as pd
import re as re
import subprocess as sb
import sys
import shutil
from datetime import date
import cx_Oracle
import requests
from requests.exceptions import HTTPError
import urllib3
from urllib3 import request
import time
import zipfile
import io
import glob
import zipfile_deflate64 as zipfile
from bs4 import BeautifulSoup
#This python script uses BeautifulSoup and IRSX libraries to pull and parse through IRS 990 filings available in xml format on IRS.gov.
#It pulls an entire year's worth of filings for grant award recipient organizations monitored by a federal agency.
# It also pulls additional 990 filings and audits from non-profit ProPublica website using APIs available to the public.
# The purpose is to obtain financial data used in risk analytics applications further downstream.
# THIS SCRIPT IS FOR DEMO ONLY, IT DOES NOT WORK AS ESSENTIAL PARAMETERS, CONFIG files, folders are made inaccessible.
# Entire script implemented by Dagnaw Amare, 2022-2024.
logger = getLogger('return')
def combine_fields(value1, value2):
'''Returns the sum of value1 and value2 or whichever operand is not None. Returns None when both are None.'''
if value1 is not None and value2 is not None:
return value1 + value2
elif value1 is None:
return value2
elif value2 is None:
return value1
else:
return None
'''The Return class represents shared attributes across all 990 forms. In general, these are values found in IRSx's ReturnHeader990x schedule.'''
class Return:
def flatten_atts_for_db(self):
'''
Returns a flattened list of dictionaries populated with return header, balance, comp information for each person.
'''
# obj_tbl_field_map is a dictionary that maps object key names (ex: self.header_dict['ein']) to preferred field names on any output
# flatten_atts_for_db() searches self.obj_tbl_field_map for user-defined custom keys before falling back to class' default keys
db_rows = []
for person in self.people:
procd_person = {}
for k, v in person.items():
try:
k = self.obj_tbl_field_map[k]
except (KeyError, TypeError) as e:
# logger.debug(e)
pass
procd_person[k] = v
for k, v in self.balance_dict.items():
try:
k = self.obj_tbl_field_map[k]
except (KeyError, TypeError) as e:
# logger.debug(e)
pass
procd_person[k] = v
for k, v in self.header_dict.items():
try:
k = self.obj_tbl_field_map[k]
except (KeyError, TypeError) as e:
# logger.debug(e)
pass
procd_person[k] = v
procd_person['object_id'] = self.object_id
db_rows.append(procd_person)
return db_rows
def process_header_fields(self):
'''
Process header information from ReturnHeader990x and return it to __init__ as a dict
Header information will be handled the same across all forms of the 990
'''
header = self.xml_runner.run_sked(self.object_id, 'ReturnHeader990x')
header_dict = {}
try:
results = header.get_result()[0]
except TypeError:
#print('Unsupport version %s'%self.object_id)
return header_dict
header_values = results['schedule_parts']['returnheader990x_part_i']
header_obj_irsx_map = {
'ein': 'ein',
'name': 'BsnssNm_BsnssNmLn1Txt',
'state': 'USAddrss_SttAbbrvtnCd',
'city': 'USAddrss_CtyNm',
'tax_year': 'RtrnHdr_TxYr'
# custom_key_name: IRSX_key_name
# add valid ReturnHeader990x keys here to save those values during processing (see variables.csv)
}
obj_str_handling_map = {
'state': lambda x: x.upper(),
'city': lambda x: x.title(),
'name': lambda x: x.title()
# map custom keys to string handling lambdas for quick & dirty cleaning
}
for obj_key, irsx_key in header_obj_irsx_map.items():
try:
value = header_values[irsx_key]
if obj_key in obj_str_handling_map:
value = obj_str_handling_map[obj_key](value)
header_dict[obj_key] = value
except KeyError:
header_dict[obj_key] = None
# special case: fiscal year date
try:
tax_prd_end_date = header_values['RtrnHdr_TxPrdEndDt']
tax_prd_end_date = datetime.strptime(tax_prd_end_date, '%Y-%m-%d')
header_dict['fiscal_year'] = tax_prd_end_date.year
except KeyError:
header_dict['fiscal_year'] = None
try:
header_dict['dba'] = header_values['BsnssNm_BsnssNmLn1Txt']
except KeyError:
header_dict['dba'] = None
return header_dict
def process_compensation_fields(self):
'''Compensation fields are specific to the flavor of 990 and this is implemented on child classes.'''
raise NotImplementedError
def process_summary_fields(self):
'''Balance fields are specific to the flavor of 990 and this is implemented on child classes.'''
raise NotImplementedError
def process_balance_fields(self):
'''Balance fields are specific to the flavor of 990 and this is implemented on child classes.'''
raise NotImplementedError
def process_expense_fields(self):
'''Balance fields are specific to the flavor of 990 and this is implemented on child classes.'''
raise NotImplementedError
def process_governance_fields(self):
'''Balance fields are specific to the flavor of 990 and this is implemented on child classes.'''
raise NotImplementedError
def process_statement_fields(self):
'''Balance fields are specific to the flavor of 990 and this is implemented on child classes.'''
raise NotImplementedError
def __init__(self, object_id,obj_tbl_field_map=None):
self.object_id = object_id
self.xml_runner = XMLRunner()
self.obj_tbl_field_map = obj_tbl_field_map
self.header_dict = self.process_header_fields()
#if not header_only:
self.summary_dict = self.process_summary_fields()
self.balance_dict = self.process_balance_fields()
self.expense_dict = self.process_expense_fields()
self.governance_dict = self.process_governance_fields()
self.statement_dict = self.process_statement_fields()
#self.people = self.process_compensation_fields()
self.failures = {
#'comp': True if self.people is None else False,
'header': True if self.header_dict is None else False,
'summary': True if self.summary_dict is None else False,
'balance': True if self.balance_dict is None else False,
'expense': True if self.expense_dict is None else False,
'governance': True if self.governance_dict is None else False,
'statement': True if self.statement_dict is None else False,
}
def __repr__(self):
return '''Object_ID: {object_id}\nHeader: {header}\nSummary: {summary}\n
Balance: {balance}\n Expense: {expense}\n Governance: {governance}\n
Statement: {statement}\n '''.format(
#People: {people}\n
object_id=self.object_id,
header=self.header_dict,
summary=self.summary_dict,
balance=self.balance_dict,
expense = self.expense_dict,
governance = self.governance_dict,
statement = self.statement_dict
#,
#people=self.people
)
'''This child class represents information we're pulling from the 990EO'''
class Return_990(Return):
def process_compensation_fields(self):
db_irsx_key_map = {
'person': 'PrsnNm',
'title': 'TtlTxt',
'base_org': 'BsCmpnstnFlngOrgAmt',
'base_rel': 'CmpnstnBsdOnRltdOrgsAmt',
'bonus_org': 'BnsFlngOrgnztnAmnt',
'bonus_rel': 'BnsRltdOrgnztnsAmt',
'other_org': 'OthrCmpnstnFlngOrgAmt',
'other_rel': 'OthrCmpnstnRltdOrgsAmt',
'defer_org': 'DfrrdCmpnstnFlngOrgAmt',
'defer_rel': 'DfrrdCmpRltdOrgsAmt',
'nontax_ben_org': 'NntxblBnftsFlngOrgAmt',
'nontax_ben_rel': 'NntxblBnftsRltdOrgsAmt',
'990_total_org': 'TtlCmpnstnFlngOrgAmt',
'990_total_rel': 'TtlCmpnstnRltdOrgsAmt',
'prev_rep_org': 'CmpRprtPrr990FlngOrgAmt',
'prev_rep_rel': 'CmpRprtPrr990RltdOrgsAmt'
# custom_key_name: IRSX_key_name
# add valid Schedule J IRSX key names here to save those values during processing (see variables.csv)
}
db_type_map = {
# Key your custom keys to types to specify how each key should be cast on processing
key: int for key in db_irsx_key_map
}
obj_str_handling_map = {
# Key custom keys to lambda functions for quick and dirty cleaning on those values
'person': lambda x: x.title(),
'title': lambda x: x.title()
}
db_type_map['person'] = str
db_type_map['title'] = str
sked_j = self.xml_runner.run_sked(self.object_id, 'IRS990ScheduleJ')
results = sked_j.get_result()[0]
try:
sked_j_values = results['groups']['SkdJRltdOrgOffcrTrstKyEmpl']
except KeyError:
return None
people = []
for employee_dict in sked_j_values:
processed = {}
for db_key in db_irsx_key_map:
irsx_key = db_irsx_key_map[db_key]
db_type = db_type_map[db_key]
try:
value = db_type(employee_dict[irsx_key]) if irsx_key in employee_dict else None
if value is None and irsx_key == 'PrsnNm':
# sometimes people's names show up under BsnssNmLn1Txt
alt_person_key = 'BsnssNmLn1Txt'
value = employee_dict[alt_person_key] if alt_person_key in employee_dict.keys() else None
if db_key in obj_str_handling_map:
value = obj_str_handling_map[db_key](value)
processed[db_key] = value
except TypeError:
# if we can't cast the value we set it to None
processed[db_key] = None
except AttributeError:
processed[db_key] = None
person_name = processed['person']
people.append(processed)
return people
def process_summary_fields(self):
#balance = self.xml_runner.run_sked(self.object_id, 'IRS990')
parsed_filing = self.xml_runner.run_filing(self.object_id)
processed = {}
result = parsed_filing.get_result()
try:
sked = result[0]
except TypeError:
return processed
#schedule_list = parsed_filing.list_schedules()
#parsed_skedez = parsed_filing.get_parsed_sked('IRS990EZ')[0]
for sked in result:
if sked['schedule_name'] not in [ 'IRS990', 'IRS990EZ']:
continue
if sked['schedule_name'] == 'IRS990':
results = parsed_filing.get_parsed_sked('IRS990')[0]
db_irsx_key_map = {'total_rev': 'CYTtlRvnAmt' ,
'total_exp': 'CYTtlExpnssAmt',
'net_assets': 'NtAsstsOrFndBlncsEOYAmt',
'grants_contrbtns':'CYCntrbtnsGrntsAmt',
'service_rev':'CYPrgrmSrvcRvnAmt',
'invstmnt_income':'CYInvstmntIncmAmt',
'other_rev':'CYOthrRvnAmt',
'Salaries_exp':'CYSlrsCmpEmpBnftPdAmt',
'grants_paid_exp':'CYGrntsAndSmlrPdAmt',
'tot_fundraising_exp':'CYTtlFndrsngExpnsAmt',
'other_exp':'CYOthrExpnssAmt',
'Num_staff':'TtlEmplyCnt'
}
part_name = 'part_i'
#print("Schedule: %s" % sked['schedule_name'])
if sked['schedule_name'] == 'IRS990EZ':
results = parsed_filing.get_parsed_sked('IRS990EZ')[0]
db_irsx_key_map = { 'total_rev': 'TtlRvnAmt',
'total_exp': 'TtlExpnssAmt',
'net_assets':'NtAsstsOrFndBlncsEOYAmt',
'grants_contrbtns':'CntrbtnsGftsGrntsEtcAmt',
'service_rev':'PrgrmSrvcRvnAmt',
'invstmnt_income':'InvstmntIncmAmt',
'other_rev':'OthrRvnTtlAmt',
'Salaries_exp':'SlrsOthrCmpEmplBnftAmt',
'grants_paid_exp':'GrntsAndSmlrAmntsPdAmt',
'tot_fundraising_exp':'SpclEvntsDrctExpnssAmt',
'other_exp':'OthrExpnssTtlAmt'
#'Num_staff':''
}
part_name = 'ez_part_i'
#print("Schedule: %s" % sked['schedule_name'])
#print("Revenue: %s" % parsed_skedez['schedule_parts']['ez_part_i']['TtlRvnAmt'])
#results = balance.get_result()[0]
try:
#balance_values = results['schedule_parts']['ez_part_i']
values = results['schedule_parts'][part_name]
except KeyError:
return None
for db_key in db_irsx_key_map:
irsx_key = db_irsx_key_map[db_key]
processed[db_key] = values[irsx_key] if irsx_key in values.keys() else None
try:
processed[db_key] = int(processed[db_key])
except TypeError:
processed[db_key] = None
#p = processed
#p['private_support'] = combine_fields(p['total_contrib'], p['govt_grants'])
return processed
def process_balance_fields(self):
#balance = self.xml_runner.run_sked(self.object_id, 'IRS990')
parsed_filing = self.xml_runner.run_filing(self.object_id)
#result = parsed_filing.get_result()
#schedule_list = parsed_filing.list_schedules()
#parsed_skedez = parsed_filing.get_parsed_sked('IRS990EZ')[0]
processed = {}
try:
tax_year = self.header_dict['tax_year']
except KeyError:
print('Tax year key error for obect id %s'%self.object_id)
try:
ein = self.header_dict['ein']
except KeyError:
print('EIN key error for obect id %s'%self.object_id)
object_id = self.object_id
#print(tax_year)
#Unrestrictedassets = 'UnrstrctdNtAssts_EOYAmt' if year<2019 else 'UnrstrctdNtAssts_EOYAmt'
result = parsed_filing.get_result()
try:
sked = result[0]
except TypeError:
return processed
for sked in result:
if sked['schedule_name'] not in [ 'IRS990','IRS990EZ']:
continue
if sked['schedule_name'] == 'IRS990':
results = parsed_filing.get_parsed_sked('IRS990')[0]
db_irsx_key_map = {
'Un_net_assets':'UnrstrctdNtAssts_EOYAmt',
'total_assets':'TtlAssts_EOYAmt',
'total_liabilities':'TtlLblts_EOYAmt',
'Cash_BOY':'CshNnIntrstBrng_BOYAmt',
'Cash_EOY':'CshNnIntrstBrng_EOYAmt',
'Savings_BOY':'SvngsAndTmpCshInvst_BOYAmt',
'Savings_EOY':'SvngsAndTmpCshInvst_EOYAmt',
'grants_receivable':'PldgsAndGrntsRcvbl_EOYAmt',
'accts_receivable':'AccntsRcvbl_EOYAmt',
'investments':'InvstmntsPrgrmRltd_EOYAmt',
'land_bldg_equip':'LndBldgEqpCstOrOthrBssAmt'
}
part_name = 'part_x'
if sked['schedule_name'] == 'IRS990EZ':
results = parsed_filing.get_parsed_sked('IRS990EZ')[0]
db_irsx_key_map = {#'Un_net_assets':'Na',
'total_assets':'Frm990TtlAssts_EOYAmt',
'total_liabilities':'SmOfTtlLblts_EOYAmt',
'Cash_BOY':'CshSvngsAndInvstmnts_BOYAmt',
'Cash_EOY':'CshSvngsAndInvstmnts_EOYAmt',
#'Savings_BOY':'Na',
#'Savings_EOY':'Na'
'Savings_BOY':None,
'Savings_EOY':None,
'grants_receivable':None,
'accts_receivable':None,
'investments':'CshSvngsAndInvstmnts_EOYAmt',
'land_bldg_equip':'LndAndBldngs_EOYAmt'
}
part_name = 'ez_part_ii'
try:
values = results['schedule_parts'][part_name]
#if (ein=='630590338'):
#print('For Ein %s Part keys are: %s'%(ein,values.keys()))
#print('Ein %s has object id %s for tax year %s'%(ein, object_id, tax_year))
#exit(0)
except KeyError:
return None
for db_key in db_irsx_key_map:
irsx_key = db_irsx_key_map[db_key]
processed[db_key] = values[irsx_key] if irsx_key in values.keys() else None
try:
processed[db_key] = int(processed[db_key])
except TypeError:
processed[db_key] = None
return processed
def process_expense_fields(self):
#balance = self.xml_runner.run_sked(self.object_id, 'IRS990')
parsed_filing = self.xml_runner.run_filing(self.object_id)
#result = parsed_filing.get_result()
#schedule_list = parsed_filing.list_schedules()
#parsed_skedez = parsed_filing.get_parsed_sked('IRS990EZ')[0]
processed = {}
result = parsed_filing.get_result()
try:
sked = result[0]
except TypeError:
return processed
db_irsx_key_map = {'Depreciation': 'DprctnDpltn_TtlAmt' }
for sked in result:
if sked['schedule_name'] not in [ 'IRS990']:
continue
results = parsed_filing.get_parsed_sked('IRS990')[0]
try:
#balance_values = results['schedule_parts']['ez_part_i']
values = results['schedule_parts']['part_ix']
except KeyError:
return None
for db_key in db_irsx_key_map:
irsx_key = db_irsx_key_map[db_key]
processed[db_key] = values[irsx_key] if irsx_key in values.keys() else None
try:
processed[db_key] = int(processed[db_key])
except TypeError:
processed[db_key] = None
return processed
def process_governance_fields(self):
#balance = self.xml_runner.run_sked(self.object_id, 'IRS990')
parsed_filing = self.xml_runner.run_filing(self.object_id)
#result = parsed_filing.get_result()
#schedule_list = parsed_filing.list_schedules()
#parsed_skedez = parsed_filing.get_parsed_sked('IRS990EZ')[0]
processed = {}
result = parsed_filing.get_result()
try:
sked = result[0]
except TypeError:
return processed
db_irsx_key_map = {'Conflict_int': 'CnflctOfIntrstPlcyInd',
'Disclose_int': 'AnnlDsclsrCvrdPrsnInd',
'Monitor_complnce':'RglrMntrngEnfrcInd',
'Diversion_assets':'MtrlDvrsnOrMssInd'}
string_map = {'true': 'Yes',
'false': 'No',
'1': 'Yes',
'0': 'No'}
for sked in result:
if sked['schedule_name'] not in [ 'IRS990']:
continue
results = parsed_filing.get_parsed_sked('IRS990')[0]
try:
values = results['schedule_parts']['part_vi']
except KeyError:
return None
for db_key in db_irsx_key_map:
irsx_key = db_irsx_key_map[db_key]
processed[db_key] = values[irsx_key] if irsx_key in values.keys() else None
try:
processed[db_key] = string_map[(processed[db_key])]
except KeyError:
processed[db_key] = None
return processed
def process_statement_fields(self):
#balance = self.xml_runner.run_sked(self.object_id, 'IRS990')
parsed_filing = self.xml_runner.run_filing(self.object_id)
#result = parsed_filing.get_result()
#schedule_list = parsed_filing.list_schedules()
#parsed_skedez = parsed_filing.get_parsed_sked('IRS990EZ')[0]
processed = {}
result = parsed_filing.get_result()
try:
sked = result[0]
except TypeError:
return processed
db_irsx_key_map = {'Audit_req': 'FdrlGrntAdtRqrdInd',
'Audit_done': 'FdrlGrntAdtPrfrmdInd'
}
string_map = {'true': 'Yes',
'false': 'No',
'1': 'Yes',
'0': 'No'}
for sked in result:
if sked['schedule_name'] not in [ 'IRS990']:
continue
results = parsed_filing.get_parsed_sked('IRS990')[0]
try:
values = results['schedule_parts']['part_xii']
except KeyError:
return None
for db_key in db_irsx_key_map:
irsx_key = db_irsx_key_map[db_key]
processed[db_key] = values[irsx_key] if irsx_key in values.keys() else None
try:
processed[db_key] = string_map[(processed[db_key])]
except KeyError:
processed[db_key] = None
return processed
def Get_cngrants_data(v_db_env,LOG_FILE):
lib_dir = r"C:\oracle\Product\instantclient_21_3"
try:
cx_Oracle.init_oracle_client(lib_dir=lib_dir)
except Exception as err:
print_txt = "Error connecting: cx_Oracle.init_oracle_client()\n"
print_txt = print_txt + err
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
CURRENT_DIRECTORY = os.getcwd()
#ctx_auth = AuthenticationContext(SITE_URL)
PSWD_FILE = os.path.join(CURRENT_DIRECTORY, 'Config','pswd.txt')
if not os.path.exists(PSWD_FILE):
print_txt='Error: Credentials file was not found: %s '%(PSWD_FILE)
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
with open(PSWD_FILE) as file:
lines = file.readlines()
for line in lines:
env=line.rstrip().split('=')[0]
if (env.upper() == v_db_env.upper()):
user_id=line.rstrip().split('=')[1].split(',')[0]
passwd=line.rstrip().split('=')[1].split(',')[1]
#print('User name is: %s, password is: %s'%(user_id, passwd))
#user_passwd = v_credentials.split('/')
#user_id = user_passwd[0]
#passwd = user_passwd[1]
db_dsn = 'Connection information'
try:
connection = cx_Oracle.connect(user=user_id, password=passwd,
dsn=db_dsn)
except Exception as err:
print_txt='Error connecting: Invalid User/Passowrd. Please check and try again.'
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
cursor = connection.cursor()
sql = """ select distinct trim(mu.org_id) as org_id, ein
from ares.mv_daily_app_universe mu, cspanowner.organizations o
where mu.org_id = o.id
and o.ein is not null
"""
cursor.execute(sql)
col_names = ['ORG_ID','EIN']
cngrants_data = pd.DataFrame(cursor.fetchall(),columns=col_names)
print_txt = 'Org_id and EIN in Monitoring/Application Universe: %s'%cursor.rowcount
print_log(LOG_FILE, print_txt,1)
#Drop non integer EINs
numeric = lambda x:int(x) if x.isnumeric() else 0
cngrants_data['EIN'] = [numeric(x) for x in cngrants_data['EIN'] ]
bad_eins = len(cngrants_data[cngrants_data['EIN'] == 0])
print_txt = 'Delete Non numberic EINs in Monitoring/Application Universe: %s'% bad_eins
print_log(LOG_FILE, print_txt,1)
cngrants_data = cngrants_data[cngrants_data['EIN'] != 0]
connection.close()
return cngrants_data
def Import_filings(v_db_env,table_name,df_filings,filing_headers,LOG_FILE):
#lib_dir = r"C:\oracle\Product\instantclient_21_3"
#try:
#cx_Oracle.init_oracle_client(lib_dir=lib_dir)
#except Exception as err:
#print("Error connecting: cx_Oracle.init_oracle_client()")
#print(err);
#sys.exit(1);
CURRENT_DIRECTORY = os.getcwd()
#ctx_auth = AuthenticationContext(SITE_URL)
PSWD_FILE = os.path.join(CURRENT_DIRECTORY, 'Config','pswd.txt')
if not os.path.exists(PSWD_FILE):
print_txt='Error: Credentials file was not found: %s '%(PSWD_FILE)
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
with open(PSWD_FILE) as file:
lines = file.readlines()
for line in lines:
env=line.rstrip().split('=')[0]
if (env.upper() == v_db_env.upper()):
user_id=line.rstrip().split('=')[1].split(',')[0]
passwd=line.rstrip().split('=')[1].split(',')[1]
#print('User name is: %s, password is: %s'%(user_id, passwd))
#user_passwd = v_credentials.split('/')
#user_id = user_passwd[0]
#passwd = user_passwd[1]
db_dsn = 'Conn_dsn'
try:
connection = cx_Oracle.connect(user=user_id, password=passwd,
dsn=db_dsn)
except Exception as err:
print_txt='Error connecting: Invalid User/Passowrd. Please check and try again.'
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
cursor = connection.cursor()
col_name = filing_headers
col_name_str = """ ("""+','.join(col_name)+""") """
#vals = ['23456','Test Organization Name']
#f = lambda x: "N/A" if pd.isna(x) else ("" if pd.isnull(x) else str(x))
f = lambda x: "" if pd.isnull(x) else str(x)
vals_vars = """ (:"""+',:'.join(col_name)+""")"""
#sql = """ insert into """+ra_table+""" (application_id) values( :did)"""
#sql = """ insert into ARES.RA_IRS990"""+col_name_str + """values""" + vals_vars
sql = """ insert into ARES."""+table_name+col_name_str + """values""" + vals_vars
rowcount = 0
#print('Insert sql is: %s'%sql)
file_recs = len(df_filings.index)
increment = 100 if int(file_recs/5) < 100 else int(file_recs/5)
increment = int(increment/100)*100
for index, rows in df_filings.iterrows():
vals = [f(x) for x in rows]
#print('Values are: %s'%vals)
try:
cursor.execute(sql,vals)
except Exception as e:
error, = e.args
if error.code in (12899,1438):
print ('Value too large for Column, skipping...')
continue
else:
print (error.code)
print(error.message)
print(error.context)
exit(1)
rowcount += 1
if (rowcount%increment == 0):
print('Inserted records %s/%s ...'%(rowcount,file_recs))
#sql = """ UPDATE ARES.RA_IRS990 SET CREATE_DT = SYSDATE WHERE CREATE_DT IS NULL"""
sql = """ UPDATE ARES."""+table_name+""" SET CREATE_DT = SYSDATE
WHERE CREATE_DT IS NULL"""
#print('Update create dt sql is: %s'%sql)
cursor.execute(sql)
connection.commit()
print_txt='Successfully imported records into %s: %s/%s'%(table_name,rowcount,file_recs)
print_log(LOG_FILE, print_txt,1)
connection.close()
def Download_index_file(v_index_year, LOG_FILE):
today = datetime.now().strftime("%m_%d_%Y_%H_%M")
index_year = str(v_index_year)
index_csv = 'index_'+index_year+'.csv'
index_csv_bkp = 'index_'+index_year+'_'+today+'.csv'
INDEX_FILE= os.path.join(INDEX_DIRECTORY, index_csv)
INDEX_FILE_BKP= os.path.join(INDEX_DIRECTORY, index_csv_bkp)
if os.path.exists(INDEX_FILE):
print_txt='Copying Index file %s to archive before downloading...' %(index_year)
print_log(LOG_FILE, print_txt,1)
shutil.copy( INDEX_FILE,INDEX_FILE_BKP )
print_txt='Downloading Index file for filing year %s...' %(index_year)
print_log(LOG_FILE, print_txt,1)
#Download steps here, previously AWS code
#https://apps.irs.gov/pub/epostcard/990/xml/2019/index_2019.csv
#sb.run(['irsx_index', '--year='+index_year])
REMOTE_DOWNLOAD_SITE = r'https://apps.irs.gov/pub/epostcard/990/xml/'+index_year+r'/'
INDEX_FILE_URL = REMOTE_DOWNLOAD_SITE+index_csv
print ('Index url: %s'%INDEX_FILE_URL)
res = requests.head(INDEX_FILE_URL)
if res.status_code != 200:
print_txt='Index file is not available for download %s...' %(INDEX_FILE_URL)
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
#Download to user default directory
users_dir = r'C:\Users'
username = os.getlogin()
LOCAL_DOWNLOAD_DIRECTORY = os.path.join(users_dir,username,'Downloads')
r = requests.get(INDEX_FILE_URL)
if r.status_code != 200:
print_txt='Failed to download index file: %s '%(INDEX_FILE_URL)
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
INDEX_FILE_NEW = os.path.join(LOCAL_DOWNLOAD_DIRECTORY,index_csv)
open(INDEX_FILE_NEW,'wb').write(r.content)
print_txt='Successfully downloaded index file to: %s '%(INDEX_FILE_NEW)
print_log(LOG_FILE, print_txt,1)
#Copy from Download to Index CSV directory
if os.path.exists(INDEX_FILE_NEW):
print_txt='Copying New Index file %s to CSV directory...' %(index_year)
print_log(LOG_FILE, print_txt,1)
shutil.copy( INDEX_FILE_NEW,INDEX_FILE )
"""
Previous code to generate Index file from XML files...
#For each file in XML directory, get OBJECT ID and corresponding EIN
index_list = []
num_files = len(os.listdir(WORKING_DIRECTORY))
proc_files = 0
for xmlfile in os.listdir(WORKING_DIRECTORY):
object_id = xmlfile.split('_')[0]
#ein = XMLRunner().run_sked(object_id, 'ReturnHeader990x').get_ein()
header_dict = Return_990(object_id,True).header_dict
try:
ein = header_dict['ein']
name = header_dict['name']
#tax_year = header_dict['tax_year']
#fiscal_year = header_dict['fiscal_year']
except KeyError:
ein = None
#index_list.append([ein, object_id,name, tax_year,fiscal_year])
index_list.append([ein, object_id,name])
#index_list.append([ein, object_id,'test org'])
proc_files += 1
if (proc_files%5000==0):
print('Number of xml files processed to generate Index file: %s/%s'%(proc_files,num_files))
break
#if num_files > 10:
#break
#print('Number of xml efiles use to generate Index file: %s'%num_files)
df_index = pd.DataFrame(index_list,columns =['EIN','OBJECT_ID','Name'])
#filings_csv = 'Test_filings_'+str(index_year)+'.csv'
#FILINGS_OUTPUT = os.path.join( CURRENT_DIRECTORY, filings_csv)
df_index.to_csv(INDEX_FILE, index=False)
"""
print_txt='Index file downloaded for %s filing year.\nIndex file location:\n %s'%(index_year, INDEX_FILE)
print_log(LOG_FILE, print_txt,1)
return INDEX_FILE
def Prepare_xml_files(LOCAL_ZIP_FILE, local_file,df_efilers, LOG_FILE):
ARCHIVE_DIRECTORY = os.path.join(WORKING_DIRECTORY, 'Archive')
#Process zip file
#z = zipfile.ZipFile(io.BytesIO(LOCAL_ZIP_FILE))
z = zipfile.ZipFile(LOCAL_ZIP_FILE,'r')
print_txt = "Processing IRS XML zip file: %s" %(local_file)
print_log(LOG_FILE, print_txt,1)
#DATA_FILE_NAME = z.namelist()[0]
ARCHIVE_ZIP = os.path.join(ARCHIVE_DIRECTORY, local_file)
#Clean archive directory
for xmlfile in glob.iglob(os.path.join(ARCHIVE_DIRECTORY, '*.xml')):
os.remove(xmlfile)
#Extract into archive directory
print_txt = "Extracting IRS XML file: %s" %(LOCAL_ZIP_FILE)
print_log(LOG_FILE, print_txt,1)
try:
z.extractall(ARCHIVE_DIRECTORY)
except RuntimeError as e:
print_txt = "Error extracting zip file file: %s\n" %(LOCAL_ZIP_FILE)
print_txt = print_txt + e
print_log(LOG_FILE, print_txt,1)
exit(1)
print_txt = "Extraction IRS XML file completed for: %s" %(LOCAL_ZIP_FILE)
print_log(LOG_FILE, print_txt,1)
#Copy XML files needed to Working directory
print_txt = "Copying needed IRS XML files to: %s" %(WORKING_DIRECTORY)
print_log(LOG_FILE, print_txt,1)
#Get object id for xmlfile in os.listdir(WORKING_DIRECTORY):
list_objectids = []
for xmlfile in glob.iglob(os.path.join(ARCHIVE_DIRECTORY, '*.xml')):
filename = os.path.basename(xmlfile)
#print ('firstfile is %s'%filename)
object_id = filename.split('_')[0]
list_objectids.append(object_id)
df_objectids = pd.DataFrame(list_objectids, columns=['OBJECT_ID'])
#Collect object ids that have corresponding XML files
df_objectids_found = pd.merge(df_efilers,
df_objectids,
on='OBJECT_ID', how='inner')['OBJECT_ID']
num_objectids_found = len(df_objectids_found.index)
num_xmls = len(df_objectids.index)
for object_id in list(df_objectids_found):
xmlfile = object_id+'_public.xml'
xmlfilepath = os.path.join(ARCHIVE_DIRECTORY,xmlfile )
shutil.copy(xmlfilepath,WORKING_DIRECTORY)
#remove XML files not needed
print_txt = "Found %s/%s needed IRS XML files from ZIP file %s, removing the rest..." %(num_objectids_found, num_xmls, local_file)
print_log(LOG_FILE, print_txt,1)
for xmlfile in glob.iglob(os.path.join(ARCHIVE_DIRECTORY, '*.xml')):
os.remove(xmlfile)
#If not archived already, copy to archive
if not os.path.exists(ARCHIVE_ZIP):
print_txt='Archiving zipped file to %s' %(ARCHIVE_ZIP)
print_log(LOG_FILE, print_txt,1)
shutil.copy( LOCAL_ZIP_FILE,ARCHIVE_ZIP )
#shutil.copy( r.content,ARCHIVE_ZIP )
#shutil.copyfileobj(mp3file, output)
return
def listFD(url, ext=''):
page = requests.get(url).content
#print(page[:1000])
soup = BeautifulSoup(page, 'html.parser')
#return [url + '/' + node.get('href') for node in soup.find_all('a') if node.get('href').endswith(ext)]
#return [node.get('title') for node in soup.find_all('a', attrs = {'class':'link-label label-file label-file-zip'}) ]
return [node.get('href') for node in soup.find_all('a') if node.get('href') is not None and node.get('href').startswith(ext) ]
def Get_names_files(index_year, LOG_FILE):
REMOTE_DOWNLOAD_SITE = r'https://apps.irs.gov/pub/epostcard/990/xml/'+index_year+r'/'
#ZIP_FILE_URL = REMOTE_DOWNLOAD_SITE #+remote_file
url = 'https://www.irs.gov/charities-non-profits/form-990-series-downloads'
ext = REMOTE_DOWNLOAD_SITE
all_files = listFD(url, ext)
zip_files = [file for file in all_files if file.endswith('zip')]
file_sizes = []
for file in zip_files:
res = requests.head(file)
if res.status_code == 200:
#For future download progress use, use download in chunks code
file_sizes.append(res.headers['content-length'])
print_txt='File available to download: %s'%file
print_log(LOG_FILE, print_txt,1)
print_txt='Total number of zip files to download: %s'%(len(zip_files))
print_log(LOG_FILE, print_txt,1)
return zip_files
def Download_zip_files(index_year, file_names, LOG_FILE):
"""
docstring
"""
#pass
#User default download
users_dir = r'C:\Users'
username = os.getlogin()
LOCAL_DOWNLOAD_DIRECTORY = os.path.join(users_dir,username,'Downloads')
#Download files only if not previously downloaded.
for file in file_names:
remote_file = os.path.basename(file)
#print('Remote file name is %s'%remote_file)
LOCAL_ZIP_FILE = os.path.join(LOCAL_DOWNLOAD_DIRECTORY,remote_file)
#Skip file already downloaded
if os.path.exists(LOCAL_ZIP_FILE):
print_txt='IRS ZIP file already downloaded: %s '%(LOCAL_ZIP_FILE)
print_log(LOG_FILE, print_txt,1)
continue
print_txt='Downloading IRS ZIP file to: %s '%(LOCAL_ZIP_FILE)
print_log(LOG_FILE, print_txt,1)
r = requests.get(file)
if r.status_code != 200:
print_txt='Download IRS ZIP file failed for: %s\n'%(LOCAL_ZIP_FILE)
print_txt=print_txt + 'Please try again later.'
print_log(LOG_FILE, print_txt,1)
sys.exit(1)
"""
response = requests.get(url, stream=True)
with open('alaska.zip', "wb") as f:
for chunk in response.iter_content(chunk_size=512):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
"""
open(LOCAL_ZIP_FILE,'wb').write(r.content)
print_txt='Successfully downloaded IRS ZIP file to: %s '%(LOCAL_ZIP_FILE)
print_log(LOG_FILE, print_txt,1)
return
def get_irsgov_data(v_index_year, df_cngrants, LOG_FILE):
#Download index file and load into Dataframe
INDEX_FILE = Download_index_file(v_index_year, LOG_FILE)
col_names = ['RETURN_ID','FILING_TYPE','EIN','TAX_PERIOD','SUB_DATE','TAXPAYER_NAME','RETURN_TYPE','DLN','OBJECT_ID']
#col_names = ['EIN','OBJECT_ID','Name']
np_year = pd.read_csv(INDEX_FILE, names=col_names, converters = {'OBJECT_ID': str,'EIN':str}, header=0,encoding='ISO-8859-1', index_col=False, low_memory=False)
CURRENT_DIRECTORY = os.getcwd()
#Get CN_Grants EINs only from Index data
df_cngrants_efilers = pd.merge(np_year,df_cngrants,on='EIN', how='inner')
#extract latest if duplicate/ammendement filing in same year
#df_cngrants_efilers = df_cngrants_efilers.sort_values(by=['ORG_ID','TAX_PERIOD','RETURN_ID'])
#df_cngrants_efilers = df_cngrants_efilers.drop_duplicates(['ORG_ID','TAX_PERIOD'], keep='last')