-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparser_classes.py
More file actions
1968 lines (1597 loc) · 82.2 KB
/
parser_classes.py
File metadata and controls
1968 lines (1597 loc) · 82.2 KB
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
import logging
import re
from bs4 import BeautifulSoup, NavigableString
import pandas as pd
import unicodedata
import uu
import pymupdf
import io
'''
10/21/24
Parser objects, written per filing type. Targetting:
- 10-Q + 10-K + 6-K
- 13F
- 13G + 13D
- S-1 + S-3
- 8K
- Form 4
- Proxy statements
- SEC actions+letters
- TODO: Form-D, CSR, NPORT
'''
####~Classes:~####
'''
Base class. Is able to read the SEC header (standard across filing types) and search for filing documents
Returns a dictionary of structure:
{
'filing_info': {
'cik': '...',
'type': '...',
'date': 'YYYYMMDD',
'accession_numer': '...',
'company_name': '...',
'sic_code': '...',
'sic_desc': '...',
'report_period': 'YYYYMMDD',
'state_of_incorp': '...',
'fiscal_yr_end': 'MMDD',
'business_address': 'ADDRESS, CITY, STATE, ZIP',
'business_phone': '...',
'name_changes': [{...},...]
'header_raw_text': '...',
'filing_raw_text': '...'
}
}
'''
class SECFulltextParser:
def __init__(self, fulltext):
self.filing_info = self.parse_sec_header(fulltext)
'''
Break filing into documents. Returns a list of dictionaries, one per document, of the following format:
{
'doc_type': '...',
'doc_sequence': '...',
'doc_filename': '...',
'doc_desc': '...',
'doc_text': '...'
}
'''
def split_filing_documents(self):
docs_found = []
document_pattern = r'<document>(.*?)</document>'
doc_info_patterns = {
'doc_type': r'\s*<type>(?P<doc_type>.*?)\s*<',
'doc_sequence': r'\s*<sequence>(?P<doc_sequence>\d+)\s*<',
'doc_filename': r'\s*<filename>(?P<doc_filename>.*?)\s*<',
'doc_desc': r'\s*<description>(?P<doc_desc>.*?)\s*<',
'doc_text': r'\s*<text>(?P<doc_text>.*?)</text>\s*'
}
# Find all filing documents
try:
documents = re.findall(document_pattern, self.filing_info['filing_raw_text'], re.DOTALL | re.IGNORECASE)
except Exception as e:
logging.error(f'Failed to find <DOCUMENT> tags in the current filing. Error: {e}')
documents = []
# Iterate through each document
for doc in documents:
doc_info = {}
doc_info['doc_desc'] = '' # May not be present, just initialize for uniformity
for key, pattern in doc_info_patterns.items():
match = re.search(pattern, doc, re.DOTALL | re.IGNORECASE)
if match:
doc_info[key] = match.group(key).strip()
else:
if key != 'doc_desc':
logging.warning(f'Failed to find SEC <document> section: {key}\nDocument contents: {doc[:100]}')
docs_found.append(doc_info)
return docs_found
# Helper for below, traversing filing. Returns the first match found.
def search_filing_for_doc(self, doc_name):
logging.info(f'Searching for document in filing: {doc_name}')
doc_info = {}
documents = self.split_filing_documents()
if not documents:
logging.error('Failed to split filing into documents to search for {doc_name}')
return doc_info
try:
for doc in documents:
if doc['doc_filename'].lower() == doc_name.lower():
doc_info = doc
break
except Exception as e:
logging.error(f'Failed iterating list of documents returned by split_filing_documents(). Error: {e}.')
return doc_info
# Helps traverse filing full text. Search documents by filename.
# (Returns contents within <TEXT>...</TEXT> tags for the found document)
def search_filing_for_doc_text(self, doc_name):
doc_text = ''
doc_info = self.search_filing_for_doc(doc_name)
if not doc_info:
return doc_text
try:
doc_text = doc_info['doc_text']
except Exception as e:
logging.error(f'Failed parsing doc_info from search_filing_for_doc(). doc_name: {doc_name}, Error: {e}.')
return doc_text
# Extracts the SEC header (<SEC-HEADER>...</SEC-HEADER>) from the full text of a filing. Helper method
def extract_sec_header(self, fulltext_contents):
# Regex pattern to capture the SEC header
pattern = r'(<sec-header>.*?</sec-header>)'
# Search for the SEC header in the full text
try:
match = re.search(pattern, fulltext_contents, re.DOTALL | re.IGNORECASE)
except Exception as e:
logging.error(f'Failed regex search for SEC header. Error: {e}.')
return None
if match:
return match.group(0) # Return the entire match, which includes the tags
else:
return None # Return None if no SEC header is found
'''
Parses the filing's SEC header into a dictionary filing_info
{
'type': '...',
'date': 'YYYYMMDD',
'accession_number': '...',
# Optional fields from here on (method won't fail if it can't fill them)
'cik': '...',
'sic_code': '...',
'sic_desc': '...',
'company_name': '...',
'report_period': 'YYYYMMDD',
'state_of_incorp': '...',
'fiscal_yr_end': 'MMDD',
'business_address': 'ADDRESS, CITY, STATE, ZIP',
'business_phone': '...',
'name_changes': [{...},...],
'header_raw_text': '...',
'filing_raw_text': '...'
}
'''
def parse_sec_header(self, fulltext_contents):
filing_info = {
'type': None,
'date': None,
'accession_number': None,
'cik': None,
'sic_code': None,
'sic_desc': None,
'company_name': None,
'report_period': None,
'state_of_incorp': None,
'fiscal_yr_end': None,
'business_address': None,
'business_phone': None,
'name_changes': [],
'header_raw_text': None,
'filing_raw_text': None
}
header_text = self.extract_sec_header(fulltext_contents)
if not header_text:
logging.error('Failed to extract SEC header from filing content.')
return filing_info
filing_info['header_raw_text'] = header_text
filing_info['filing_raw_text'] = fulltext_contents
# Extract required fields
required_patterns = {
'accession_number': r'accession number:\s+([^\n]+)',
'type': r'form type:\s+([^\n]+)',
'date': r'filed as of date:\s+(\d{8})'
# (CIK + SIC will be grabbed later on. If they cannot be found, xxxxxxxxxx and xxxx will be used, respectively, for unknowns)
}
for key, pattern in required_patterns.items():
match = re.search(pattern, header_text, re.IGNORECASE)
if match:
filing_info[key] = match.group(1).strip()
else:
logging.error(f'Failed to parse SEC header required field: {key}.')
return filing_info # Early exit. Something is wrong lol
# Report period if applicable
report_period_match = re.search(r'\s*conformed period of report:\s*(.+?)', header_text, re.IGNORECASE)
if report_period_match:
filing_info['report_period'] = report_period_match.group(1).strip()
else:
logging.warning('Header field not found: report_period')
filing_info['report_period'] = None
# We try to ensure we only grab the filer / filed by / issuer company, not a subject company.
# Filings such as 13D/G, hold company data on both subject companies and filer companies.
filed_by_match = re.search(r'filed by:', header_text, re.IGNORECASE)
filer_match = re.search(r'filer:', header_text, re.IGNORECASE)
issuer_match = re.search(r'issuer:', header_text, re.IGNORECASE)
if filed_by_match:
remaining_text = header_text[filed_by_match.end():] # Extract text after 'filed by:'
elif filer_match:
remaining_text = header_text[filer_match.end():] # Extract text after 'filer:'
elif issuer_match:
remaining_text = header_text[issuer_match.end():]
else:
remaining_text = header_text # Fallback in case neither section is present
# Some company data patterns
company_data_patterns = {
'company_name': r'\s*COMPANY CONFORMED NAME:\s*(?P<company_name>.+?)\s*(?:\n|$)',
'cik' : r'\s*CENTRAL INDEX KEY:\s*(?P<cik>\d+)\s*(?:\n|$)',
'sic_whole' : r'\s*STANDARD INDUSTRIAL CLASSIFICATION:\s*',
'state_of_incorp': r'\s*STATE OF INCORPORATION:\s*(?P<state_of_incorp>\w+)\s*(?:\n|$)',
'fiscal_yr_end': r'\s*FISCAL YEAR END:\s*(?P<fiscal_yr_end>\d{4})\s*(?:\n|$)',
'business_address': r'\s*BUSINESS ADDRESS:\s*',
'business_phone': r'\s*BUSINESS PHONE:\s*(?P<business_phone>.+?)\s*(?:\n|$)'
}
for key, pattern in company_data_patterns.items():
match = re.search(pattern, remaining_text, re.IGNORECASE)
if match:
# Address field takes some additional processing
if key == 'business_address':
business_address_patterns = {
'street1': r"\s*STREET\s+1:\s*(?P<street1>.*?)\s*(?:\n|$)",
'street2': r"\s*STREET\s+2:\s*(?P<street2>.*?)\s*(?:\n|$)",
'city': r"\s*CITY:\s*(?P<city>.*?)\s*(?:\n|$)",
'state': r"\s*STATE:\s*(?P<state>\w+)\s*(?:\n|$)",
'zip': r"\s*ZIP:\s*(?P<zip>\d+)"
}
business_address_info = {}
for key, pattern in business_address_patterns.items():
match = re.search(pattern, remaining_text, re.IGNORECASE | re.DOTALL)
if match:
business_address_info[key] = match.group(key).strip()
else:
logging.warning(f'Business address component not found: {key}')
# Construct the address
components = [component for component in business_address_info.values() if component]
filing_info['business_address'] = ', '.join(components)
# SIC needs to be split into code and description
elif key == 'sic_whole':
sic_pattern = r"\s*STANDARD INDUSTRIAL CLASSIFICATION:\s*(?P<sic_description>.+?)\s*\[(?P<sic_code>\d{4})\]"
# Search for the SIC
match = re.search(sic_pattern, remaining_text, re.IGNORECASE)
if match:
filing_info['sic_desc'] = match.group('sic_description').strip()
filing_info['sic_code'] = match.group('sic_code').strip()
else:
filing_info['sic_desc'] = None
filing_info['sic_code'] = 'XXXX'
logging.warning('Failed to parse sic_code or sic_desc')
else:
filing_info[key] = match.group(1).strip()
else:
logging.warning(f'Header field not found: {key}')
if key == 'cik':
filing_info[key] = 'XXXXXXXXXX'
elif key == 'sic_whole':
filing_info['sic_desc'] = None
filing_info['sic_code'] = 'XXXX'
# Lastly, grab any former company names
former_name_pattern = r"\s*FORMER COMPANY:\s*FORMER CONFORMED NAME:\s*(?P<former_name>.+?)\s*DATE OF NAME CHANGE:\s*(?P<date_of_change>\d{8})"
# Find all matches
matches = re.finditer(former_name_pattern, remaining_text, re.IGNORECASE | re.DOTALL)
for match in matches:
filing_info['name_changes'].append({
'former_name': match.group('former_name').strip(),
'date_of_change': match.group('date_of_change').strip()
})
logging.info('Finished parsing filing SEC header')
return filing_info
def full_parse(self):
return self.construct_parsed_output()
def construct_parsed_output(self):
return {
'filing_info': self.filing_info,
}
'''
10-Q, 10-K, 6-K parser
Adds financial_statements and text_section fields to returned dict:
{
'filing_info': {
'cik': '...',
'type': '...',
'date': 'YYYYMMDD',
'accession_numer': '...',
'company_name': '...',
'sic_code': '...',
'sic_desc': '...',
'report_period': 'YYYYMMDD',
'state_of_incorp': '...',
'fiscal_yr_end': 'MMDD',
'business_address': 'ADDRESS, CITY, STATE, ZIP',
'business_phone': '...',
'name_changes': [{...},...]
'header_raw_text': '...',
'filing_raw_text': '...'
},
'financial_statements': [
{
'report_doc': '...',
'report_name': '...',
'report_title_read': '...',
'report_raw_text': '...',
'report_parsed_data': {...},
'report_df': ...
},
...
],
'text_sections': [
{
'section_doc': '...',
'section_name': '...',
'section_type': '...',
'section_raw_text': '...',
'section_parsed_text': {...} / '...'
},
...
],
}
'''
class FinancialFilingParser(SECFulltextParser):
def __init__(self, fulltext):
# Init self.filing_info
super().__init__(fulltext)
self.financial_statements = []
self.text_sections = []
'''
Returns a list of dictionaries about each of the reports found in the given FilingSummary.xml contents
Structure of each dict:
{
'menucategory': '...',
'shortname': '...',
'longname': '...',
'doc_name': '...',
'role': '...',
'position': '...'
}
'''
def list_xbrl_reports(self, filingsummary, report_category=None):
reports_found = []
# Find MyReports and loop through them
summary_soup = BeautifulSoup(filingsummary, 'xml')
reports = summary_soup.find(re.compile('myreports', flags=re.IGNORECASE))
if not reports:
logging.warning('Failed to find <myreports> tag for filing.')
return reports_found
for report in reports.find_all(re.compile(r'^(?:\w+:)?report$', flags=re.IGNORECASE)):
tag_regex = lambda tag: re.compile(rf'^(?:\w+:)?{tag}$', flags=re.IGNORECASE)
report_info = {}
report_info['menu_category'] = report.find(tag_regex('MenuCategory')).get_text() if report.find(tag_regex('MenuCategory')) else None
if report_category:
if not report_info['menu_category']:
logging.info(f'Passing on report, has no MenuCategory set but filter is set to {report_category}.')
continue
if report_category.lower() != report_info['menu_category'].lower():
logging.info(f'Passing on report, non-target menu category. Desired: {report_category.lower()}, found: {report_info["menu_category"].lower()}.')
continue
report_info['short_name'] = report.find(tag_regex('ShortName')).get_text() if report.find(tag_regex('ShortName')) else None
report_info['long_name'] = report.find(tag_regex('LongName')).get_text() if report.find(tag_regex('LongName')) else None
report_info['doc_name'] = report.find(tag_regex('HtmlFileName')).get_text() if report.find(tag_regex('HtmlFileName')) else None
report_info['role'] = report.find(tag_regex('Role')).get_text() if report.find(tag_regex('Role')) else None
report_info['position'] = report.find(tag_regex('Position')).get_text() if report.find(tag_regex('Position')) else None
reports_found.append(report_info)
logging.info(f'Found report of interest: {report_info["short_name"]}.')
return reports_found
# Attempts to extract data from the given XBRL financial/statement report
def parse_xbrl_fin_report(self, report_content):
# Dictionary we will return
report_data = {}
report_data['headers'] = []
report_data['sections'] = []
report_data['data'] = []
# Soupify report
report_soup = BeautifulSoup(report_content, 'html.parser')
# In case there are multiple tables in the document, loop through all of those labeled with the "report" class. Tables of other classes (i.e. of type "authRefData") are ignored.
for table_index, current_table in enumerate(report_soup.find_all('table', class_ = "report")):
# Loop through table's rows
for row_index, current_row in enumerate(current_table.find_all('tr')):
# If we come across a row of class "rh" (signaling an end of the aggregated/totals and beginning of member/source breakdowns), end here tell user they may want to further split the table
# So far this structure seems to hold true as discussed in the "*" above.
try:
if "rh" in current_row['class']:
logging.warning("Member/source-specific financial information is available but will not be recorded here. Consider further splitting the report by member.")
break
except:
pass
# Grab all the elements / columns of the row. Keep in mind column headers don't have <td> tags, thus we list <th> objects within the elif upon finding them
line_columns = current_row.find_all('td')
# Decide if row is: data, section (sub) header, or column header according to logic above (th and strong tags)
# and append it to the proper list (headers, sections, or data) of the statement_data dictionary.
# Data row. May be a footnote or superscript, which we will filter out
if (len(current_row.find_all('th')) == 0 and len(current_row.find_all('strong')) == 0):
data_row = []
try:
for i in current_row['class']: # We need to do a sub-string search, TODO optimize this loop
# Skip rows containing "note" in a class tag (usually are footnotes)
if "note" in i.lower():
pass
# Skip superscripted values/columns (usually link to footnote) and those with class of "fn", again link to footnote
for current_column in line_columns:
if len(current_column.find_all('sup')) == 0:
try:
if "fn" not in current_column['class']:
data_column = current_column.text.strip()
data_row.append(data_column)
except: # No column class set. Shouldn't happen but just ignore and try next column of the row
pass
report_data['data'].append(data_row)
# Most likely did not have a row class set. Generally means blank / separator
except:
pass
# Section/sub header row
elif (len(current_row.find_all('th')) == 0 and len(current_row.find_all('strong')) != 0):
section_row = line_columns[0].text.strip() # Only the first element in this row will have the section label, the others are blank so no point
report_data['sections'].append(section_row)
# Header row
elif len(current_row.find_all('th')) != 0:
header_row = []
# Again, skip superscripted columns. TODO potentially record these somewhere
for current_column in current_row.find_all("th"):
if len(current_column.find_all("sup")) == 0:
header_column = current_column.text.strip()
header_row.append(header_column)
report_data['headers'].append(header_row)
# Unable to identify
else:
logging.warning(r"Unable to identify row #{} of table #{} found in table of financial report".format(row_index + 1, table_index + 1))
# TODO remove any newline characters in the columns or section headers
# Return the filled dictionary
return report_data
# Makes the given list of strings unique, appending _X as they increase in count
def make_unique_string_list(self, list_of_strings):
unique_list = []
existing_counts = {}
if list_of_strings:
for current_string in list_of_strings:
if current_string in existing_counts:
existing_counts[current_string] += 1
unique_list.append(f"{current_string}_{existing_counts[current_string]}")
else:
existing_counts[current_string] = 0
unique_list.append(current_string)
else:
logging.warning(f'Empty list of strings passed to make_unique method. Object passed: {list_of_strings}.')
return unique_list
# Attempts to store the data from the parsed financial report dictionary into a pandas dataframe
def parsed_fin_report_to_df(self, parsed_fin_report):
# Create two lists: headers (column headings), and data values. Ignore section headers for now
try:
report_headers_list = parsed_fin_report['headers']
report_data_list = parsed_fin_report['data']
except Exception as e:
logging.error(f'Passed invalid parsed_fin_report dict. Error: {e}.')
return None
# Check that data has been passed. Can be empty if the report starts off with an "rh" row, usually seen in parenthetical statements regarding member entities etc.
if not report_data_list:
logging.warning('An empty report was passed to parsed_fin_report_to_df(). DF will be None.')
return None
# Create the dataframe around the report data list
report_df = pd.DataFrame(report_data_list)
# Create a dictionary to count occurrences of each line item / financial account
name_count = {}
# Iterate through the first column to rename duplicates
for index in range(len(report_df)):
item_name = report_df.iloc[index, 0] # Get the name in the first column
if item_name in name_count:
name_count[item_name] += 1
# Rename the item with an index suffix
report_df.iloc[index, 0] = f"{item_name}_{name_count[item_name]}"
else:
name_count[item_name] = 1 # Initialize count for the first occurrence
# Set the DF index
report_df.index = report_df[0]
report_df.index.name = 'account_name'
report_df = report_df.drop(0, axis=1)
# Sanitize it of illegal characters
report_df = report_df.replace('[\[\]\$,)]', '', regex = True)\
.replace('[(]', '-', regex = True)\
.replace('', 'NaN', regex = True)
# Convert data values to floats. "Unlimited" and other text may be present, so ignore for now. Could convert them to NaNs also
report_df = report_df.astype(dtype = float, errors = 'ignore')
# Drop rows with all NaN's
#report_df = report_df.dropna(how="all")
# Set column names to the headers we stored. Remember we have a list of lists. Do some cleaning
# If there is only one list/row of column headers, we want to drop the first element (which basically holds the table name). Otherwise rely on the last row to be the dates / headings we want.
# TD-DO: Better optimization for multi-line headers etc, also integrate section headers
try:
headers_list = []
if len(report_headers_list) == 1:
headers_list = self.make_unique_string_list(report_headers_list[0][1:])
elif len(report_headers_list) > 1:
headers_list = self.make_unique_string_list(report_headers_list[-1])
else:
logging.warning(f'Unexpected fin report header structure. Possibly empty. Object: {report_headers_list}.\nDataframe structure will be incomplete.')
report_df = report_df.set_axis(headers_list, axis='columns')
except Exception as e:
logging.error(f"Failed to read/set column headers for dataframe of financial report. Error: {e}.")
return report_df
# At the moment am relying on XBRL enabled filings which contain 'reports' organizing financial statements (see github/cchummer/sec-api)
def parse_financial_statements(self):
reports_list = []
logging.info('Attempting to parse financial statements')
# Check that a FilingSummary.xml exists. It will contain information on reports present
reports_summary = self.search_filing_for_doc_text('filingsummary.xml')
if not reports_summary:
logging.info('No FilingSummary.xml was found.')
# TODO implement manual HTML table parsing (or pd.read_html())
return reports_list
# Find reports
found_reports = self.list_xbrl_reports(reports_summary, report_category='statements')
if not found_reports:
logging.info('No financial statement reports found.')
return reports_list
# Parse/scrape them
for fin_report in found_reports:
logging.info(f'Parsing report: {fin_report["short_name"]}.')
report_text = self.search_filing_for_doc_text(fin_report['doc_name'])
if report_text:
scraped_report = self.parse_xbrl_fin_report(report_text.lower())
else:
logging.warning('Failed to find report document in filing full text.')
scraped_report = {}
# Save report info so far
report_dict = {}
report_dict['report_doc'] = fin_report['doc_name']
report_dict['report_name'] = fin_report['short_name']
report_dict['report_raw_text'] = None
report_dict['report_parsed_data'] = scraped_report
try:
report_dict['report_title_read'] = scraped_report['headers'][0][0]
except:
logging.warning(f'Unable to read report title from parsed contents. Report name: {fin_report["short_name"]}.')
# Save to dataframe
report_dict['report_df'] = None
report_df = self.parsed_fin_report_to_df(scraped_report)
if report_df is not None and not report_df.empty:
try:
report_dict['report_df'] = report_df.to_json(orient='index')
except Exception as e:
logging.error(f'Exception thrown writing {fin_report["short_name"]} to dictionary. Error: {e}.')
else:
logging.warning(f'Parsed report {fin_report["short_name"]} DF was returned empty. No data being saved.')
reports_list.append(report_dict)
logging.info(f'Finished parsing report {fin_report["short_name"]}.')
return reports_list
# Helper functions for cleaning filing text
# unicode.normalize leaves behind a couple of not technically whitespace control-characters. See https://www.geeksforgeeks.org/python-program-to-remove-all-control-characters/ and http://www.unicode.org/reports/tr44/#GC_Values_Table
def remove_control_characters(self, s):
return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C")
# Cleans the given text (specifically: unicode normalize and turn newlines/whitespace into a single space)
def clean_filing_text(self, text_to_clean):
clean_text = unicodedata.normalize('NFKD', text_to_clean)
clean_text = self.remove_control_characters(clean_text)
clean_text = clean_text.replace('\n', ' ') # Split doesn't catch newlines from my testing
clean_text = " ".join(clean_text.split()) # Split string along tabs and spaces, then rejoin the parts with single spaces instead
return clean_text
# Attempts to extract data from the given XBRL 'notes' report, mainly targetting text data
# TODO better handling of tables in these reports
def parse_xbrl_note_report(self, note_text):
# Returned structure
table_data = {
"header_vals" : [],
"text_vals" : []
}
report_soup = BeautifulSoup(note_text, 'html.parser')
# In case there are multiple tables in the document, loop through all of those labeled with the "report" class. Tables of other classes (i.e. of type "authRefData") are ignored.
for table_index, current_table in enumerate(report_soup.find_all('table', class_ = "report")):
# Loop through rows
for row_index, current_row in enumerate(current_table.find_all('tr')):
# Header row if <th> element is found
header_columns = current_row.find_all('th')
if header_columns:
# Strip the text from each column and append it to headers master list
for hdr_column in header_columns:
table_data["header_vals"].append(hdr_column.text.strip())
# Not a header row, look for columns of class "text"
else:
# Strip the text from each column and append it to text_vals master list
# TODO: Optimize for tables within note. Formatting is a bit janky / unpreserved right now
for txt_column in current_row.find_all('td', class_ = "text"):
# Loop through the children of the text column
for child in txt_column.children:
# Ignore empty paragraphs/spacers
child_text = self.clean_filing_text(child.text.strip())
if len(child_text):
table_data["text_vals"].append(child_text)
return table_data
# Helper function to below
# Attempts to locate a table of contents by looking for a <table> element containing one or more <href> elements
# Returns the bs4.Element.Tag object of that table if it exists, or None
def linked_toc_exists(self, document_soup):
# Find all <table> tags
all_tables = document_soup.find_all('table')
for cur_table in all_tables:
# Look for an <a href=...>
links = cur_table.find_all('a', attrs = { 'href' : True })
if len(links):
return cur_table
return None
# Helper method to find_section_with_toc, extracts the text found inbetween 2 bs4 Tags/elements
def text_between_tags(self, start, end):
cur = start
found_text = ""
# Loop through all elements inbetween the two
while cur and cur != end:
if isinstance(cur, NavigableString):
text = cur.strip()
if len(text):
found_text += "{} ".format(text)
cur = cur.next_element
return self.clean_filing_text(found_text.strip()) # Strip trailing space that the above pattern will result in
# Helper method to find_section_with_toc, extracts the text found starting at a given tag through the end of the soup
def text_starting_at_tag(self, start):
cur = start
found_text = ""
# Loop through all elements
while cur:
if isinstance(cur, NavigableString):
text = cur.strip()
if len(text):
found_text += "{} ".format(text)
cur = cur.next_element
return self.clean_filing_text(found_text.strip())
# Support method for find_section_with_toc, attempt to determine if the given text is simple a page number (duplicate link in my observations)
def is_text_page_number(self, question_text):
# Check argument
if type(question_text) != str:
logging.warning("Non-string passed to is_text_page_number. Returning True (will result in href being skipped)")
return True
# Strip just to be sure
stripped_question_text = question_text.strip()
# Check if text is only digits
if stripped_question_text.isnumeric():
return True
# Check if only roman numerals
valid_romans = ["M", "D", "C", "L", "X", "V", "I", "(", ")"]
is_roman = True
for letter in stripped_question_text.upper():
if letter not in valid_romans:
is_roman = False
break
return is_roman
"""
Use the hyperlinked TOC to find the given text section. Provide a bs4 Tag object for the located TOC. Returns a list of dictionaries:
[
{
"section_name": "...",
"section_raw_text": "...",
"section_parsed_text": "..."
},
...
]
"""
def find_sections_with_toc(self, document_soup, toc_soup):
# Returned list
section_list = []
# First, loop through the <a> tags of the TOC and build a dictionary of href anchor values and text (sections) values
link_dict = {}
link_tags = toc_soup.find_all('a', attrs = { 'href' : True })
for link_tag in link_tags:
# From some TOC's I have examined, there may be a second <a href...> for each section, labeled instead by the page number. This page number may be a digit or a roman numeral
# If I come across a filing with a different TOC strcture, I will find a more nuanced way to handle it. For now simply check if the text is only digits or roman numerals
# Some TOC's also look to have a third link to each section, on the far left of the table and with the text "Item 1, Item 2, ...". Again will update if these appear after the properly labeled links and thus
# over-write that spot in the href dict defined below. As of now we are relying on the properly/fully labeled links being the last non-page-number reference to each href in order to be recorded.
if self.is_text_page_number(link_tag.text.strip()):
continue
link_dict[link_tag.get('href').replace('#', '')] = self.clean_filing_text(link_tag.text.strip())
# Grab a list of destination anchors (<a> or <div> tags with "id" or "name" attribute)
link_dests = document_soup.find_all('a', attrs = { 'id' : True }) + document_soup.find_all('a', attrs = { 'name' : True })\
+ document_soup.find_all('div', attrs = { 'id' : True }) + document_soup.find_all('div', attrs = { 'name' : True })
# Filter out those which are never linked to, they will obstruct our logic in text_between_tags as we rely on the next anchor to be the beginning of the next section
# I have run into filings with such "phantom" anchors that are never linked to and can prematurely signal the end of a section
# (i.e: https://www.sec.gov/Archives/edgar/data/1331451/000133145118000076/0001331451-18-000076.txt)
link_dests = [anchor for anchor in link_dests if (anchor.get('id') in link_dict.keys() or anchor.get('name') in link_dict.keys())]
# Now loop through the target sections that we just found links to. We will try to locate the destination of each
for target_href, target_name in link_dict.items():
# The href values are used at their destination in <a> tags with an id/name attribute of the same href value (minus the leading #, why we got rid of it)
# Loop through the link_dests list of all destination tags, and find the one with id/name=target_href
num_destinations = len(link_dests)
for dest_index, link_dest in enumerate(link_dests):
if (link_dest.get('id') == target_href or link_dest.get('name') == target_href): # Can be either id or name according to HTML spec (see https://stackoverflow.com/questions/484719/should-i-make-html-anchors-with-name-or-id)
# Grab the text inbetween the current destination tag and the next occuring destination in link_dests
# If we are on the last destination, grab all the text left
section_text = ""
if dest_index + 1 < num_destinations:
section_text = self.text_between_tags(link_dest, link_dests[dest_index + 1])
else:
section_text = self.text_starting_at_tag(link_dest)
if section_text:
section_info = {}
section_info['section_name'] = target_name
section_info['section_raw_text'] = None
section_info['section_parsed_text'] = section_text
# Add to master list
section_list.append(section_info)
return section_list
# Attempts to grab any existent notes to the financial statements, and all text sections
def parse_text_sections(self):
sections_list = []
logging.info('Attempting to parse filing text sections.')
# Look for notes accompanying financials, in XBRL enabled filings will be their own reports
reports_summary = self.search_filing_for_doc_text('filingsummary.xml')
if reports_summary:
found_notes = self.list_xbrl_reports(reports_summary, report_category='notes')
if found_notes:
for note in found_notes:
logging.info(f'Parsing note to financial statement: {note["short_name"]}.')
note_text = self.search_filing_for_doc_text(note['doc_name'])
if note_text:
scraped_note = self.parse_xbrl_note_report(note_text.lower())
else:
logging.warning('Failed to find note document in filing full text.')
scraped_note = {}
text_section_info = {}
text_section_info['section_doc'] = note['doc_name']
text_section_info['section_name'] = note['short_name']
text_section_info['section_type'] = 'xbrl_note' # Denotes difference in scraped_note format
text_section_info['section_raw_text'] = None
text_section_info['section_parsed_text'] = scraped_note # Will be a dictionary
sections_list.append(text_section_info)
logging.info(f'Finished parsing note: {note["short_name"]}.')
logging.info('Finished parsing notes to financial statements.')
# Now look for more traditional text sections
# TODO: ATM, relying on a linked TOC to navigate filing sections. Develop more robust method
# Loop through all documents in the filing
docs_list = self.split_filing_documents()
if not docs_list:
logging.warning('Failed to split filing into documents')
for doc_info in docs_list:
# Only parse HTM/HTML files
if not doc_info['doc_filename'].lower().endswith('.htm'):
continue
doc_html = BeautifulSoup(doc_info['doc_text'].lower(), "html.parser")
# Will hold results from current document
doc_sections = []
logging.info(f'Parsing filing HTML document ({doc_info["doc_filename"]}) for TOC.')
# Parse using TOC if it exists
# TODO: BETTER PARSING / STORING OF TABLES FOUND IN TEXT SECTIONS
toc_tag = self.linked_toc_exists(doc_html)
if toc_tag:
doc_sections = self.find_sections_with_toc(doc_html, toc_tag)
else:
logging.warning(f'Could not find a hyperlinked TOC to crawl for text sections. Parsing whole file {doc_info["doc_filename"]} as one section.')
sections_list.append({
'section_doc': doc_info['doc_filename'],
'section_name': f'doc-{doc_info["doc_filename"]}',
'section_type': 'html_whole_doc',
'section_raw_text': None,
'section_parsed_text': doc_html.get_text(separator='\n', strip=True)
})
# We will enforce section name uniqueness on a document level
existing_section_names = set()
# Loop through results, add to the master dict
if doc_sections:
for result_section_data in doc_sections:
logging.info(f'Parsing {doc_info["doc_filename"]} section: {result_section_data["section_name"]}')
section_key_name = result_section_data['section_name']
i = 1
# Check for duplicates within the document using the set
while section_key_name in existing_section_names:
section_key_name = f"{section_key_name}_{i}"
i += 1
# Add to dict after finding unused key
text_section_info = {}
text_section_info['section_doc'] = doc_info['doc_filename']
text_section_info['section_name'] = section_key_name
text_section_info['section_type'] = 'linked_toc_section'
text_section_info['section_raw_text'] = result_section_data['section_raw_text']
text_section_info['section_parsed_text'] = result_section_data['section_parsed_text'] # Will be a string in this case
sections_list.append(text_section_info)
existing_section_names.add(section_key_name) # Update the set with the new name
logging.info(f'Finished parsing section: {result_section_data["section_name"]}')
return sections_list
def full_parse(self):
self.financial_statements = self.parse_financial_statements()
self.text_sections = self.parse_text_sections()
return self.construct_parsed_output()
def construct_parsed_output(self):
return {
'filing_info': self.filing_info,
'financial_statements': self.financial_statements,
'text_sections': self.text_sections
}
def __repr__(self):
return 'FinancialFilingParser'
'''
13F parser
Returns the filing_info and a holdings report object for a 13F filing. Dict structure: