-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuantamental_functions.py
1429 lines (1232 loc) · 70.4 KB
/
Quantamental_functions.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 re
import gc
import requests
import time
import pickle
import warnings
import concurrent.futures
import pandas as pd
import yfinance as yf
import numpy as np
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
from selenium import webdriver # type: ignore
from selenium.webdriver.chrome.service import Service # type: ignore
from selenium.webdriver.common.by import By # type: ignore
from selenium.webdriver.support.ui import WebDriverWait # type: ignore
from selenium.webdriver.support import expected_conditions as EC # type: ignore
from selenium.common.exceptions import TimeoutException, NoSuchElementException # type: ignore
from selenium.webdriver.chrome.options import Options # type: ignore
from selenium_stealth import stealth # type: ignore
warnings.filterwarnings('ignore', category=FutureWarning)
headers = {"User-Agent": "<[email protected]>", "Accept": "application/json"} #modify using your email
keywords_method1 = pd.read_excel('Data/DataRaw/Duplicate_keywords.xlsx', header=0, sheet_name='Method1')
keywords_method4 = pd.read_excel('Data/DataRaw/Duplicate_keywords.xlsx', header=0, sheet_name='Method4')
def get_data(ticker, start_date, end_date):
"""
Fetch historical stock data for a given ticker from Yahoo Finance
"""
try:
data = yf.download(ticker, start=start_date, end=end_date)['Close']
data = data.dropna()
return data
except Exception:
return None
def get_accession_numbers(cik, form_type, dateb):
base_url = "https://www.sec.gov"
search_url = f"{base_url}/cgi-bin/browse-edgar?action=getcompany&CIK={cik}&type={form_type}&dateb={dateb}&owner=exclude&count=100&search_text="
chromedriver_path = "/usr/local/bin/chromedriver"
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.142 Safari/537.36')
service = Service(chromedriver_path)
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win64",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
)
accession_numbers = []
try:
driver.get(search_url)
wait = WebDriverWait(driver, 30)
try:
filings_table = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'tableFile2')))
except TimeoutException:
print("Timeout while waiting for the filings table to load.")
#driver.save_screenshot('timeout_error_screenshot.png')
raise
soup = BeautifulSoup(driver.page_source, 'html.parser')
filings_table = soup.find('table', {'class': 'tableFile2'})
if not filings_table:
print(f"No filings found for CIK {cik} with form type {form_type} up to date {dateb}")
raise Exception(f"No filings found for CIK {cik} with form type {form_type} up to date {dateb}")
rows = filings_table.find_all('tr')[1:]
for row in rows:
description_cell = row.find('td', class_='small')
if description_cell:
acc_no_text = description_cell.get_text()
acc_no_match = re.search(r'Acc-no:\s*(\d+-\d+-\d+)', acc_no_text)
if acc_no_match:
acc_no = acc_no_match.group(1).replace('-', '')
accession_numbers.append(acc_no)
except TimeoutException as e:
print(f"Timeout occurred: {e}")
except NoSuchElementException as e:
print(f"Element not found: {e}")
finally:
driver.quit()
return accession_numbers
def generate_dates(start, end):
start_date = datetime.strptime(start, "%m%d")
end_date = datetime.strptime(end, "%m%d")
dates = []
current_date = start_date
while current_date <= end_date:
dates.append(current_date.strftime("%m%d"))
current_date += timedelta(days=1)
return dates
def generate_edgar_urls(cik, accession_numbers, ticker, dateb):
base_url = "https://www.sec.gov/Archives/edgar/data"
cik = cik.lstrip('0')
quarters_groups = [
["0929","0930", "1001", "1029", "1030", "1031", "1101", "1102", "1130"],
["0630", "0701", "0702", "0730", "0731", "0801", "0802", "0831"],
["0228","0331", "0401", "0430", "0501", "0502"]
]
dateb = datetime.strptime(dateb, "%Y%m%d")
urls = []
for i, acc_no in enumerate(accession_numbers):
year_suffix = int(acc_no[10:12])
base_year = 2000 + year_suffix if year_suffix < 50 else 1900 + year_suffix
group_index = i % len(quarters_groups)
quarters = quarters_groups[group_index]
for quarter in quarters:
report_date_str = f"{base_year}{quarter}"
try:
report_date = datetime.strptime(report_date_str, "%Y%m%d")
except ValueError:
continue
if report_date < dateb:
base_url_with_date = f"{base_url}/{cik}/{acc_no}/{ticker.lower()}-{report_date_str}.htm"
urls.append(base_url_with_date)
modified_url_x10q = base_url_with_date.replace(".htm", "x10q.htm")
urls.append(modified_url_x10q)
parts = modified_url_x10q.split('-')
if len(parts) > 1:
report_date_part = parts[-1].replace('x10q.htm', '')
if report_date_part[4] == '0':
report_date_part = report_date_part[:4] + report_date_part[5:]
further_modified_url = '-'.join(parts[:-1]) + '-' + report_date_part + "x10q.htm"
urls.append(further_modified_url)
additional_url = f"{base_url}/{cik}/{acc_no}/{ticker.lower()}-10q_{report_date_str}.htm"
urls.append(additional_url)
extra_url = f"{base_url}/{cik}/{acc_no}/{ticker.lower()}{report_date_str}_10q.htm"
urls.append(extra_url)
if (i + 1) % len(quarters_groups) == 0:
base_year -= 1
return urls
#In process_urls: break_limit = 254 if month in ['09', '10', '11'] else 325 if month in ['02', '03', '04', '05'] else 320
def generate_edgar_urls_extended(cik, accession_numbers, ticker, dateb):
base_url = "https://www.sec.gov/Archives/edgar/data"
cik = cik.lstrip('0')
quarters_groups = [
generate_dates("0929", "1130"),
generate_dates("0629", "0831"),
generate_dates("0227", "0502")
]
dateb = datetime.strptime(dateb, "%Y%m%d")
urls = []
for i, acc_no in enumerate(accession_numbers):
year_suffix = int(acc_no[10:12])
base_year = 2000 + year_suffix if year_suffix < 50 else 1900 + year_suffix
group_index = i % len(quarters_groups)
quarters = quarters_groups[group_index]
for quarter in quarters:
report_date_str = f"{base_year}{quarter}"
try:
report_date = datetime.strptime(report_date_str, "%Y%m%d")
except ValueError:
continue
if report_date < dateb:
base_url_with_date = f"{base_url}/{cik}/{acc_no}/{ticker.lower()}-{report_date_str}.htm"
urls.append(base_url_with_date)
modified_url_x10q = base_url_with_date.replace(".htm", "x10q.htm")
urls.append(modified_url_x10q)
parts = modified_url_x10q.split('-')
if len(parts) > 1:
report_date_part = parts[-1].replace('x10q.htm', '')
if report_date_part[4] == '0':
report_date_part = report_date_part[:4] + report_date_part[5:]
further_modified_url = '-'.join(parts[:-1]) + '-' + report_date_part + "x10q.htm"
urls.append(further_modified_url)
additional_url = f"{base_url}/{cik}/{acc_no}/{ticker.lower()}-10q_{report_date_str}.htm"
urls.append(additional_url)
extra_url = f"{base_url}/{cik}/{acc_no}/{ticker.lower()}{report_date_str}_10q.htm"
urls.append(extra_url)
if (i + 1) % len(quarters_groups) == 0:
base_year -= 1
return urls
def extract_accno(url):
parts = url.split('/')
if len(parts) > 5:
return parts[7]
return None
def fetch_10q_document(url):
chromedriver_path = "/usr/local/bin/chromedriver"
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.142 Safari/537.36')
service = Service(chromedriver_path)
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win64",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
)
document_content = None
try:
driver.get(url)
wait = WebDriverWait(driver, 30)
wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
soup = BeautifulSoup(driver.page_source, 'html.parser')
document_content = soup.prettify()
except TimeoutException as e:
print(f"Timeout occurred: {e}")
except NoSuchElementException as e:
print(f"Element not found: {e}")
finally:
driver.quit()
return document_content
def extract_date(url):
match = re.search(
r'-(\d{4})(\d{2})(\d{2})x10q\.htm|-(\d{4})(\d{2})(\d{2})\.htm|-(\d{4})(\d)(\d{2})x10q\.htm|-(\d{4})_(\d{2})(\d{2})x10q\.htm|-10q_(\d{4})(\d{2})(\d{2})\.htm|(\d{4})(\d{2})(\d{2})_10q\.htm', url)
if match:
if match.group(1):
year, month, day = match.group(1), match.group(2), match.group(3)
elif match.group(4):
year, month, day = match.group(4), match.group(5), match.group(6)
elif match.group(7):
year, month, day = match.group(7), match.group(8), match.group(9)
elif match.group(10):
year, month, day = match.group(10), match.group(11), match.group(12)
elif match.group(13):
year, month, day = match.group(13), match.group(14), match.group(15)
elif match.group(16):
year, month, day = match.group(16), match.group(17), match.group(18)
date_str = f"{year}{month}{day}"
date_obj = datetime.strptime(date_str, "%Y%m%d")
formatted_date = date_obj.strftime("%d-%m-%Y")
return formatted_date
return None
def clean_description(desc):
desc = re.sub(r'\(.*?\)', '', desc)
desc = desc.lower()
desc = re.sub(r'[^a-z\s]', '', desc)
desc = re.sub(r'\s+', ' ', desc).strip()
return desc
def rename_duplicates(df):
duplicates = dict(zip(keywords_method4.iloc[:, 0], keywords_method4.iloc[:, 1]))
df['Description'] = df['Description'].replace(duplicates)
return df
def filter_description(df):
terms_to_keep = [
"total assets", "tangible assets", "total current assets", "long term debt", "total current liabilities", "accounts payable", "accrued expenses and other",
"cash and cash equivalents", "marketable securities", "total shareholders equity", "total liabilities and equity",
"retained earnings", "goodwill", "accounts receivable", "inventories", "operating leases",
"cash flow from operations", "cash flow from investing", "cash flow from financing", "change in cash", "capex", "depreciation and amortization",
"total revenues", "basic earnings per share", "diluted earnings per share", "net income", "cost of sales", "total operating expenses", "operating income",
"total non operating expenses", "income before income taxes"
]
df = df[df['Description'].isin(terms_to_keep)]
return df
def clean_df(df, url):
year_found = False
year_col = None
target_column = None
date_str = extract_date(url)
extracted_year = str(int(date_str.split('-')[2]))
df.dropna(axis=0, how='all', inplace=True)
df.dropna(axis=1, how='all', inplace=True)
df.columns = ['Description'] + [f'Column_{i}' for i in range(1, len(df.columns))]
df['Description'] = df['Description'].astype(str)
df = df[~df['Description'].str.lower().str.startswith("common stock") & ~df['Description'].str.lower().str.startswith("treasury stock") & ~df['Description'].str.lower().str.startswith("class a common stock")
& ~df['Description'].str.lower().str.startswith("class b common stock") & ~df['Description'].str.lower().str.startswith("shares:") &
~df['Description'].str.contains("Preferred stock|additional paid-in capital|preferred stock", case=False)]
for col in df.columns[1:]:
column_values = df[col].astype(str).str.strip()
if column_values.str.contains(extracted_year).any():
year_col = col
year_found = True
break
df = df[df['Description'].notna()]
if year_found:
for col in df.columns[df.columns.get_loc(year_col):]:
column_values = df[col].astype(str).str.strip()
if column_values.str.contains(r'\$').any():
next_col_idx = df.columns.get_loc(col) + 1
if next_col_idx < len(df.columns):
target_column = df.columns[next_col_idx]
break
if target_column is None:
for col in df.columns[1:]:
column_values = df[col].astype(str).str.strip()
if pd.to_numeric(column_values, errors='coerce').notna().sum() > 0:
target_column = col
break
df['Description'] = df['Description'].str.strip().apply(clean_description)
df = rename_duplicates(df)
df['Description'] = df['Description'].str.strip().apply(lambda x: 'net income' if x.lower() == 'income' else x.strip().lower())
df['Description'] = df['Description'].str.strip().apply(lambda x: 'accounts receivable' if x.lower().startswith('accounts receivable') else x.strip().lower())
df['Description'] = df['Description'].str.strip().apply(lambda x: 'accounts receivable' if x.lower().startswith('receivables') else x.strip().lower())
df['Description'] = df['Description'].str.strip().apply(lambda x: 'accounts receivable' if x.lower().startswith('trade accounts receivable') else x.strip().lower())
df['Description'] = df['Description'].str.strip().apply(lambda x: 'accounts receivable' if x.lower().startswith('trade receivables') else x.strip().lower())
df['Description'] = df['Description'].str.strip().apply(lambda x: 'accounts payable' if x.lower().startswith('accounts payable') else x.strip().lower())
df['Description'] = df['Description'].str.strip().apply(lambda x: 'tangible assets' if x.lower().startswith('property and equipment') else x.strip().lower())
df['Description'] = df['Description'].str.strip().apply(lambda x: 'tangible assets' if x.lower().startswith('property plant and equipment') else x.strip().lower())
if 'basic' in df['Description'].values:
basic_row = df[df['Description'] == 'basic']
if basic_row.iloc[:, 1:].map(lambda x: isinstance(x, float)).any().any():
df.loc[df['Description'] == 'basic', 'Description'] = 'basic earnings per share'
if 'diluted' in df['Description'].values:
diluted_row = df[df['Description'] == 'diluted']
if diluted_row.iloc[:, 1:].map(lambda x: isinstance(x, float)).any().any():
df.loc[df['Description'] == 'diluted', 'Description'] = 'diluted earnings per share'
df = filter_description(df)
df['Value'] = df[target_column]
df = df[['Description', 'Value']]
df.dropna(subset=['Value'], inplace=True)
df.drop_duplicates(subset=['Description'], inplace=True)
df['Value'] = df['Value'].astype(str)
df['Value'] = df['Value'].str.replace('—', '0')
df['Value'] = df['Value'].str.replace('-', '0')
df['Value'] = df['Value'].str.replace(r'\s*\(\s*', '-', regex=True)
df['Value'] = df['Value'].str.replace(r'\s*\)\s*', '', regex=True)
df['Value'] = df['Value'].str.replace(',', '')
df['Value'] = df['Value'].astype(float)
return df
def update_df(consolidated_df, df, date_str):
df.rename(columns={'Value': date_str}, inplace=True)
consolidated_df = pd.merge(consolidated_df, df, on='Description', how='outer') if not consolidated_df.empty else df
return consolidated_df
def extract_cf(html_content):
soup = BeautifulSoup(html_content, "html.parser")
tables = soup.find_all('table')
search_phrases = [
"Net cash from operations",
"Cash generated by operating activities",
"Net cash provided by operating activities",
"Net cash provided by (used in) operating activities",
"Net cash provided by (used for) operating activities",
"Net cash used for operating activities",
"Net cash used in operating activities",
"Cash provided by operating activities",
"Cash provided (used) by operations",
"Net Cash Provided by Operating Activities",
"Net Cash Provided By Operating Activities",
"Net Cash Provided By (Used In) Operating Activities",
"Net Cash Used for Operating Activities",
"Net Cash Used In Operating Activities",
"Net Cash Provided by (Used for) Operating Activities",
"Net Cash (Used in) Provided by Operating Activities",
"Net Cash Used in Operating Activities",
"Net Cash Provided by (Used in) Operating Activities",
"Net cash (used in)/provided by operating activities",
"Net cash provided by/(used in) operating activities",
"Cash flows from operating activities"
]
for table in tables:
table_text = table.get_text()
if any(phrase in table_text for phrase in search_phrases):
try:
df = pd.read_html(str(table))[0]
return df
except ValueError:
continue
return None
def extract_bs(html_content):
soup = BeautifulSoup(html_content, "html.parser")
tables = soup.find_all('table')
search_phrases = [
"Total assets",
"Total Assets",
"TOTAL ASSETS"
]
for table in tables:
table_text = table.get_text()
if any(phrase in table_text for phrase in search_phrases):
try:
df = pd.read_html(str(table))[0]
return df
except ValueError:
continue
return None
def extract_is(html_content):
soup = BeautifulSoup(html_content, "html.parser")
tables = soup.find_all('table')
search_phrases = [
"Income before income taxes",
"Income before provision for income taxes",
"Income (loss) before income taxes",
"Income from continuing operations before income taxes",
"Income (loss) from continuing operations before income taxes",
"Income from operations, before income taxes",
"Income from continuing operations, before income taxes",
"Earnings before provision for income taxes",
"Income before income tax",
"Consolidated profit before taxes",
"Income Before Income Taxes",
"Loss before income taxes",
"Loss before provision for income taxes",
"Income (Loss) Before Income Taxes",
"(Loss) Income Before Income Taxes",
"Earnings before income taxes",
"Earnings Before Income Taxes"
]
for table in tables:
table_text = table.get_text()
if any(phrase in table_text for phrase in search_phrases):
try:
df = pd.read_html(str(table))[0]
return df
except ValueError:
continue
return None
def get_consolidated_dfs(ciks, tickers, form_type, dateb):
consolidated_cf_dfs = {}
consolidated_bs_dfs = {}
consolidated_is_dfs = {}
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [executor.submit(process_tickers, cik, ticker, form_type, dateb) for cik, ticker in zip(ciks, tickers)]
for future in concurrent.futures.as_completed(futures):
ticker, cf_df, bs_df, is_df = future.result()
consolidated_cf_dfs[ticker] = cf_df
consolidated_bs_dfs[ticker] = bs_df
consolidated_is_dfs[ticker] = is_df
return consolidated_cf_dfs, consolidated_bs_dfs, consolidated_is_dfs
def process_table(url, extract_func, consolidated_df):
html_content = fetch_10q_document(url)
if html_content:
table = extract_func(html_content)
if table is not None:
cleaned_df = clean_df(table, url)
date_str = extract_date(url)
consolidated_df = update_df(consolidated_df, cleaned_df, date_str).fillna(0)
return consolidated_df
def process_urls(urls):
acc_proc = set()
acc_notab = set()
acc_notab_count = {}
consolidated_cf_df = pd.DataFrame()
consolidated_bs_df = pd.DataFrame()
consolidated_is_df = pd.DataFrame()
for url in urls:
accession_number = extract_accno(url)
if accession_number in acc_proc:
continue
temp_cf_df = process_table(url, extract_cf, pd.DataFrame())
temp_bs_df = process_table(url, extract_bs, pd.DataFrame())
temp_is_df = process_table(url, extract_is, pd.DataFrame())
if not temp_bs_df.empty:
total_liabilities_and_equity = temp_bs_df[temp_bs_df['Description'] == 'total liabilities and equity']
if total_liabilities_and_equity.empty:
break
if not temp_cf_df.empty and not temp_bs_df.empty and not temp_is_df.empty:
consolidated_cf_df = pd.merge(consolidated_cf_df, temp_cf_df, on='Description', how='outer').fillna(0) if not consolidated_cf_df.empty else temp_cf_df.fillna(0)
consolidated_bs_df = pd.merge(consolidated_bs_df, temp_bs_df, on='Description', how='outer').fillna(0) if not consolidated_bs_df.empty else temp_bs_df.fillna(0)
consolidated_is_df = pd.merge(consolidated_is_df, temp_is_df, on='Description', how='outer').fillna(0) if not consolidated_is_df.empty else temp_is_df.fillna(0)
acc_proc.add(accession_number)
if accession_number in acc_notab:
acc_notab.remove(accession_number)
if accession_number in acc_notab_count:
acc_notab_count[accession_number] = 0
else:
acc_notab.add(accession_number)
if accession_number not in acc_notab_count:
acc_notab_count[accession_number] = 0
acc_notab_count[accession_number] += 1
formatted_date = extract_date(url)
if formatted_date:
month = formatted_date.split('-')[1]
break_limit = 38 if month in ['09', '10', '11'] else 30 if month in ['02', '03', '04', '05'] else 40
if acc_notab_count[accession_number] >= break_limit:
break
return consolidated_cf_df, consolidated_bs_df, consolidated_is_df
def process_tickers(cik, ticker, form_type, dateb):
accession_numbers = get_accession_numbers(cik, form_type, dateb)
urls = generate_edgar_urls(cik, accession_numbers, ticker, dateb)
cf_df, bs_df, is_df = process_urls(urls)
print(f"CF DataFrame for {ticker}")
print(f"BS DataFrame for {ticker}")
print(f"IS DataFrame for {ticker}")
return ticker, cf_df.fillna(0), bs_df.fillna(0), is_df.fillna(0)
def update_df_tickers(df, html_content, extract_function, url):
table = extract_function(html_content)
if table is not None:
cleaned_df = clean_df(table, url)
date_str = extract_date(url)
df = update_df(df, cleaned_df, date_str)
return df
def transpose_df(df):
melted_df = pd.melt(df, id_vars='Description', var_name='Date', value_name='Value')
transposed_df = melted_df.pivot(index='Date', columns='Description', values='Value')
transposed_df.index = pd.to_datetime(transposed_df.index, format="%d-%m-%Y")
transposed_df.sort_index(inplace=True)
transposed_df.index = transposed_df.index.strftime("%d-%m-%Y")
transposed_df.columns.name = None
return transposed_df
def filter_columns(cf_df, bs_df, is_df):
cf_columns_to_keep = [
"cash flow from operations", "cash flow from investing", "cash flow from financing",
"change in cash", "capex", "depreciation and amortization"
]
bs_columns_to_keep = [
"total assets", "tangible assets", "total current assets", "long term debt", "total current liabilities",
"accounts payable", "accrued expenses and other", "cash and cash equivalents", "marketable securities",
"total shareholders equity", "total liabilities and equity", "retained earnings", "goodwill",
"accounts receivable", "inventories", "operating leases"
]
is_columns_to_keep = [
"total revenues", "basic earnings per share", "diluted earnings per share", "net income",
"cost of sales", "total operating expenses", "operating income", "total non operating expenses",
"income before income taxes"
]
filtered_cf_df = cf_df[[col for col in cf_columns_to_keep if col in cf_df.columns]]
filtered_bs_df = bs_df[[col for col in bs_columns_to_keep if col in bs_df.columns]]
filtered_is_df = is_df[[col for col in is_columns_to_keep if col in is_df.columns]]
filtered_cf_df = filtered_cf_df.sort_index(axis=1)
filtered_bs_df = filtered_bs_df.sort_index(axis=1)
filtered_is_df = filtered_is_df.sort_index(axis=1)
return filtered_cf_df, filtered_bs_df, filtered_is_df
def combine_combo_dfs(consolidated_cf_dfs, consolidated_bs_dfs, consolidated_is_dfs, tickers, bond_yield, start_date, end_date):
combined_data = {}
for ticker in tickers:
share_price = get_data(ticker, start_date, end_date)
cf_df = transpose_df(consolidated_cf_dfs[ticker])
bs_df = transpose_df(consolidated_bs_dfs[ticker])
is_df = transpose_df(consolidated_is_dfs[ticker])
cf_df, bs_df, is_df = filter_columns(cf_df, bs_df, is_df)
columns_to_check = {"marketable securities": 0, "accrued expenses and other": 0, "depreciation and amortization": 0, "tangible assets": 0}
is_df['nshares'] = (is_df['net income'] / is_df['diluted earnings per share']).astype(int)
combo_df = pd.concat([cf_df, bs_df, is_df], axis=1)
combo_df = combo_df.sort_index(axis=1)
combo_df_dates = combo_df.index.to_series().unique()
combo_df = combo_df.assign(bond_yield=combo_df.index.to_series().map(lambda date: bond_yield.asof(date)))
combo_df = combo_df.assign(share_price=combo_df.index.to_series().map(lambda date: share_price.asof(date)))
combo_df["eps growth rate"] = combo_df['diluted earnings per share'].pct_change().fillna(0)
combo_df["intrinsic value"] = combo_df['diluted earnings per share'] * (8.5 + 2 * combo_df["eps growth rate"]) * 4.4 / combo_df['bond_yield']
combo_df["owner earnings"] = combo_df["net income"] - combo_df["capex"]
for column in columns_to_check:
if column not in combo_df.columns:
combo_df[column] = columns_to_check[column]
combo_df["invested capital"] = (combo_df["total assets"] - combo_df["cash and cash equivalents"] - combo_df["marketable securities"] + combo_df["accounts payable"] + combo_df["accrued expenses and other"])
combo_df["roic"] = combo_df["owner earnings"] / combo_df["invested capital"]
combo_df["current ratio"] = combo_df["total current assets"] / combo_df["total current liabilities"]
combo_df["net current assets"] = combo_df["total current assets"] - combo_df["total current liabilities"]
combo_df["bvps"] = combo_df["total shareholders equity"] / combo_df["nshares"]
combo_df["pe ratio"] = combo_df["share_price"] / combo_df["diluted earnings per share"]
combo_df["pb ratio"] = combo_df["share_price"] / (combo_df["total shareholders equity"] / combo_df["nshares"])
combo_df["multiplier pb"] = combo_df["pe ratio"] * combo_df["pb ratio"]
combo_df["margin safety"] = 1 - (combo_df["share_price"] / combo_df["intrinsic value"])
combo_df["total debt"] = combo_df["total liabilities and equity"] - combo_df["total shareholders equity"]
combo_df["tbvps"] = combo_df["tangible assets"] / combo_df["nshares"]
combo_df["ncav"] = (combo_df["total current assets"] - combo_df["total debt"]) / combo_df["nshares"]
combined_data[ticker] = {
"combined_df": combo_df,
"dates": combo_df_dates
}
return combined_data
def load_pickle(file_path):
file_name = f'Data/DataDerived/{file_path}'
with open(file_name, 'rb') as f:
return pickle.load(f)
def fetch_company_info():
url = "https://www.sec.gov/files/company_tickers.json"
response = requests.get(url, headers=headers)
if response.ok:
data = response.json()
company_info = pd.DataFrame(data).T
company_info = company_info.drop_duplicates(subset='cik_str', keep='first')
company_info['title'] = company_info['title'].str.upper()
return company_info
else:
print(f"Failed to retrieve data, status code: {response.status_code}")
return None
def fetch_form_accno():
company_info = fetch_company_info()
url_submissions = []
url_facts = []
cik_data = {}
for i in range(len(company_info)):
CIK = company_info['cik_str'][i]
url_submission = f"https://data.sec.gov/submissions/CIK{str(CIK).zfill(10)}.json"
url_submissions.append(url_submission)
url_fact = f"https://data.sec.gov/api/xbrl/companyfacts/CIK{str(CIK).zfill(10)}.json"
url_facts.append(url_fact)
def fetch_url(url, cik_str):
response = requests.get(url, headers=headers)
if response.ok:
data = response.json()
forms = data['filings']['recent']['form']
accessionNumbers = data['filings']['recent']['accessionNumber']
filtered_data = [acc_num for form, acc_num in zip(forms, accessionNumbers) if form == "10-Q"]
return cik_str, filtered_data
else:
return cik_str, []
#total_tasks = len(url_facts)
#completed_tasks = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to_url = {executor.submit(fetch_url, url, company_info['cik_str'][i]): i for i, url in enumerate(url_submissions)}
for future in concurrent.futures.as_completed(future_to_url):
cik_str, filtered_data = future.result()
if filtered_data:
cik_data[cik_str] = {'accessionNumber': filtered_data, 'facts': []}
#completed_tasks += 1
#print(f"Completed: {completed_tasks}/{total_tasks}")
with open('Data/DataDerived/accno_data.pkl', 'wb') as f:
pickle.dump((cik_data, cik_data, url_facts, url_submissions), f)
del cik_data
del url_facts
del url_submissions
gc.collect()
return 'Data/DataDerived/accno_data.pkl'
def fetch_data(fact, period):
url = f"https://data.sec.gov/api/xbrl/frames/us-gaap/{fact}/USD/{period}.json"
response = requests.get(url, headers=headers)
if response.ok:
return response.json()
def fetch_data_parallel(fact, period):
data = fetch_data(fact, period)
return fact, period, data
def fetch_facts(cik_data, url_facts):
required_fact_names = set(keywords_method1.iloc[:, 0].tolist())
total_tasks = len(url_facts)
completed_tasks = 0
def process_url(url_fact):
try:
response = requests.get(url_fact, headers=headers)
if response.ok:
facts_data = response.json()
for cik, data in cik_data.items():
accession_numbers_set = set(data['accessionNumber'])
cik_facts = facts_data.get('facts', {})
for facts in cik_facts.values():
for fact_name, fact_details in facts.items():
if fact_name not in required_fact_names:
continue
for unit_details in fact_details.get('units', {}).values():
for detail in unit_details:
temp_frame = detail.get('frame')
if detail['accn'] in accession_numbers_set and temp_frame is None:
val = detail.get('val', 'N/A')
fp = detail.get('fp', 'N/A')
fy = detail.get('fy', 'N/A')
cik_data[cik]['facts'].append({
'fact_name': fact_name,
'val': val,
'fp': fp,
'fy': fy
})
del facts_data
gc.collect()
return True
else:
return None
except:
return None
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to_url = {executor.submit(process_url, url): url for url in url_facts}
for future in concurrent.futures.as_completed(future_to_url):
result = future.result()
if result:
completed_tasks += 1
print(f"Completed: {completed_tasks}/{total_tasks}")
time.sleep(0.1)
with open('Data/DataDerived/facts_data.pkl', 'wb') as f:
pickle.dump((cik_data), f)
return 'Data/DataDerived/facts_data.pkl'
def fetch_concept_url(cik_data):
required_fact_names = set(keywords_method1.iloc[:, 0].tolist())
positive_responses = []
total_tasks = len(cik_data) * len(required_fact_names)
completed_tasks = 0
delay = 1 / 10
def fetch_links(cik, fact_name):
url_concept = f"https://data.sec.gov/api/xbrl/companyconcept/CIK{str(cik).zfill(10)}/us-gaap/{fact_name}.json"
try:
response = requests.get(url_concept, headers=headers)
if response.ok:
return url_concept
else:
return None
except requests.exceptions.RequestException:
return None
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for cik in cik_data.keys():
for fact_name in required_fact_names:
futures.append(executor.submit(fetch_links, cik, fact_name))
time.sleep(delay)
completed_tasks += 1
if completed_tasks % 1000 == 0:
print(f"Completed: {completed_tasks}/{total_tasks}")
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result:
positive_responses.append(result)
with open('Data/DataDerived/concept_urls.pkl', 'wb') as f:
pickle.dump(positive_responses, f)
return 'Data/DataDerived/concept_urls.pkl'
def fetch_concept(cik_data, concept_urls):
total_tasks = len(concept_urls)
completed_tasks = 0
def fetch_concept_data(url):
try:
response = requests.get(url, headers=headers)
if response.ok:
return url, response.json()
else:
return url, None
except requests.exceptions.RequestException:
return url, None
def process_concept_data(url, concept_data):
cik = int(url.split('CIK')[1].split('/')[0])
fact_name = url.split('us-gaap/')[1].split('.json')[0]
for _, unit_details in concept_data.get('units', {}).items():
for detail in unit_details:
if detail['accn'] in cik_data[cik]['accessionNumber'] and detail.get('frame') is None:
cik_data[cik]['facts'].append({
'fact_name': fact_name,
'val': detail.get('val', 'N/A'),
'fp': detail.get('fp', 'N/A'),
'fy': detail.get('fy', 'N/A')
})
for url in concept_urls:
url, concept_data = fetch_concept_data(url)
if concept_data:
process_concept_data(url, concept_data)
completed_tasks += 1
if completed_tasks % 100 == 0:
print(f"Completed: {completed_tasks}/{total_tasks}")
del concept_data
gc.collect()
with open('Data/DataDerived/concept_data.pkl', 'wb') as f:
pickle.dump(cik_data, f)
return 'Data/DataDerived/concept_data.pkl'
def calculate_financial_metrics(df, bond_yield, share_price):
default_columns = {
"marketable securities": 0,
"accrued expenses and other": 0
}
for column, default_value in default_columns.items():
if column not in df.columns:
df[column] = default_value
df['bond_yield'] = df.index.map(bond_yield.asof)
if share_price is not None and not share_price.empty:
df['share_price'] = df.index.map(share_price.asof)
df['share_price'] = df['share_price'].ffill().bfill()
if 'diluted earnings per share' in df.columns:
df['eps growth rate'] = df['diluted earnings per share'].pct_change().fillna(0)
if 'diluted earnings per share' in df.columns and 'bond_yield' in df.columns:
df['intrinsic value'] = df['diluted earnings per share'] * (8.5 + 2 * df['eps growth rate']) * 4.4 / df['bond_yield']
if 'share_price' in df.columns and 'intrinsic value' in df.columns:
df['margin safety'] = 1 - (df['share_price'] / df['intrinsic value'])
if 'total current assets' in df.columns and 'total current liabilities' in df.columns:
df['current ratio'] = df['total current assets'] / df['total current liabilities']
df['net current assets'] = df['total current assets'] - df['total current liabilities']
if 'share_price' in df.columns and 'diluted earnings per share' in df.columns:
df['pe ratio'] = df['share_price'] / df['diluted earnings per share']
if 'capex' in df.columns and 'depreciation and amortization' in df.columns and 'net income' in df.columns:
df['owner earnings'] = df['net income'] - df['capex']
if {'total assets', 'cash and cash equivalents', 'accounts payable'}.issubset(df.columns):
df['invested capital'] = (
df['total assets'] - df['cash and cash equivalents'] - df['marketable securities'] +
df['accounts payable'] + df['accrued expenses and other']
)
if 'owner earnings' in df.columns:
df['roic'] = df['owner earnings'] / df['invested capital']
if 'total shareholders equity' in df.columns and 'nshares' in df.columns:
df['bvps'] = df['total shareholders equity'] / df['nshares']
if 'share_price' in df.columns:
df['pb ratio'] = df['share_price'] / df['bvps']
if 'pe ratio' in df.columns:
df['multiplier pb'] = df['pe ratio'] * df['pb ratio']
if 'total liabilities and equity' in df.columns and 'total shareholders equity' in df.columns:
df['total debt'] = df['total liabilities and equity'] - df['total shareholders equity']
if 'tangible assets' in df.columns and 'nshares' in df.columns:
df['tbvps'] = df['tangible assets'] / df['nshares']
if 'total debt' in df.columns and 'total current assets' in df.columns and 'nshares' in df.columns:
df['ncav'] = (df['total current assets'] - df['total debt']) / df['nshares']
df = df.loc[:, ~df.columns.duplicated()]
return df
def convert_fp_to_date(fp, fy):
fp_to_date = {
'Q1': '0331',
'Q2': '0630',
'Q3': '0930',
'Q4': '1231'
}
fy_str = str(int(fy))
return pd.to_datetime(f"{fy_str}{fp_to_date[fp]}", format='%Y%m%d')
def convert_quarters(index_name):
if 'Q' in index_name:
year_quarter = index_name.split('CY')[1]
year = year_quarter[:4]
quarter = year_quarter[4:]
if quarter == 'Q1':
return pd.Timestamp(f'{year}-03-31')
elif quarter == 'Q2':
return pd.Timestamp(f'{year}-06-30')
elif quarter == 'Q3':
return pd.Timestamp(f'{year}-09-30')
elif quarter == 'Q4':
return pd.Timestamp(f'{year}-12-31')
return index_name
def df_facts_ticker(cik, ticker_data, bond_yield):
facts = ticker_data['facts']
df = pd.DataFrame(facts)
if df.empty:
return df
df = df[(df['fp'] != 'FY') & (df['fy'].notna())]
df['date'] = df.apply(lambda row: convert_fp_to_date(row['fp'], row['fy']), axis=1)
df = df.drop(columns=['fp', 'fy'])
df = df.drop_duplicates(subset=['date', 'fact_name'])
start_date = df['date'].min()
end_date = df['date'].max()
complete_dates = pd.date_range(start=start_date, end=end_date, freq='Q')
df = df.pivot(index='date', columns='fact_name', values='val')
df = df.reindex(complete_dates).sort_index()
df = df.rename_axis(None, axis=0).rename_axis(None, axis=1)
df = df.dropna(axis=1, how='all')
df = df.loc[:, (df.sum(axis=0) != 0)]
df = df.round(2).fillna(0)
df = transform_df(df)
df = df.sort_index()
column_mapping = dict(zip(keywords_method1.iloc[:, 0], keywords_method1.iloc[:, 1]))
df.rename(columns=column_mapping, inplace=True)
df = df.reindex(sorted(df.columns), axis=1)
df = df.replace(0, pd.NA)
df = df.ffill().bfill()
ticker = get_ticker_from_cik(cik)
if ticker is not None:
share_price = get_data(ticker, start_date, end_date)
if share_price is not None and not share_price.empty:
df = df.assign(share_price=share_price)
df['share_price'] = df['share_price'].ffill().bfill()
df = calculate_financial_metrics(df, bond_yield, share_price)
else:
df = calculate_financial_metrics(df, bond_yield, None)
else:
df = calculate_financial_metrics(df, bond_yield, None)
return df.fillna(0)
def dfs_facts_tickers(cik_data, bond_yield, filename_prefix):
ticker_dfs = {}
for cik, data in cik_data.items():
ticker_dfs[cik] = df_facts_ticker(cik, data, bond_yield)
print(f"Completed {len(ticker_dfs)}/{len(cik_data)}")
filename = f"Data/DataDerived/{filename_prefix}_df_file.pkl"
with open(filename, 'wb') as f:
pickle.dump(ticker_dfs, f)
return filename
def process_data(start_year, end_year):
quarters = ['Q4', 'Q3', 'Q2', 'Q1']
cik_database = {}
futures = []
with concurrent.futures.ThreadPoolExecutor() as executor:
for _, row in keywords_method1.iterrows():
fact = row[0]
for year in range(start_year, end_year + 1):
for quarter in quarters:
period = f"CY{year}{quarter}"
future = executor.submit(fetch_data_parallel, fact, period)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
fact, period, data = future.result()
if data:
for item in data['data']:
cik = item['cik']
if cik not in cik_database:
cik_database[cik] = {}
cik_database[cik][f"{fact}_{period}"] = item['val']
with open('Data/DataDerived/frames_data.pkl', 'wb') as f:
pickle.dump(cik_database, f)
del cik_database