datamule 0.416__cp310-cp310-win_amd64.whl → 0.418__cp310-cp310-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of datamule might be problematic. Click here for more details.

@@ -0,0 +1,70 @@
1
+ from xml.etree import ElementTree as ET
2
+
3
+ def element_to_dict(elem):
4
+ """Convert an XML element to dict preserving structure."""
5
+ result = {}
6
+
7
+ # Add attributes directly to result
8
+ if elem.attrib:
9
+ result.update(elem.attrib)
10
+
11
+ # Add text content if present and no children
12
+ if elem.text and elem.text.strip():
13
+ text = elem.text.strip()
14
+ if not len(elem): # No children
15
+ return text
16
+ else:
17
+ result['text'] = text
18
+
19
+ # Process children
20
+ for child in elem:
21
+ child_data = element_to_dict(child)
22
+ child_tag = child.tag.split('}')[-1] # Remove namespace
23
+
24
+ if child_tag in result:
25
+ # Convert to list if multiple elements
26
+ if not isinstance(result[child_tag], list):
27
+ result[child_tag] = [result[child_tag]]
28
+ result[child_tag].append(child_data)
29
+ else:
30
+ result[child_tag] = child_data
31
+
32
+ return result
33
+
34
+ def parse_form_d(filepath):
35
+ """Parse Form D XML file into metadata and document sections."""
36
+ # Parse XML
37
+ tree = ET.parse(filepath)
38
+ root = tree.getroot()
39
+
40
+ # Remove namespaces for cleaner processing
41
+ for elem in root.iter():
42
+ if '}' in elem.tag:
43
+ elem.tag = elem.tag.split('}')[-1]
44
+
45
+ # Convert entire document to dict
46
+ full_dict = element_to_dict(root)
47
+
48
+ # Separate metadata and document content
49
+ result = {
50
+ 'metadata': {},
51
+ 'document': {}
52
+ }
53
+
54
+ # Extract metadata
55
+ metadata_fields = {
56
+ 'schemaVersion',
57
+ 'submissionType',
58
+ 'testOrLive',
59
+ 'primaryIssuer' # Including all issuer information in metadata
60
+ }
61
+
62
+ for field in metadata_fields:
63
+ if field in full_dict:
64
+ result['metadata'][field] = full_dict[field]
65
+ del full_dict[field] # Remove from full_dict to avoid duplication
66
+
67
+ # Everything else goes to document
68
+ result['document'] = full_dict
69
+
70
+ return result
@@ -0,0 +1,78 @@
1
+ # Parses e.g. 10-K, 10-Q,..... any form with items and/or parts
2
+ from .helper import load_file_content, clean_title, clean_text
3
+ from pathlib import Path
4
+ import re
5
+
6
+ # OK figured out general pattern
7
+ # find toc
8
+ # figure out mapping. we do need it
9
+ # just do mapping tonight
10
+
11
+ pattern = re.compile(r'^\s*(?:item\s+\d+(?:\.\d+)?(?:[a-z])?|signature(?:\.?s)?)\s*', re.I | re.M)
12
+
13
+ def find_anchors(content):
14
+ anchors = []
15
+ prev_title = None
16
+
17
+ for part_match in pattern.finditer(content):
18
+ title = clean_title(part_match.group())
19
+ # Skip duplicates, e.g. "item 1" and "item1 continued"
20
+ if prev_title == title:
21
+ continue
22
+ prev_title = title
23
+ anchors.append((title, part_match.start()))
24
+
25
+ return anchors
26
+
27
+ # I think this works, but I haven't tested it extensively.
28
+ def map_sections(content, anchors):
29
+ positions = anchors + [('end', len(content))]
30
+
31
+ result = {}
32
+ for i, (title, start) in enumerate(positions[:-1]):
33
+ _, next_start = positions[i + 1]
34
+ section_text = content[start:next_start].strip()
35
+ result[title.lower()] = clean_text(section_text)
36
+
37
+ def sort_key(x):
38
+ match = re.search(r'item\s+(\d+)(?:[\.a-z])?', x[0], re.I)
39
+ if not match:
40
+ return float('inf')
41
+ num = match.group(0).lower()
42
+ # This will sort 1, 1a, 1b, 2, 2a etc
43
+ return float(re.findall(r'\d+', num)[0]) + (ord(num[-1]) - ord('a') + 1) / 100 if num[-1].isalpha() else float(re.findall(r'\d+', num)[0])
44
+
45
+ return dict(sorted(result.items(), key=sort_key))
46
+
47
+ # def find_content_start(anchors):
48
+ # def find_first_non_repeating(seq):
49
+ # for i in range(len(seq)):
50
+ # remaining = seq[i:]
51
+ # # Get same length subsequence from the next position
52
+ # next_seq = seq[i + 1:i + 1 + len(remaining)]
53
+ # if remaining != next_seq and len(next_seq) > 0:
54
+ # return i
55
+ # return 0 # Default to start if no pattern found
56
+
57
+ # return find_first_non_repeating([title for title, _ in anchors])
58
+
59
+ def generalized_parser(filename):
60
+ # load content
61
+ content = load_file_content(filename)
62
+
63
+ # find anchors
64
+ anchors = find_anchors(content)
65
+
66
+ # Skip tables of contents. Not implemented yet, since we overwrite the keys anyway.
67
+ # content_start = find_content_start(anchors)
68
+ # print(content_start)
69
+
70
+ result = {}
71
+ # assign metadata
72
+ result["metadata"] = {"document_name": Path(filename).stem}
73
+
74
+ # extract sections, assign text based on mapping_dict
75
+ result['document'] = map_sections(content, anchors)
76
+
77
+ return result
78
+
@@ -0,0 +1,75 @@
1
+ from selectolax.parser import HTMLParser
2
+ import re
3
+
4
+ # This will be modified in the future to remove SEC specific code such as <PAGE> tags
5
+ def load_text_content(filename):
6
+ with open(filename) as f:
7
+ return f.read().translate(str.maketrans({
8
+ '\xa0': ' ', '\u2003': ' ',
9
+ '\u2018': "'", '\u2019': "'",
10
+ '\u201c': '"', '\u201d': '"'
11
+ }))
12
+
13
+ def load_html_content(filename):
14
+ parser = HTMLParser(open(filename).read())
15
+
16
+ # Remove hidden elements first
17
+ hidden_nodes = parser.css('[style*="display: none"], [style*="display:none"], .hidden, .hide, .d-none')
18
+ for node in hidden_nodes:
19
+ node.decompose()
20
+
21
+ blocks = {'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'article', 'section', 'li', 'td'}
22
+ lines = []
23
+ current_line = []
24
+
25
+ def flush_line():
26
+ if current_line:
27
+ lines.append(' '.join(current_line))
28
+ current_line.clear()
29
+
30
+ for node in parser.root.traverse(include_text=True):
31
+ if node.tag in ('script', 'style', 'css'):
32
+ continue
33
+
34
+ if node.tag in blocks:
35
+ flush_line()
36
+ lines.append('')
37
+
38
+ if node.text_content:
39
+ text = node.text_content.strip()
40
+ if text:
41
+ if node.tag in blocks:
42
+ flush_line()
43
+ lines.append(text)
44
+ lines.append('')
45
+ else:
46
+ current_line.append(text)
47
+
48
+ flush_line()
49
+
50
+ text = '\n'.join(lines)
51
+ while '\n\n\n' in text:
52
+ text = text.replace('\n\n\n', '\n\n')
53
+
54
+ return text.translate(str.maketrans({
55
+ '\xa0': ' ', '\u2003': ' ',
56
+ '\u2018': "'", '\u2019': "'",
57
+ '\u201c': '"', '\u201d': '"'
58
+ }))
59
+ def load_file_content(filename):
60
+ if filename.suffix =='.txt':
61
+ return load_text_content(filename)
62
+ elif filename.suffix in ['.html','.htm']:
63
+ return load_html_content(filename)
64
+ else:
65
+ raise ValueError(f"Unsupported file type: {filename}")
66
+
67
+ def clean_title(title: str) -> str:
68
+ """Clean up section title by removing newlines, periods, and all whitespace, converting to lowercase."""
69
+ return ''.join(title.replace('\n', '').replace('.', '').split()).lower()
70
+
71
+ # This is a bit hacky, removes PART IV, PART V etc from the end of the text
72
+ # we do this to avoid having to map for general cases
73
+ def clean_text(text):
74
+ text = text.strip()
75
+ return re.sub(r'\s*PART\s+[IVX]+\s*$', '', text, flags=re.I)
@@ -0,0 +1,41 @@
1
+ from xml.etree import ElementTree as ET
2
+
3
+ def parse_13f_hr_information_table_xml(xml_file):
4
+ # Parse the XML file
5
+ tree = ET.parse(xml_file)
6
+ root = tree.getroot()
7
+
8
+ data = []
9
+
10
+ # Iterate through each infoTable
11
+ for info_table in root.findall('.//{*}infoTable'):
12
+ row = {
13
+ 'NAMEOFISSUER': info_table.findtext('.//{*}nameOfIssuer') or '',
14
+ 'TITLEOFCLASS': info_table.findtext('.//{*}titleOfClass') or '',
15
+ 'CUSIP': info_table.findtext('.//{*}cusip') or '',
16
+ 'FIGI': info_table.findtext('.//{*}figi') or '',
17
+ 'VALUE': info_table.findtext('.//{*}value') or '',
18
+ 'SSHPRNAMT': '',
19
+ 'SSHPRNAMTTYPE': '',
20
+ 'PUTCALL': info_table.findtext('.//{*}putCall') or '',
21
+ 'INVESTMENTDISCRETION': info_table.findtext('.//{*}investmentDiscretion') or '',
22
+ 'OTHERMANAGER': info_table.findtext('.//{*}otherManager') or '',
23
+ 'VOTING_AUTH_SOLE': '',
24
+ 'VOTING_AUTH_SHARED': '',
25
+ 'VOTING_AUTH_NONE': ''
26
+ }
27
+
28
+ shrs_or_prn_amt = info_table.find('.//{*}shrsOrPrnAmt')
29
+ if shrs_or_prn_amt is not None:
30
+ row['SSHPRNAMT'] = shrs_or_prn_amt.findtext('.//{*}sshPrnamt') or ''
31
+ row['SSHPRNAMTTYPE'] = shrs_or_prn_amt.findtext('.//{*}sshPrnamtType') or ''
32
+
33
+ voting_authority = info_table.find('.//{*}votingAuthority')
34
+ if voting_authority is not None:
35
+ row['VOTING_AUTH_SOLE'] = voting_authority.findtext('.//{*}Sole') or ''
36
+ row['VOTING_AUTH_SHARED'] = voting_authority.findtext('.//{*}Shared') or ''
37
+ row['VOTING_AUTH_NONE'] = voting_authority.findtext('.//{*}None') or ''
38
+
39
+ data.append(row)
40
+
41
+ return data
@@ -0,0 +1,158 @@
1
+ from xml.etree import ElementTree as ET
2
+ from typing import Dict, Any, Optional
3
+
4
+ def get_footnotes(doc) -> dict:
5
+ """Extract footnotes into a lookup dictionary."""
6
+ return {
7
+ f.attrib.get('id', ''): f.text.strip()
8
+ for f in doc.findall('.//footnotes/footnote')
9
+ }
10
+
11
+ def get_value_and_footnote(elem, footnotes: dict) -> dict:
12
+ """Get value and footnote for a field."""
13
+ result = {'value': ''}
14
+
15
+ if elem is None:
16
+ return result
17
+
18
+ # Get value
19
+ value_elem = elem.find('.//value')
20
+ if value_elem is not None:
21
+ result['value'] = value_elem.text or ''
22
+
23
+ # Get footnote if exists
24
+ footnote_elem = elem.find('.//footnoteId')
25
+ if footnote_elem is not None:
26
+ footnote_id = footnote_elem.attrib.get('id', '')
27
+ if footnote_id in footnotes:
28
+ result['footnote'] = footnotes[footnote_id]
29
+
30
+ return result
31
+
32
+ def parse_form345(filepath) -> Dict[str, Any]:
33
+ """Parse SEC Form XML with enhanced data extraction."""
34
+ doc = ET.parse(filepath).getroot()
35
+ if doc is None:
36
+ return {"error": "No ownershipDocument found"}
37
+
38
+ footnotes = get_footnotes(doc)
39
+
40
+ result = {
41
+ 'metadata': {
42
+ 'schemaVersion': doc.findtext('schemaVersion', ''),
43
+ 'documentType': doc.findtext('documentType', ''),
44
+ 'periodOfReport': doc.findtext('periodOfReport', ''),
45
+ 'dateOfOriginalSubmission': doc.findtext('dateOfOriginalSubmission', ''),
46
+ 'form3HoldingsReported': doc.findtext('form3HoldingsReported', ''),
47
+ 'form4TransactionsReported': doc.findtext('form4TransactionsReported', ''),
48
+ 'issuer': {
49
+ 'cik': doc.findtext('.//issuerCik', ''),
50
+ 'name': doc.findtext('.//issuerName', ''),
51
+ 'tradingSymbol': doc.findtext('.//issuerTradingSymbol', '')
52
+ },
53
+ 'reportingOwner': {
54
+ 'cik': doc.findtext('.//rptOwnerCik', ''),
55
+ 'name': doc.findtext('.//rptOwnerName', ''),
56
+ 'address': {
57
+ 'street1': doc.findtext('.//rptOwnerStreet1', ''),
58
+ 'street2': doc.findtext('.//rptOwnerStreet2', ''),
59
+ 'city': doc.findtext('.//rptOwnerCity', ''),
60
+ 'state': doc.findtext('.//rptOwnerState', ''),
61
+ 'zip': doc.findtext('.//rptOwnerZipCode', ''),
62
+ 'stateDescription': doc.findtext('.//rptOwnerStateDescription', '')
63
+ },
64
+ 'relationship': {
65
+ 'isDirector': doc.findtext('.//isDirector', ''),
66
+ 'isOfficer': doc.findtext('.//isOfficer', ''),
67
+ 'isTenPercentOwner': doc.findtext('.//isTenPercentOwner', ''),
68
+ 'isOther': doc.findtext('.//isOther', ''),
69
+ 'officerTitle': doc.findtext('.//officerTitle', '')
70
+ }
71
+ },
72
+ 'signature': {
73
+ 'name': doc.findtext('.//signatureName', ''),
74
+ 'date': doc.findtext('.//signatureDate', '')
75
+ }
76
+ },
77
+ 'holdings': []
78
+ }
79
+
80
+ # Parse non-derivative holdings/transactions
81
+ for entry in doc.findall('.//nonDerivativeTable/*'):
82
+ holding = {
83
+ 'type': 'non-derivative',
84
+ 'securityTitle': get_value_and_footnote(entry.find('.//securityTitle'), footnotes),
85
+ 'postTransactionAmounts': {
86
+ 'sharesOwned': get_value_and_footnote(entry.find('.//sharesOwnedFollowingTransaction'), footnotes)
87
+ },
88
+ 'ownershipNature': {
89
+ 'directOrIndirect': entry.findtext('.//directOrIndirectOwnership/value', '')
90
+ }
91
+ }
92
+
93
+ # Add transaction fields if present
94
+ if 'Transaction' in entry.tag:
95
+ transactionCoding = {
96
+ 'formType': entry.findtext('.//transactionFormType', ''),
97
+ 'code': entry.findtext('.//transactionCode', ''),
98
+ 'equitySwapInvolved': entry.findtext('.//equitySwapInvolved', '')
99
+ }
100
+
101
+ transactionAmounts = {
102
+ 'shares': get_value_and_footnote(entry.find('.//transactionShares'), footnotes),
103
+ 'pricePerShare': get_value_and_footnote(entry.find('.//transactionPricePerShare'), footnotes),
104
+ 'acquiredDisposedCode': get_value_and_footnote(entry.find('.//transactionAcquiredDisposedCode'), footnotes)
105
+ }
106
+
107
+ holding.update({
108
+ 'transactionDate': get_value_and_footnote(entry.find('.//transactionDate'), footnotes),
109
+ 'transactionCoding': transactionCoding,
110
+ 'transactionAmounts': transactionAmounts
111
+ })
112
+
113
+ result['holdings'].append(holding)
114
+
115
+ # Parse derivative holdings/transactions
116
+ for entry in doc.findall('.//derivativeTable/*'):
117
+ holding = {
118
+ 'type': 'derivative',
119
+ 'securityTitle': get_value_and_footnote(entry.find('.//securityTitle'), footnotes),
120
+ 'conversionOrExercisePrice': get_value_and_footnote(entry.find('.//conversionOrExercisePrice'), footnotes),
121
+ 'exerciseDate': get_value_and_footnote(entry.find('.//exerciseDate'), footnotes),
122
+ 'expirationDate': get_value_and_footnote(entry.find('.//expirationDate'), footnotes),
123
+ 'underlyingSecurity': {
124
+ 'title': get_value_and_footnote(entry.find('.//underlyingSecurityTitle'), footnotes),
125
+ 'shares': get_value_and_footnote(entry.find('.//underlyingSecurityShares'), footnotes)
126
+ },
127
+ 'postTransactionAmounts': {
128
+ 'sharesOwned': get_value_and_footnote(entry.find('.//sharesOwnedFollowingTransaction'), footnotes)
129
+ },
130
+ 'ownershipNature': {
131
+ 'directOrIndirect': entry.findtext('.//directOrIndirectOwnership/value', ''),
132
+ 'nature': entry.findtext('.//natureOfOwnership/value', '')
133
+ }
134
+ }
135
+
136
+ # Add transaction-specific fields
137
+ if 'Transaction' in entry.tag:
138
+ transactionCoding = {
139
+ 'formType': entry.findtext('.//transactionFormType', ''),
140
+ 'code': entry.findtext('.//transactionCode', ''),
141
+ 'equitySwapInvolved': entry.findtext('.//equitySwapInvolved', '')
142
+ }
143
+
144
+ transactionAmounts = {
145
+ 'shares': get_value_and_footnote(entry.find('.//transactionShares'), footnotes),
146
+ 'pricePerShare': get_value_and_footnote(entry.find('.//transactionPricePerShare'), footnotes),
147
+ 'acquiredDisposedCode': get_value_and_footnote(entry.find('.//transactionAcquiredDisposedCode'), footnotes)
148
+ }
149
+
150
+ holding.update({
151
+ 'transactionDate': get_value_and_footnote(entry.find('.//transactionDate'), footnotes),
152
+ 'transactionCoding': transactionCoding,
153
+ 'transactionAmounts': transactionAmounts
154
+ })
155
+
156
+ result['holdings'].append(holding)
157
+
158
+ return result
@@ -0,0 +1,95 @@
1
+ # I will liekely move this file to a more appropriate location in the future
2
+
3
+ mapping_dict_10k = {
4
+ 'filing_summary': 'Annual report providing comprehensive overview of company business, financial performance, risks, and operations. Contains audited financial statements, business description, risk analysis, and detailed operational metrics.',
5
+
6
+ 'structure': {
7
+ 'part1': {
8
+ 'summary': 'Overview of company operations, risks, and material business information. Contains key business strategy, market position, competitive landscape, and significant challenges.',
9
+ 'item1': {
10
+ 'summary': 'Detailed description of business operations including primary products/services, markets served, distribution methods, competitive conditions, regulatory environment, and business segments'
11
+ },
12
+ 'item1a': {
13
+ 'summary': 'Comprehensive list and explanation of significant risks and uncertainties that could affect business performance, financial condition, and stock value'
14
+ },
15
+ 'item1b': {
16
+ 'summary': 'Disclosure of any unresolved comments or issues raised by SEC staff regarding company filings'
17
+ },
18
+ 'item1c': {
19
+ 'summary': 'Information about cybersecurity risks, incidents, risk management, governance, and strategy'
20
+ },
21
+ 'item2': {
22
+ 'summary': 'Description of principal physical properties, including manufacturing facilities, offices, warehouses, and other significant real estate'
23
+ },
24
+ 'item3': {
25
+ 'summary': 'Description of material pending legal proceedings, including potential impacts on business'
26
+ },
27
+ 'item4': {
28
+ 'summary': 'Disclosure of mine safety violations, citations, and orders received under the Mine Act'
29
+ }
30
+ },
31
+ 'part2': {
32
+ 'summary': 'Detailed financial performance analysis, including management insights, market risks, and complete audited financial statements.',
33
+ 'item5': {
34
+ 'summary': 'Information about company stock, including market data, price history, dividends, share repurchases, and securities offerings'
35
+ },
36
+ 'item6': {
37
+ 'summary': 'Selected historical financial data showing trends in financial condition and results over past 5 years'
38
+ },
39
+ 'item7': {
40
+ 'summary': 'Management\'s analysis of financial condition, operations results, liquidity, capital resources, and future outlook'
41
+ },
42
+ 'item7a': {
43
+ 'summary': 'Discussion of exposure to market risk including interest rates, foreign exchange, commodities, and hedging activities'
44
+ },
45
+ 'item8': {
46
+ 'summary': 'Audited financial statements, including balance sheets, income statements, cash flows, and comprehensive notes'
47
+ },
48
+ 'item9': {
49
+ 'summary': 'Information about changes in independent auditors and any disagreements with them'
50
+ },
51
+ 'item9a': {
52
+ 'summary': 'Management\'s assessment of internal control effectiveness over financial reporting'
53
+ },
54
+ 'item9b': {
55
+ 'summary': 'Other significant information not reported elsewhere in the filing'
56
+ }
57
+ },
58
+ 'part3': {
59
+ 'summary': 'Information about company leadership, compensation structures, and corporate governance practices.',
60
+ 'item10': {
61
+ 'summary': 'Information about directors and executive officers, including their experience, qualifications, and corporate governance practices'
62
+ },
63
+ 'item11': {
64
+ 'summary': 'Detailed information about executive compensation, including salary, bonuses, stock awards, and compensation policies'
65
+ },
66
+ 'item12': {
67
+ 'summary': 'Information about beneficial ownership of securities by management and major shareholders, equity compensation plans'
68
+ },
69
+ 'item13': {
70
+ 'summary': 'Description of transactions with related parties and potential conflicts of interest'
71
+ },
72
+ 'item14': {
73
+ 'summary': 'Disclosure of fees paid for audit and non-audit services provided by independent accountants'
74
+ }
75
+ },
76
+ 'part4': {
77
+ 'summary': 'Supporting documentation and additional required disclosures.',
78
+ 'item15': {
79
+ 'summary': 'List of all exhibits, including material contracts, corporate documents, and supplementary financial information'
80
+ },
81
+ 'item16': {
82
+ 'summary': 'Optional summary of key information from the entire Form 10-K filing'
83
+ }
84
+ }
85
+ },
86
+
87
+ 'search_hints': {
88
+ 'financial_metrics': ['item6', 'item7', 'item8'],
89
+ 'risk_assessment': ['item1a', 'item1c', 'item7a'],
90
+ 'business_overview': ['item1', 'item2'],
91
+ 'leadership_info': ['item10', 'item11'],
92
+ 'material_events': ['item3', 'item9', 'item13'],
93
+ 'operational_data': ['item1', 'item7', 'item2']
94
+ }
95
+ }
@@ -0,0 +1,70 @@
1
+ from xml.etree import ElementTree as ET
2
+
3
+ def element_to_dict(elem):
4
+ """Convert an XML element to dict preserving structure."""
5
+ result = {}
6
+
7
+ # Add attributes directly to result
8
+ if elem.attrib:
9
+ result.update(elem.attrib)
10
+
11
+ # Add text content if present and no children
12
+ if elem.text and elem.text.strip():
13
+ text = elem.text.strip()
14
+ if not len(elem): # No children
15
+ return text
16
+ else:
17
+ result['text'] = text
18
+
19
+ # Process children
20
+ for child in elem:
21
+ child_data = element_to_dict(child)
22
+ child_tag = child.tag.split('}')[-1] # Remove namespace
23
+
24
+ if child_tag in result:
25
+ # Convert to list if multiple elements
26
+ if not isinstance(result[child_tag], list):
27
+ result[child_tag] = [result[child_tag]]
28
+ result[child_tag].append(child_data)
29
+ else:
30
+ result[child_tag] = child_data
31
+
32
+ return result
33
+
34
+ def parse_nport_p(filepath):
35
+ """Parse NPORT XML file into metadata and document sections."""
36
+ # Parse XML
37
+ tree = ET.parse(filepath)
38
+ root = tree.getroot()
39
+
40
+ # Remove namespaces for cleaner processing
41
+ for elem in root.iter():
42
+ if '}' in elem.tag:
43
+ elem.tag = elem.tag.split('}')[-1]
44
+
45
+ # Convert entire document to dict
46
+ full_dict = element_to_dict(root)
47
+
48
+ # Separate metadata and document content
49
+ result = {
50
+ 'metadata': {},
51
+ 'document': {}
52
+ }
53
+
54
+ # Extract metadata sections
55
+ if 'headerData' in full_dict:
56
+ result['metadata']['headerData'] = full_dict['headerData']
57
+
58
+ if 'formData' in full_dict and 'genInfo' in full_dict['formData']:
59
+ result['metadata']['genInfo'] = full_dict['formData']['genInfo']
60
+
61
+ # Everything else goes to document
62
+ result['document'] = full_dict
63
+
64
+ # Remove metadata sections from document to avoid duplication
65
+ if 'headerData' in result['document']:
66
+ del result['document']['headerData']
67
+ if 'formData' in result['document'] and 'genInfo' in result['document']['formData']:
68
+ del result['document']['formData']['genInfo']
69
+
70
+ return result
@@ -0,0 +1,73 @@
1
+ import xml.etree.ElementTree as ET
2
+ from .basic_8k_parser import parse_8k
3
+ from .basic_10k_parser import parse_10k
4
+ from .basic_10q_parser import parse_10q
5
+ from .information_table_parser_13fhr import parse_13f_hr_information_table_xml
6
+ from .insider_trading_parser import parse_form345
7
+ from .form_d_parser import parse_form_d
8
+ from .n_port_p_parser import parse_nport_p
9
+ from .basic_13d_parser import parse_13d
10
+ from .basic_13g_parser import parse_13g
11
+ from .generalized_item_parser import generalized_parser
12
+ from .mappings import *
13
+
14
+ class Parser:
15
+
16
+ def __init__(self):
17
+ pass
18
+
19
+ def parse_filing(self, filename, filing_type):
20
+ if filing_type == 'INFORMATION TABLE':
21
+ return parse_13f_hr_information_table_xml(filename)
22
+ elif filing_type == '8-K':
23
+ return parse_8k(filename)
24
+ elif filing_type == '10-K':
25
+ return parse_10k(filename)
26
+ elif filing_type == '10-Q':
27
+ return parse_10q(filename)
28
+ elif filing_type in ['3', '4', '5']:
29
+ return parse_form345(filename)
30
+ elif filing_type == 'D':
31
+ return parse_form_d(filename)
32
+ elif filing_type == 'NPORT-P':
33
+ return parse_nport_p(filename)
34
+ elif filing_type == 'SC 13D':
35
+ return parse_13d(filename)
36
+ elif filing_type == 'SC 13G':
37
+ return parse_13g(filename)
38
+ else:
39
+ raise ValueError(f'Filing type {filing_type} not supported')
40
+
41
+
42
+ def parse_company_concepts(self, data):
43
+
44
+ # get cik
45
+ cik = data['cik']
46
+ # get categories
47
+ categories = list(data['facts'].keys())
48
+
49
+ table_dict_list = []
50
+ for category in categories:
51
+ for fact in data['facts'][category]:
52
+ label = data['facts'][category][fact]['label']
53
+ description = data['facts'][category][fact]['description']
54
+ units = list(data['facts'][category][fact]['units'].keys())
55
+
56
+ for unit in units:
57
+ table = data['facts'][category][fact]['units'][unit]
58
+
59
+ # Find all unique keys across all rows
60
+ all_keys = set()
61
+ for row in table:
62
+ all_keys.update(row.keys())
63
+
64
+ # Ensure all rows have all keys
65
+ for row in table:
66
+ for key in all_keys:
67
+ if key not in row:
68
+ row[key] = None
69
+
70
+ table_dict = {'cik':cik, 'category': category, 'fact': fact, 'label': label, 'description': description, 'unit': unit, 'table': table}
71
+ table_dict_list.append(table_dict)
72
+
73
+ return table_dict_list