-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathxbrl_to_json.py
1706 lines (1615 loc) · 75.8 KB
/
xbrl_to_json.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
import sys, os, shutil, logging, datetime, json, time, copy, re, random
import urllib.request
import bs4, anytree, anytree.exporter, anytree.importer
import xml.etree.ElementTree as ET
import pprint as pp
logging.basicConfig(format=' ---- %(filename)s|%(lineno)d ----\n%(message)s', level=logging.INFO)
clarks_to_ignore = ['http://www.w3.org/2001/XMLSchema',
'http://www.xbrl.org/2003/instance',
'http://www.xbrl.org/2003/linkbase',
'http://xbrl.org/2006/xbrldi',
]
unit_ref_list = []
MONTH_IN_SECONDS = 60.0 * 60 * 24 * 7 * 30
ANNUAL_FORM_TYPES = ["10-K", "20-F", "40-F"]
PREFIXES_THAT_MATTER = ["us-gaap", "dei", "srt", "country", "stpr", "custom"]
US_COUNTRY_CODES = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE",
"NV", "NH", "NJ","NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD",
"TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY", "X1", ]
CANADA_COUNTRY_CODES = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "B0", "Z4",]
def main_xbrl_to_json_converter(ticker, cik, date, folder_path, sic=None, country_code=None, delete_files_after_import=False):
root_node_dict = {}
potential_json_filename = return_xbrl_to_json_converted_filename_with_date(folder_path, ticker, date)
# logging.info(potential_json_filename)
''' first we try to import the json files'''
try:
root_json = import_json(potential_json_filename)
root_node = convert_dict_to_node_tree(root_json)
except Exception as e:
logging.error(e)
root_node = None
''' if we don't have the root node, we need to get it from the actual files '''
if not root_node:
logging.info("json file does not already exist, creating one...")
list_of_filenames_in_directory = os.listdir(folder_path)
''' we're going to iterate through the relevant xml/xsd files '''
for filename in list_of_filenames_in_directory:
if filename.endswith(".xml") or filename.endswith(".xsd"):
xbrl_filename = os.path.join(folder_path, filename)
logging.info("processing xbrl file: {}".format(xbrl_filename))
''' here we generate the root node '''
root_node = xbrl_to_json_processor(xbrl_filename, ticker, write_file=testing_write_file, write_txt_file=testing_write_file)
logging.info("done")
root_node_dict[filename] = root_node
''' here we build up the whole tree '''
fact_tree_root = fact_centric_xbrl_processor(root_node_dict, ticker, sic, country_code)
write_txt_file = not delete_files_after_import # if we're deleting files, lets not save a render.txt file
''' here get the root of the whole tree '''
root_node = xbrl_to_json_processor(potential_json_filename, ticker, root_node=fact_tree_root, write_file=True, write_txt_file=write_txt_file)
''' this is an important ^^^ function '''
if delete_files_after_import:
if os.path.isdir(folder_path):
shutil.rmtree(folder_path)
potential_txt_file = "{}.json_render.txt".format(folder_path)
if os.path.isfile(potential_txt_file):
os.remove(potential_txt_file)
return root_node
def return_refernce_node(node, fact_tree_root, other_tree_root, ticker):
''' we create a refernce node for the underlying node if it doesn't exist,
this will act as a parent node, since many nodes are related, but not directly.
Note that this will be a "parent node" in the sense that...
well, in the sense that it's a folder that contains related items
'''
local_prefixes_that_matter = PREFIXES_THAT_MATTER + [ticker.lower()]
reference_node = None
locator = None
href = node.attrib.get("{http://www.w3.org/1999/xlink}href")
if href:
locator = return_xlink_locator(node)
else:
if node.clark not in clarks_to_ignore:
locator = node.suffix
if locator:
''' if a locator is present, this should be a fact item.
here, with the prefixes_that_matter we're looking at locators that start with
us-gaap_ or similar. This is, unfortunately, pretty common.
It seems to creep in, and it'd be nice to avoid it in the refernces.
'''
locator_prefix = None
modified_locator = None
''' check for the prefixes '''
for prefix in local_prefixes_that_matter:
if locator.startswith("{}_".format(prefix)):
locator_prefix = prefix
modified_locator = locator.replace("{}_".format(prefix), "")
''' next we look for a potential existing parent/reference node by name '''
if modified_locator:
reference_node = anytree.search.find_by_attr(fact_tree_root, modified_locator)
else:
reference_node = anytree.search.find_by_attr(fact_tree_root, locator)
''' if there is not a parent/reference node, we make one '''
if not reference_node:
''' so all that follows is to try and mimic the structure of the base fact file with prefixes '''
if modified_locator:
if locator_prefix:
reference_node = anytree.Node(modified_locator,
parent=fact_tree_root,
prefix=locator_prefix,
suffix=modified_locator)
else:
reference_node = anytree.Node(modified_locator,
parent=fact_tree_root,
suffix=modified_locator)
else:
reference_node = anytree.Node(locator,
parent=fact_tree_root,
suffix=locator)
''' i'm going to try and associate the type of fact with the
reference node
'''
try:
''' maybe a prefix already exists'''
existing_prefix = reference_node.prefix
except:
''' it doesn't so lets try and find one '''
node_prefix=None
''' we want the node to have a fact
(because we are looking for fact prefix from the main .xml file)
'''
try:
node_fact = node.fact
except:
'probably not a fact node'
node_fact = ""
if node_fact != "":
try:
node_prefix = node.prefix
except:
node_prefix = None
if node_prefix:
reference_node.prefix = node_prefix
return reference_node
else:
''' this is a contextual item
we will put this item in to the "other tree root" tree and deal with it later
'''
xbrli_node = anytree.search.find_by_attr(other_tree_root, "{{{}}}{}".format(node.clark, node.suffix))
if not xbrli_node:
xbrli_node = anytree.Node("{{{}}}{}".format(node.clark, node.suffix),
parent=other_tree_root,
suffix=node.suffix)
return xbrli_node
def fact_centric_xbrl_processor(root_node_dict, ticker, sic, country_code, sort_trash_for_debugging=False):
fact_tree_root = anytree.Node(ticker)
other_tree_root = anytree.Node('xbrli')
trash_tree_root = anytree.Node('unsorted_trash')
parent_child_tuple_list = []
'''Here i'm going to attempt to order the files, to facilitate normal order:'''
extension_order_after_primary_file_list = [".xsd", "_lab.xml", "_def.xml", "_cal.xml", "_pre.xml"]
ordered_filename_list = []
for extention in extension_order_after_primary_file_list:
for filename in root_node_dict.keys():
if filename.endswith(extention):
ordered_filename_list.append(filename)
'''now add the primary file:'''
for filename in root_node_dict.keys():
if filename not in ordered_filename_list:
ordered_filename_list.insert(0, filename)
'''here, we're just looking to see if a top level fact reference exists
(could be made more efficient in the future, but limited)
'''
logging.info("Start initial sorting:")
start_time = time.time()
for filename in ordered_filename_list:
logging.info(filename)
''' grab the root node '''
root_node = root_node_dict.get(filename)
''' iterate through and look for suffixes, if one is missing, there's a major error '''
for node in anytree.PreOrderIter(root_node):
try:
suffix = node.suffix
except:
logging.error("there is a problem with this node... it has no 'suffix' attribute")
#logging.info(pp.pformat(vars(node)))
sys.exit()
''' we create a refernce node if it doesn't exist,
why: we're trying to prevent dublicates
now let's pair it with that node
'''
reference_node = return_refernce_node(node, fact_tree_root, other_tree_root, ticker)
parent_child_tuple_list.append((reference_node, node))
''' we iterate through, check for duplicates'''
for reference_node, child in parent_child_tuple_list:
''' now lets unite all these nodes together '''
unique = True
''' here we go through to check for duplicates '''
for existing_child in reference_node.children:
if vars(child) == vars(existing_child):
'''this prevents lots of redundant nodes'''
unique = False
if unique == False:
break
if unique == True:
''' if we have a unique parent child relationship, we map it
that is we attach the parent/reference node as the parent of our node
'''
child.parent = reference_node
else:
''' here, our node is a duplicate, and so we throw it out '''
child.parent = trash_tree_root
''' at this point we should have a basic tree structure with the base as the ticker'''
print_root_node_lengths(fact_tree_root, other_tree_root, trash_tree_root)
logging.info("Finished in {}sec".format(round(time.time() - start_time)))
''' now let's need to pair more of the other refernces with our facts'''
logging.info("Start deep sorting:")
start_time = time.time()
''' make a quick sort dict '''
fact_tree_children_dict = {node.suffix: node for node in fact_tree_root.children}
''' got to the other other_tree_root and try to pair the stuff left over '''
for node in anytree.PreOrderIter(other_tree_root):
replacement_parent = return_new_parent(node, fact_tree_children_dict)
if replacement_parent:
node.parent = replacement_parent
print_root_node_lengths(fact_tree_root, other_tree_root, trash_tree_root)
logging.info("Finished in {}sec".format(round(time.time() - start_time)))
#fact_tree_children_dict = {node.suffix: node for node in fact_tree_root.children}
logging.info("Start deep sorting second pass:")
start_time = time.time()
for node in anytree.PreOrderIter(other_tree_root):
replacement_parent = return_new_parent_round_two(node, fact_tree_children_dict)
if replacement_parent:
node.parent = replacement_parent
print_root_node_lengths(fact_tree_root, other_tree_root, trash_tree_root)
logging.info("Finished in {}sec".format(round(time.time() - start_time)))
logging.info("Start contextRef sorting:")
start_time = time.time()
for node in anytree.PreOrderIter(fact_tree_root):
replacement_parent = return_new_parent_for_Axis_contextRefs(node)
if replacement_parent:
node.parent = replacement_parent
print_root_node_lengths(fact_tree_root, other_tree_root, trash_tree_root)
logging.info("Finished in {}sec".format(round(time.time() - start_time)))
logging.info("Create context refs dict:")
start_time = time.time()
convert_context_refs_into_id_keyed_dict(fact_tree_root, other_tree_root, trash_tree_root, sic, country_code)
logging.info("Finished in {}sec".format(round(time.time() - start_time)))
if sort_trash_for_debugging:
logging.info("Sort trash file:")
start_time = time.time()
trash_tree_root = keep_trash_sorted(trash_tree_root)
logging.info("Finished in {}sec".format(round(time.time() - start_time)))
logging.info("Saving text files")
start_time = time.time()
# the following are for testing:
if testing:
fact_tree_root_filename = ticker + "_facts"
root_node_to_rendertree_text_file(fact_tree_root, fact_tree_root_filename)
other_tree_root_filename = ticker + "_xbrli"
root_node_to_rendertree_text_file(other_tree_root, other_tree_root_filename)
trash_filename = ticker + "_trash"
root_node_to_rendertree_text_file(trash_tree_root, trash_filename)
logging.info("Finished in {}sec".format(round(time.time() - start_time)))
return fact_tree_root
def convert_context_refs_into_id_keyed_dict(fact_tree_root, other_tree_root, trash_tree_root, sic, country_code):
'converts contexts refs into a dict, and adds country code and sic'
context_node = None
period_node_list = []
for child in list(other_tree_root.children):
if child.suffix == "context":
context_node = child
elif child.suffix in ["startDate", "endDate", "instant", "forever"]:
period_node_list.append(child)
context_dict = {}
for period_node in period_node_list:
for node in anytree.PreOrderIter(period_node):
try:
existing_entry = context_dict.get(node.parent_id)
except:
continue
if node.parent.suffix == "measure":
continue
if existing_entry is None:
context_dict[node.parent_id] = node.fact
else: # entry already exists
if node.suffix == "startDate":
new_entry = node.fact + ":" + existing_entry
elif node.suffix == "endDate":
new_entry = existing_entry + ":" + node.fact
elif node.suffix == "instant":
logging.error("This should not happen. Examine this code error")
sys.exit()
context_dict[node.parent_id] = new_entry
node.parent = trash_tree_root
for node in anytree.PreOrderIter(context_node):
node.parent = trash_tree_root
context_dict_node = anytree.Node("context_dict", parent=fact_tree_root, attrib = context_dict)
context_sic_node = anytree.Node("sic", parent=fact_tree_root, attrib = sic)
context_country_code_node = anytree.Node("country_code", parent=fact_tree_root, attrib = country_code)
def keep_trash_sorted(trash_tree_root):
sorted_trash_tree_root = anytree.Node('trash')
for node in anytree.PreOrderIter(trash_tree_root):
success = False
if node.parent:
for sorted_node in anytree.PreOrderIter(sorted_trash_tree_root):
if sorted_node.parent:
if vars(node) == vars(sorted_node):
success = True
node.parent = sorted_node
break
if not success:
node.parent = sorted_trash_tree_root
logging.info("old trash tree")
logging.info(anytree.RenderTree(trash_tree_root))
return sorted_trash_tree_root
def print_root_node_lengths(fact_tree_root, other_tree_root, trash_tree_root):
fact_tree_root_len = len(list(anytree.PreOrderIter(fact_tree_root)))
other_tree_root_len = len(list(anytree.PreOrderIter(other_tree_root)))
trash_tree_root_len = len(list(anytree.PreOrderIter(trash_tree_root)))
logging.info("facts:\t{}\tother:\t{}\ttrash:\t{}".format(fact_tree_root_len, other_tree_root_len, trash_tree_root_len))
def return_new_parent(node, fact_tree_children_dict):
# step 1: recursion
try:
parent_id = node.parent_id
except:
parent_id = None
if parent_id:
parent = fact_tree_children_dict.get(parent_id)
if parent:
return parent
# step 2: start check dimension
try:
dimension = node.attrib.get("dimension")
except:
dimension = None
if dimension:
dimension_parent_id = dimension.split(":")[-1]
parent = fact_tree_children_dict.get(dimension_parent_id)
if parent:
return parent
dimension_underscore = dimension.replace(":", "_")
parent = fact_tree_children_dict.get(dimension_underscore)
if parent:
return parent
# step 3 check label
try:
label = node.attrib.get("{http://www.w3.org/1999/xlink}label")
except:
label = None
if label:
for suffix, tree_node in fact_tree_children_dict.items():
if suffix in label:
try:
parent_label = tree_node.attrib.get("{http://www.w3.org/1999/xlink}label")
except:
parent_label = None
if parent_label:
if label == parent_label:
return tree_node
parent = recursive_label_node_getter(tree_node, label)
if parent:
return parent
# step 5: from and to attributes
try:
from_attrib = node.attrib.get("{http://www.w3.org/1999/xlink}from")
to_attrib = node.attrib.get("{http://www.w3.org/1999/xlink}to")
except:
from_attrib = None
to_attrib = None
if from_attrib and to_attrib:
''' i decided not to make copies, but instead, just leave them in the from attributes'''
# to attribute (make copy)
'''
for suffix, tree_node in fact_tree_children_dict.items():
if suffix in to_attrib:
try:
parent_label = tree_node.attrib.get("{http://www.w3.org/1999/xlink}label")
except:
parent_label = None
if parent_label:
if to_attrib == parent_label:
to_node = copy.copy(node)
to_node.parent = tree_node
break
to_parent = recursive_label_node_getter(tree_node, to_attrib)
if to_parent:
to_node = copy.copy(node)
to_node.parent = tree_node
break
'''
# from attribute (return node)
for suffix, tree_node in fact_tree_children_dict.items():
if suffix in from_attrib:
try:
parent_label = tree_node.attrib.get("{http://www.w3.org/1999/xlink}label")
except:
parent_label = None
if parent_label:
if from_attrib == parent_label:
return tree_node
parent = recursive_label_node_getter(tree_node, from_attrib)
if parent:
return parent
# step 4 roles
try:
role = node.attrib.get("{http://www.w3.org/1999/xlink}role")
except:
role = None
if role:
parent = fact_tree_children_dict.get(role.split("/")[-1])
if parent:
return parent
def return_new_parent_round_two(node, fact_tree_children_dict):
look_up_list = ["name", "{http://www.w3.org/1999/xlink}from", "id"]
for item in look_up_list:
try:
attribute = node.attrib.get(item)
except:
attribute = None
if attribute:
for suffix, tree_node in fact_tree_children_dict.items():
if suffix == attribute:
return tree_node
elif suffix in attribute:
parent = recursive_node_id_getter(tree_node, attribute)
if parent:
return parent
parent = recursive_label_node_getter(tree_node, attribute)
if parent:
return parent
def return_new_parent_for_Axis_contextRefs(node):
try:
contextRef = node.attrib.get('contextRef')
except:
return
if contextRef is None:
return
split_contextRef = contextRef.split("_")
if len(split_contextRef) == 1:
return
if "Axis" in contextRef or "Member" in contextRef:
for index, sub_string in enumerate(split_contextRef):
if sub_string.endswith("Axis") or sub_string.endswith("Member"):
parent = node.parent
for child in parent.children:
if child.suffix == sub_string:
return child
# we should have establish there is no pre-existing subparent if we are here
subparent = anytree.Node(sub_string,
parent = parent,
# node_order = node_order,
suffix = sub_string,
axis = True
)
return subparent
def recursive_node_id_getter(node, original_id):
try:
potential_id_match = node.attrib.get("id")
except:
potential_id_match = None
if potential_id_match:
if original_id == potential_id_match:
return node
for child in node.children:
parent = recursive_node_id_getter(child, original_id)
if parent:
return parent
def recursive_label_node_getter(node, original_label):
try:
potential_match = node.attrib.get("{http://www.w3.org/1999/xlink}label")
except:
potential_match = None
if potential_match:
if original_label == potential_match:
return node
if original_label == potential_match.replace("loc_", "lab_"):
return node
for child in node.children:
parent = recursive_label_node_getter(child, original_label)
if parent:
return parent
def other_tree_node_replacement(attribute_list, fact_tree_root_children):
replacement_node = None
for child in fact_tree_root_children:
for attribute in attribute_list:
if attribute == child.suffix:
replacement_node = child
if replacement_node:
return replacement_node
if not replacement_node:
for attribute in attribute_list:
new_attr = attribute.replace(":", "_")
if new_attr == child.suffix:
replacement_node = child
if replacement_node:
return replacement_node
if not replacement_node:
for attribute in attribute_list:
try:
new_attr = attribute.split(":")[-1]
except:
continue
if new_attr == child.suffix:
replacement_node = child
if replacement_node:
return replacement_node
if not replacement_node:
for attribute in attribute_list:
try:
new_attr = attribute.split("_")[-1]
except:
continue
if new_attr == child.suffix:
replacement_node = child
if replacement_node:
return replacement_node
return replacement_node
def xbrl_to_json_processor(xbrl_filename, ticker, root_node=None, write_file=False, write_txt_file=False):
if not (xbrl_filename or root_node):
logging.error("You must include a either a filename or root_node")
sys.exit()
if not root_node:
root_node = process_xbrl_file_to_tree(xbrl_filename, ticker)
#print(anytree.RenderTree(root_node))
flat_file_dict = convert_tree_to_dict(root_node)
if write_file:
should_be_json_filename = xbrl_filename
if not should_be_json_filename.endswith(".json"):
should_be_json_filename = should_be_json_filename + ".json"
write_dict_as_json(flat_file_dict, should_be_json_filename)
if write_txt_file:
root_node_to_rendertree_text_file(root_node, should_be_json_filename)
return root_node
def custom_render_tree(root_node):
output_str = ""
for pre, _, node in anytree.RenderTree(root_node):
fact = ""
formatted_fact = ""
attrib = ""
formatted_attrib = ""
try:
fact = node.fact
attrib = node.attrib
except:
pass
if fact:
formatted_fact = "\n{}{}".format(pre, fact)
if attrib:
formatted_attrib = "\n{}{}".format(pre, attrib)
formatted_str = "{}{}{}{}\n".format(pre, node.name, formatted_fact, formatted_attrib)
output_str = output_str + "\n" + formatted_str
return output_str
def root_node_to_rendertree_text_file(root_node, xbrl_filename, custom=False):
with open('{}_render.txt'.format(xbrl_filename), 'w') as outfile:
if custom:
output_str = custom_render_tree(root_node)
else:
output_str = str(anytree.RenderTree(root_node))
outfile.write(output_str)
def recursive_iter(xbrl_element, reversed_ns, ticker, parent=None, node_order=0):
elements = []
clark, prefix, suffix = xbrl_clark_prefix_and_suffix(xbrl_element, reversed_ns)
fact = xbrl_element.text
if isinstance(fact, str):
fact = fact.strip()
if fact is None:
fact = ""
attrib = xbrl_element.attrib
parent_id = None
if fact:
try:
parent_id = parent.attrib.get("id")
if parent_id is None:
if parent.suffix == "period":
grandparent = parent.parent
# use parent_id for simpler code
parent_id = grandparent.attrib.get("id")
except:
pass
if parent_id and fact:
node_element = anytree.Node(suffix,
parent = parent,
parent_id = parent_id,
#node_order= node_order,
clark = clark,
prefix = prefix,
suffix = suffix,
fact = fact,
attrib = attrib,
)
else:
node_element = anytree.Node(suffix,
parent = parent,
#node_order= node_order,
clark = clark,
prefix = prefix,
suffix = suffix,
fact = fact,
attrib = attrib,
)
elements.append(node_element)
subtag_count_dict = {}
for element in xbrl_element:
count = subtag_count_dict.get(element.tag)
if count is None:
subtag_count_dict[element.tag] = 1
count = 0
else:
subtag_count_dict[element.tag] = count + 1
sub_elements = recursive_iter(element,
reversed_ns,
ticker,
parent=node_element,
node_order=count,
)
for element_sub2 in sub_elements:
elements.append(element_sub2)
return elements
def process_xbrl_file_to_tree(xbrl_filename, ticker):
logging.info(xbrl_filename)
tree, ns, root = extract_xbrl_tree_namespace_and_root(xbrl_filename)
#print(root)
reversed_ns = {value: key for key, value in ns.items()}
elements = recursive_iter(root, reversed_ns, ticker)
#print(len(elements))
xbrl_tree_root = elements[0]
return xbrl_tree_root
def convert_tree_to_dict(root_node):
exporter = anytree.exporter.JsonExporter(indent=2, sort_keys=True)
json_dict = json.loads(exporter.export(root_node))
return json_dict
def convert_dict_to_node_tree(dict_to_convert):
importer = anytree.importer.JsonImporter()
json_str = json.dumps(dict_to_convert)
root_node = importer.import_(json_str)
return root_node
#### utils ####
def extract_xbrl_tree_namespace_and_root(xbrl_filename):
ns = {}
try:
for event, (name, value) in ET.iterparse(xbrl_filename, ['start-ns']):
if name:
ns[name] = value
except Exception as e:
logging.error(e)
return[None, None, None]
tree = ET.parse(xbrl_filename)
root = tree.getroot()
#logging.info([tree, ns, root])
return [tree, ns, root]
def xbrl_clark_prefix_and_suffix(xbrl_element, reversed_ns):
clark, suffix = xbrl_element.tag[1:].split("}")
prefix = reversed_ns.get(clark)
return [clark, prefix, suffix]
def xbrl_ns_clark(xbrl_element):
'''return clark notation prefix'''
return xbrl_element.tag.split("}")[0][1:]
def xbrl_ns_prefix(xbrl_element, ns):
return [key for key, value in ns.items() if xbrl_ns_clark(xbrl_element) == value][0]
def xbrl_ns_suffix(xbrl_element):
return xbrl_element.tag.split("}")[1]
def return_xlink_locator(element_with_href):
href = element_with_href.attrib.get("{http://www.w3.org/1999/xlink}href")
href_list = href.split("#")
if len(href_list) > 1:
href = href_list[-1]
return href
def import_json(json_filename):
logging.info("importing: {}".format(json_filename))
with open(json_filename, 'r') as inputfile:
data_dict = json.load(inputfile)
return data_dict
def write_dict_as_json(dict_to_write, json_filename):
logging.info("writing: {}".format(json_filename))
with open(json_filename, 'w') as outfile:
json.dump(dict_to_write, outfile, indent=2)
def form_type_conversion(form_type, country_code, us_codes=US_COUNTRY_CODES, ca_codes=CANADA_COUNTRY_CODES):
logging.info(country_code)
if form_type == "10-Q":
if country_code not in us_codes:
return None
elif form_type in ANNUAL_FORM_TYPES:
if country_code in us_codes:
return "10-K"
elif country_code in ca_codes:
return "40-F"
else:
return "20-F"
else:
return None
def folder_path_form_type_conversion(ticker, form_type):
make_folder = False
folder_path = return_xbrl_data_formatted_folder_path(ticker, form_type)
if not does_file_exist_in_dir(folder_path):
if form_type in ANNUAL_FORM_TYPES:
us_path = return_xbrl_data_formatted_folder_path(ticker, "10-K")
ca_path = return_xbrl_data_formatted_folder_path(ticker, "40-F")
adr_path = return_xbrl_data_formatted_folder_path(ticker, "20-F")
if does_file_exist_in_dir(us_path):
form_type = '10-K'
folder_path = us_path
#logging.info("US company path generated")
elif does_file_exist_in_dir(ca_path):
form_type = '40-F'
folder_path = ca_path
#logging.info("Canadian company path generated")
elif does_file_exist_in_dir(adr_path):
form_type = '20-F'
folder_path = adr_path
#logging.info("International company path generated")
else:
make_folder = True
else:
make_folder = True
return folder_path, form_type, make_folder
def does_file_exist_in_dir(path):
'is there a file in this path'
try:
return any(os.path.isfile(os.path.join(path, i)) for i in os.listdir(path))
except:
return None
#### xbrl from sec ####
def return_url_request_data(url, values_dict={}, secure=False, sleep=1):
time.sleep(sleep)
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"}
http__prefix = "http://"
https_prefix = "https://"
if secure:
url_prefix = https_prefix
else:
url_prefix = http__prefix
if "http://" in url or "https://" in url:
url_prefix = ""
url = url_prefix + url
encoded_url_extra_values = urllib.parse.urlencode(values_dict)
data = encoded_url_extra_values.encode('utf-8')
#logging.warning("\n{}\n{}\n{}".format(url, data, headers))
if data:
request = urllib.request.Request(url, data, headers=headers)
else:
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request) # get request
response_data = response.read().decode('utf-8')
return response_data
def sec_xbrl_single_stock(cik, form_type):
base_url = "https://www.sec.gov/cgi-bin/browse-edgar"
values = {"action": "getcompany",
"CIK": cik,
"type": form_type,
}
response_data = return_url_request_data(base_url, values, secure=True)
return response_data
def parse_sec_results_page(sec_response_data, cik, form_type, date="most recent", previous_error=False):
soup = bs4.BeautifulSoup(sec_response_data, 'html.parser')
if form_type == "10-K":
ten_k_soup = soup
#logging.info(soup.prettify())
identInfo = soup.find_all("p", class_="identInfo")[0]
linked_data = identInfo.find_all("a")
previous_item = None
sic = None
country_code = None
for item in linked_data:
# e.g.
# /cgi-bin/browse-edgar?action=getcompany&SIC=7370&owner=exclude&count=40
# /cgi-bin/browse-edgar?action=getcompany&State=F4&owner=exclude&count=40
href = item.get("href")
if "&SIC=" in href:
sic = item.text
elif "&State=" in href:
country_code = item.text
new_form_type = form_type_conversion(form_type, country_code)
if new_form_type != form_type:
logging.info("{} vs {}".format(new_form_type, form_type))
form_type = new_form_type
logging.info("-"*2000)
logging.info(form_type)
new_response_data = sec_xbrl_single_stock(cik, form_type)
soup = bs4.BeautifulSoup(new_response_data, 'html.parser')
if not sic and country_code:
raise(Exception)
table_list = soup.find_all("table", {"summary": "Results"})
#logging.info(len(table_list))
if not len(table_list) == 1:
logging.error("something's up here")
table = table_list[0]
logging.info(table)
document_button_list = table.find_all("a", {"id":"documentsbutton"})
logging.info(document_button_list)
if not document_button_list:
if form_type not in ["10-K", "10-Q"]:
logging.warning("something else is up here")
soup = ten_k_soup
table_list = soup.find_all("table", {"summary": "Results"})
#logging.info(len(table_list))
if not len(table_list) == 1:
logging.error("something's up here")
table = table_list[0]
logging.info(table)
document_button_list = table.find_all("a", {"id":"documentsbutton"})
logging.info(document_button_list)
if document_button_list:
form_type = "10-K"
if not date:
date = "most recent"
if date == "most recent":
relevant_a_tag = table.find("a", {"id":"documentsbutton"})
if previous_error:
relevant_interactive_tag = table.find("a", {"id":"interactiveDataBtn"})
tag_parent = relevant_interactive_tag.parent
relevant_a_tag = tag_parent.find("a", {"id":"documentsbutton"})
else:
year = date[:4]
month = date[4:6]
day = date[6:]
logging.info("{}-{}-{}".format(year, month, day))
relevant_td = table.find("td", string="{}-{}-{}".format(year, month, day))
relevant_td_parent = None
if not relevant_td:
relevant_interactive_tags = table.find_all("a", {"id":"interactiveDataBtn"})
tag_parents = [tag.parent.parent for tag in relevant_interactive_tags]
if tag_parents:
# i'm going to get clever here, and count backwards through the months
# starting with the listed month, to find the nearest previous entry
# if the month is correct, it should work the first time
# if you encounter an error here, that's what's happening
for i in reversed(range(int(month))):
month_str = str(i+1).zfill(2)
date_str = "{}-{}".format(year, month_str)
for parent in tag_parents:
if date_str in parent.text:
for child in parent.children:
if child.string:
if date_str in child.string:
relevant_td = child
if relevant_td:
break
if relevant_td:
break
if relevant_td:
break
relevant_td_parent = relevant_td.parent
relevant_a_tag = relevant_td_parent.find("a", {"id":"documentsbutton"})
logging.info(relevant_a_tag)
relevant_a_href = relevant_a_tag['href']
sec_url = "https://www.sec.gov"
relevant_xbrl_url = sec_url + relevant_a_href
return relevant_xbrl_url, sic, country_code, form_type
def write_xbrl_file(file_name, sec_response_data):
with open(file_name, 'w') as outfile:
outfile.write(sec_response_data)
def return_xbrl_data_formatted_folder_path(ticker, form_type):
return os.path.join("XBRL_Data", ticker, form_type)
def return_most_recent_xbrl_to_json_converted_filename(folder_path, ticker):
filename = find_most_recent_filename_from_date(folder_path, ticker)
return os.path.join(folder_path, filename)
def return_xbrl_to_json_converted_filename_with_date(folder_path, ticker, date):
ticker_date = "{}-{}".format(ticker, date)
if folder_path.endswith(ticker_date):
filename = folder_path + ".json"
else:
filename = ticker_date + ".json"
filename = os.path.join(folder_path, filename)
return filename
def find_most_recent_filename_from_date(folder_path, ticker):
pattern = re.compile(ticker.lower() + r"-[0-9]{8}")
most_recent_folder_date = 0
most_recent_filename = None
for filename in os.listdir(folder_path):
#logging.info(filename)
if filename.endswith(".json"):
if ticker.lower() in filename:
if pattern.search(filename):
ticker_hyphen_date = filename.replace(".json", "")
folder_date = ticker_hyphen_date.split("-")[1]
if int(folder_date) > most_recent_folder_date:
most_recent_folder_date = int(folder_date)
most_recent_filename = filename
return most_recent_filename
def get_xbrl_files_and_return_folder_name(ticker, xbrl_data_page_response_data, form_type, url_in_case_of_error=None):
soup = bs4.BeautifulSoup(xbrl_data_page_response_data, 'html.parser')
table_list = soup.find_all("table", {"summary": "Data Files"})
if not len(table_list) == 1:
logging.error("something's up here")
#logging.info(pp.pformat(table_list))
if not table_list:
logging.error("Likely refering to a sec page without XBRL, manually check the url")
logging.error(url_in_case_of_error)
return "Error: No Table"
table = table_list[0]
a_tag_list = table.find_all("a")
sec_url = "https://www.sec.gov"
folder_name = None
data_date = None
for a in a_tag_list:
href = a["href"]
file_name = a.text
if not folder_name:
if "_" not in file_name:
folder_name = file_name.split(".")[0]
else:
# grmn-20181229_def.xml
folder_name = file_name.split("_")[0]
data_date = folder_name.split("-")[1]
# logging.info(ticker, form_type, folder_name, file_name)
full_file_name = os.path.join("XBRL_Data", ticker, form_type, folder_name, file_name)
full_folders_name = os.path.join("XBRL_Data", ticker, form_type, folder_name)
if not os.path.exists(full_folders_name):
os.makedirs(full_folders_name)
else:
if os.path.exists(full_file_name):
logging.info("Data for {} already exists".format(ticker))
return full_folders_name, data_date
full_url = sec_url + href
response_data = return_url_request_data(full_url)
write_xbrl_file(full_file_name, response_data)
return full_folders_name, data_date
def full_sec_xbrl_folder_download(ticker, cik, form_type, date="most recent", previous_error=False):
response_data = sec_xbrl_single_stock(cik, form_type)
logging.info("sec response_data gathered")
relevant_xbrl_url, sic, country_code, form_type = parse_sec_results_page(response_data, cik, form_type, date=date, previous_error=previous_error)
logging.info("precise url found")
xbrl_data_page_response_data = return_url_request_data(relevant_xbrl_url)
logging.info("xbrl data downloaded")
folder_name, data_date = get_xbrl_files_and_return_folder_name(ticker, xbrl_data_page_response_data, form_type, url_in_case_of_error=relevant_xbrl_url)
if folder_name == "Error: No Table":
if not previous_error:
return full_sec_xbrl_folder_download(ticker, cik, form_type, date=date, previous_error=True)
else:
logging.error("error loop here")
return
logging.info("xbrl files created")
return folder_name, data_date, sic, country_code, form_type
#### main ####
def main_download_and_convert(ticker, cik, form_type, year=None, month=None, day=None, force_download=False, delete_files_after_import=False):
given_date = None
if year and (month and day):
try:
year = str(year).zfill(4)
month = str(month).zfill(2)
day = str(day).zfill(2)
given_date = "{}{}{}".format(year, month, day)
except:
logging.error("invalid year/month/date input")
# start by converting to path name
folder_path = return_xbrl_data_formatted_folder_path(ticker, form_type)
#logging.info(folder_path)
if not does_file_exist_in_dir(folder_path):
folder_path, form_type, make_folder = folder_path_form_type_conversion(ticker, form_type)
if make_folder:
os.makedirs(folder_path, exist_ok=True)
#logging.info(folder_path)
# if we are going to force a download attempt, the following can all be skipped
if not force_download:
# if we have a specific date we're looking for, this will do that
if given_date:
try:
folder_name = "{}-{}".format(ticker.lower(), given_date)
full_path = os.path.join(folder_path, folder_name)
if os.path.exists(full_path):
xbrl_tree_root = main_xbrl_to_json_converter(ticker, cik, given_date, full_path, delete_files_after_import=delete_files_after_import)
if not os.path.exists("{}_facts_dict.json".format(full_path)):
convert_root_node_facts_to_fact_dict(xbrl_tree_root, ticker, full_path)
return xbrl_tree_root
except Exception as e:
logging.warning(e)
logging.info("probably no date given")
pass