-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_retrieval.R
965 lines (830 loc) · 43.7 KB
/
data_retrieval.R
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
# Author: gp1981
# Purpose: Contains the script to retrieve company data from SEC filings.
# Disclaimer: This script is intended for educational purposes only and should not be used for investment decisions. Use at your own risk.
# Function to retrieve list of companies ----------------------------------
# Function to operating companies from SEC database.
retrieve_Company_List <- function(headers) {
# Retrieve company tickers list
company_Tickers <- GET("https://www.sec.gov/files/company_tickers.json", add_headers(headers))
# Check for HTTP errors
if (http_error(company_Tickers)) {
stop("Failed to retrieve company list. HTTP error: ", http_status(company_Tickers)$message)
}
# Proceed with data extraction
company_Tickers_List <- fromJSON(httr::content(company_Tickers, as = "text"))
# Convert the JSON list to a data frame
company_List <- as.data.frame(t(sapply(company_Tickers_List, unlist)), stringsAsFactors = FALSE)
# Add zeros to CIK
company_List$cik_str <- sprintf("%010s", company_List$cik_str)
return(company_List)
}
# Function to retrieve company data ---------------------------------------
# Function to retrieve company data based on cik code from SEC database.
retrieve_Company_Data <- function(headers, cik) {
# Retrieve company metadata
company_Metadata <- GET(paste0("https://data.sec.gov/submissions/CIK", cik, ".json"), add_headers(headers))
# Check for HTTP errors in company_Metadata request
if (http_error(company_Metadata)) {
stop("Failed to retrieve company metadata. HTTP error: ", http_status(company_Metadata)$message)
}
# Process and adjust JSON data
company_Metadata <- fromJSON(httr::content(company_Metadata, as = "text"))
# Retrieve company Facts
company_Facts <- GET(paste0("https://data.sec.gov/api/xbrl/companyfacts/CIK", cik, ".json"), add_headers(headers))
# Check for HTTP errors in company_Facts request
if (http_error(company_Facts)) {
stop("Failed to retrieve company facts. HTTP error: ", http_status(company_Facts)$message)
}
# Process and adjust JSON data
company_Facts <- fromJSON(httr::content(company_Facts, as = "text"))
# Retrieve company Concepts
company_Concept <- GET(paste0("https://data.sec.gov/api/xbrl/companyconcept/CIK", cik, "/us-gaap/Assets.json"), add_headers(headers))
# Check for HTTP errors in company_Concept request
if (http_error(company_Concept)) {
stop("Failed to retrieve company concept data. HTTP error: ", http_status(company_Concept)$message)
}
# Process and adjust JSON data
company_Concept <- fromJSON(httr::content(company_Concept, as = "text"))
# Prepare output
company_Data <- list(
company_Metadata = company_Metadata,
company_Facts = company_Facts,
company_Concept = company_Concept
)
return(company_Data)
}
# Function to create a dataframe of fundamentals ---------------------------------------
# Function to unnest list company_Facts using parallel processing. This function takes company_Data and unnests it, creating a data frame with relevant information including values, labels, descriptions, etc.
Fundamentals_to_Dataframe <- function(company_Data) {
# Ensure cik has 10 digits
company_details_cik <- sprintf("%010d", company_Data$company_Facts$cik)
# Extract tickers separately
company_details_ticker <- company_Data$company_Metadata$tickers[1]
# Create a vector with the modified details
company_details <- c(
company_details_cik,
company_Data$company_Facts$entityName,
company_Data$company_Metadata$sic,
company_Data$company_Metadata$sicDescription,
company_details_ticker
)
# Create a data frame with the details
details_df <- as.data.frame(t(company_details))
colnames(details_df) <- c("cik", "entityName", "sic", "sicDescription","tickers")
# Retrieve company_Facts data
company_Facts_us_gaap <- company_Data$company_Facts$facts$`us-gaap`
# Use parallel processing with future_map_dfr to apply the operation on each list concurrently
df_units <- furrr::future_map_dfr(names(company_Facts_us_gaap), function(list_name) {
# Extract the relevant information from the 'units' list and create a tibble
df_list <- company_Facts_us_gaap[[list_name]]$units$USD %>%
as_tibble() %>%
# Add columns with 'label', 'description', and 'us_gaap_reference'
mutate(
label = company_Facts_us_gaap[[list_name]]$label,
description = company_Facts_us_gaap[[list_name]]$description,
us_gaap_reference = list_name
)
return(df_list)
})
# Replicate details_df to match the number of rows in df_units
details_replicated <- details_df[rep(seq_len(nrow(details_df)), each = nrow(df_units)), ]
# Bind the two data frames together
df_units <- bind_cols(df_units, details_replicated)
# Mutate to reduce values in millions by dividing by 1 million
df_units <- df_units %>%
mutate(
val = val / 1e6
)
return(df_units)
}
# Function to create a dataframe of fundamentals from json SEC files ---------------------------------------
# Function to unnest list company_Facts using parallel processing. This function takes company_Data and unnests it, creating a data frame with relevant information including values, labels, descriptions, etc.
Fundamentals_to_Dataframe_multi_files <- function(company_Data,company_details_cik,company_List) {
# # Create a vector with the modified details
# company_details <- c(
# company_details_cik,
# company_Data$company_Facts$entityName,
# company_Data$company_Metadata$sic,
# company_Data$company_Metadata$sicDescription,
# company_details_ticker
# )
# # Create a data frame with the details
# details_df <- as.data.frame(t(company_details))
# colnames(details_df) <- c("cik", "entityName", "sic", "sicDescription","tickers")
# Retrieve company_Facts data
company_Facts_us_gaap <- company_Data$facts$`us-gaap`
# Use parallel processing with future_map_dfr to apply the operation on each list concurrently
df_units <- furrr::future_map_dfr(names(company_Facts_us_gaap), function(list_name) {
# Extract the relevant information from the 'units' list and create a tibble
df_list <- company_Facts_us_gaap[[list_name]]$units$USD %>%
as_tibble() %>%
# Add columns with 'label', 'description', and 'us_gaap_reference'
mutate(
label = company_Facts_us_gaap[[list_name]]$label,
description = company_Facts_us_gaap[[list_name]]$description,
us_gaap_reference = list_name
)
return(df_list)
})
# Add the corresponding ticker to the dataframe
df_units <- df_units %>%
mutate(
entityName = company_Data$entityName,
cik = company_details_cik,
tickers = company_List[company_List$cik_str == company_details_cik,]$cik_str)
# # Replicate details_df to match the number of rows in df_units
# details_replicated <- details_df[rep(seq_len(nrow(details_df)), each = nrow(df_units)), ]
#
# # Bind the two data frames together
# df_units <- bind_cols(df_units, details_replicated)
#
# Mutate to reduce values in millions by dividing by 1 million
df_units <- df_units %>%
mutate(
val = val / 1e6
)
return(df_units)
}
# Function to rebuild the balancesheet statement ---------------------------------------
# Function to create a dataframe representative of the quarterly balance sheet of the entity. The basis for the dataframe is a standardized balance sheet (standardized_balancesheet.xlsx).
BS_std <- function(df_Facts) {
# 01 - Join standardized_balancesheet ------------------------------------------------------
# Define the standardized balancesheet file path
BS_path <- here(data_dir, "standardized_BS.xlsx")
# Read the standardized_BS.xlsx file
standardized_BS <- read.xlsx(BS_path, sheet = "Sheet1")
# Rename standardized_BS column df_Fact_Description to perform left_join
standardized_BS <- standardized_BS %>%
rename(description = df_Facts_Description)
# Merge df_Facts with standardized_BS based on description and period
df_std_BS <- df_Facts %>%
left_join(standardized_BS, by = "description") %>%
filter(Financial.Report == "BS") %>%
select(standardized_label, everything())
# 02 - Data cleaning ------------------------------------------------------
# This code filters rows based on whether there's a "/A" in the 'form' column. Rows with "/A" are retained if any row in their group contains it. Relevant columns are selected.
# Change format of start and end dates from characters to date
df_std_BS <- df_std_BS %>%
mutate(end = as.Date(end),
start = as.Date(start),
filed = as.Date(filed),
val = as.numeric(val))
df_std_BS <- df_std_BS %>%
# Filter out rows without standardized_label
filter(!is.na(standardized_label)) %>%
# Group by end period (end) and label
group_by(end, description) %>%
# Arrange by descending end date within each group
arrange(desc(end)) %>%
# Add a column indicating if any row in the group has a form ending with /A
mutate(
has_form_A = grepl("/A$", form)
) %>%
# Filter rows based on the condition:
# - Retain rows without /A
# - Retain rows with /A if there's at least one row with /A in the group
filter(!has_form_A | (has_form_A & grepl("/A$", form))) %>%
# Select relevant columns
select(end, standardized_label, everything(),-has_form_A) %>%
# Arrange by descending end date
arrange(desc(end)) %>%
# Remove grouping
ungroup() %>%
# Group by and arrange by descending filed date within each group
group_by(standardized_label, end) %>%
# Arrange by filed date
arrange(desc(filed)) %>%
# Retain only the first row i.e.. most recent by "filed" date
slice_head(n = 1) %>%
# Remove grouping
ungroup()
# Split the 'end' column into 'year_end' and 'quarter_end'
df_std_BS <- df_std_BS %>%
mutate(
year_end = as.integer(lubridate::year(end)),
quarter_end = as.integer(lubridate::quarter(end)),
year_start = case_when(
Financial.Report == "BS" & is.na(as.integer(lubridate::year(start))) ~ as.integer(lubridate::year(end)), TRUE ~ as.integer(lubridate::year(start))),
quarter_start = case_when(
Financial.Report == "BS" & is.na(as.integer(lubridate::quarter(start))) ~ as.integer(lubridate::quarter(end)), TRUE ~ as.integer(lubridate::quarter(start)))
)
# Prepare dataframe for pivot
df_std_BS_pivot <- df_std_BS %>%
# Group by standardized_lable and fiscal period
group_by(end,standardized_label,year_end,quarter_end, accn,cik,sic, sicDescription,tickers, Financial.Report) %>%
# Sum Quarterly_val within the group
summarise(
quarterly_val= sum(val)
) %>%
ungroup() %>%
select(end, standardized_label, quarterly_val, year_end, quarter_end, everything())
# 03 - Pivot df_std_BS in a dataframe format ------------------------------------------------------
# This code transforms the data from a long format with multiple rows per observation to a wide format where each observation is represented by a single row with columns corresponding to different Concepts
df_std_BS <- df_std_BS_pivot %>%
select(end,standardized_label,quarterly_val) %>%
# Pivot the data using standardized_cashflow_label as column names
pivot_wider(
names_from = standardized_label,
values_from = quarterly_val
) %>%
# Arrange the dataframe in descending order based on the 'end' column
arrange(desc(end))
# 04 - Add new columns for standardization -----------------------------------
# This code add the missing columns to the df_std_BS based on the standardized_balancesheet.xls and perform checks
## Step 1 - Check key financial Concepts -----------------------------------
# It checks whether specific columns exist or are empty. If so it stops or remove corresponding rows
if (!("Total Assets" %in% colnames(df_std_BS)) || !("Total Liabilities" %in% colnames(df_std_BS))) {
stop("Total Assets or Total Liabilities is missing. The entity is not adequate for financial analysis.")
}
if (!("Total Liabilities & Stockholders Equity" %in% colnames(df_std_BS))) {
stop("Total Liabilities & Stockholders Equity is missing. The entity is not adequate for financial analysis.")
}
if (!("Total Current Assets" %in% colnames(df_std_BS))) {
stop("Total Current Assets is missing. The entity is not adequate for financial analysis.")
}
if (!("Total Current Liabilities" %in% colnames(df_std_BS))) {
stop("Both Total Current Liabilities is missing. The entity is not adequate for financial analysis.")
}
# Remove rows where key financial Concepts are empty (or NA)
df_std_BS <- df_std_BS %>%
filter(
any(!is.na(`Total Liabilities & Stockholders Equity`) | `Total Liabilities & Stockholders Equity` != ""),
any(!is.na(`Total Assets`) | `Total Assets` != ""),
any(!is.na(`Total Liabilities`) | `Total Liabilities` != "")
)
## Step 2 - Add missing columns -----------------------------------
# It checks which columns from columns_to_add are not already present in df_std_BS
columns_to_add <- setdiff(standardized_BS$standardized_label,colnames(df_std_BS))
#It then adds only the missing columns to df_std_BS and initializes them with NA.
if (length(columns_to_add) > 0) {
# Add columns to the dataframe
df_std_BS[,columns_to_add] <- NA
}
# Prepare company details to add to df_std_BS as additional columns
df_Facts_columns_to_add <- df_Facts[1:nrow(df_std_BS), ]
# Add company details columns to df_std_BS
df_std_BS <- cbind(df_std_BS,df_Facts_columns_to_add[,c("cik","entityName","sic","sicDescription","tickers")])
## Step 3 - Calculate newly added columns columns -----------------------------------
# Evaluate expressions for newly added columns
df_std_BS <- df_std_BS %>%
mutate(
`Total Current Assets` = pmax(0, case_when(
is.na(`Total Current Assets`) ~ coalesce(`Total Assets`,0) - coalesce(`Total Non Current Assets`,0),
TRUE ~ coalesce(`Total Current Assets`,0)
)),
`Total Non Current Assets` = pmax(0, case_when(
is.na(`Total Non Current Assets`) ~ coalesce(`Total Assets`,0) - coalesce(`Total Current Assets`,0),
TRUE ~ coalesce(`Total Non Current Assets`,0)
)),
`Other Current Assets` = pmax(0, case_when(
is.na(`Other Current Assets`) ~ coalesce(`Total Current Assets`,0) - (coalesce(`Cash & Cash Equivalent`,0) + coalesce(`Marketable Securities Current`,0) + coalesce(`Total Accounts Receivable`,0) + coalesce(`Total Inventory`,0) + coalesce(`Prepaid Expenses`,0)),
TRUE ~ coalesce(`Other Current Assets`,0)
)),
`Other Non Current Assets` = pmax(0, case_when(
is.na(`Other Non Current Assets`) ~ coalesce(`Total Non Current Assets`,0) - (coalesce(`Marketable Securities Non Current`,0) + coalesce(`Property Plant and Equipment`,0) + coalesce(`Intangible Assets (excl. goodwill)`,0) + coalesce(`Goodwill`,0)),
TRUE ~ coalesce(`Other Non Current Assets`,0)
)),
`Total Non Current Liabilities` = pmax(0, case_when(
is.na(`Total Non Current Liabilities`) ~ coalesce(`Total Liabilities`,0) - coalesce(`Total Current Liabilities`,0),
TRUE ~ coalesce(`Total Non Current Liabilities`,0)
)),
`Other Current Liabilities` = pmax(0, case_when(
is.na(`Other Current Liabilities`) ~ coalesce(`Total Current Liabilities`,0) - (coalesce(`Accounts Payable`,0) + coalesce(`Tax Payable`,0) + coalesce(`Current Debts`,0) + coalesce(`Operating Lease Liability Current`,0)),
TRUE ~ coalesce(`Other Current Liabilities`,0)
)),
`Other Non Current Liabilities` = pmax(0, case_when(
is.na(`Other Non Current Liabilities`) ~ coalesce(`Total Non Current Liabilities`,0) - (coalesce(`Non Current Debts`,0) + coalesce(`Operating Lease Liability Non Current`,0)),
TRUE ~ coalesce(`Other Non Current Liabilities`,0)
)),
`Total Stockholders Equity` = case_when(
is.na(`Total Stockholders Equity`) ~ coalesce(`Total Liabilities & Stockholders Equity`,0) - coalesce(`Total Liabilities`,0),
TRUE ~ coalesce(`Total Stockholders Equity`,0)
)
)
## Step 4 - Order columns based on standardized_balancesheet_label -----------------------------------
custom_order <- unique(standardized_BS[,1])
# Reorder the columns as per standardized_balancesheet.xlsx
df_std_BS <- df_std_BS[, c("end", custom_order)]
# Add the columns with the metadata
df_std_BS <- df_std_BS %>%
mutate(
cik = df_Facts$cik[1],
entityName = df_Facts$entityName[1],
sic = df_Facts$sic[1],
sicDescription = df_Facts$sicDescription[1],
tickers = df_Facts$tickers[1]
)
return(df_std_BS)
}
# Function to rebuild the income statement ---------------------------------------
# Function to create a dataframe representative of the quarterly income statement of the entity. The basis for the dataframe is a standardized income statement (standardized_IS.xlsx). In case of quarters that are missing the data (Facts) are estimated. The estimate of the data of the missing quarters is calculated based on the yearly data available. The difference between the yearly data and the data from the available quarter is then allocated equally to the missing quarters.
IS_std <- function(df_Facts) {
# 01 - Join standardized_IS ------------------------------------------------------
# Define the standardized incomestatement file path
IS_path <- here(data_dir, "standardized_IS.xlsx")
# Read the standardized_IS.xlsx file
standardized_IS <- read.xlsx(IS_path, sheet = "Sheet1")
# Rename standardized_IS column df_Fact_Description to perform left_join
standardized_IS <- standardized_IS %>%
rename(description = df_Facts_Description)
# Merge df_Facts with standardized_IS based on description and period
df_std_IS <- df_Facts %>%
left_join(standardized_IS, by = "description") %>%
filter(Financial.Report == "IS") %>%
select(standardized_label, everything(), -df_Facts_us_gaap_references)
# 02 - Data cleaning ------------------------------------------------------
# This code filters rows in df_std_IS based on whether there's a "/A" in the 'form' column. Rows with "/A" are retained if any row in their group contains it. Relevant columns are selected.
# Change format of start and end dates from characters to date
df_std_IS <- df_std_IS %>%
mutate(end = as.Date(end),
start = as.Date(start),
filed = as.Date(filed),
val = as.numeric(val))
df_std_IS <- df_std_IS %>%
# Filter out rows without standardized_label
filter(!is.na(standardized_label)) %>%
# Group by end period (end) and label
group_by(end, description) %>%
# Arrange by descending end date within each group
arrange(desc(end)) %>%
# Add a column indicating if any row in the group has a form ending with /A
mutate(
has_form_A = grepl("/A$", form)
) %>%
# Filter rows based on the condition:
# - Retain rows without /A
# - Retain rows with /A if there's at least one row with /A in the group
filter(!has_form_A | (has_form_A & grepl("/A$", form))) %>%
# Select relevant columns
select(end, standardized_label, everything(),-has_form_A) %>%
# Arrange by descending end date
arrange(desc(end)) %>%
# Remove grouping
ungroup()
# Split the 'end' and 'start' columns into 'year_end/start' and 'quarter_end/start'
df_std_IS <- df_std_IS %>%
mutate(
year_end = as.integer(lubridate::year(end)),
quarter_end = as.integer(lubridate::quarter(end)),
year_start = case_when(
Financial.Report == "BS" & is.na(as.integer(lubridate::year(start))) ~ as.integer(lubridate::year(end)), TRUE ~ as.integer(lubridate::year(start))),
quarter_start = case_when(
Financial.Report == "BS" & is.na(as.integer(lubridate::quarter(start))) ~ as.integer(lubridate::quarter(end)), TRUE ~ as.integer(lubridate::quarter(start)))
)
# 03 - Handling cumulative values and estimating missing quarters ------------------------------------------------------
# Perform additional data processing to clean data set and estimate cumulative values from existing data
# Estimate number of quarters underlying a Fact of financial item i.e. val
df_std_IS <- df_std_IS %>%
group_by(description, year_end) %>%
arrange(desc(quarter_end), desc(quarter_start)) %>%
mutate(
cumulative_quarters = case_when(
year_end == year_start & quarter_end != quarter_start ~ quarter_end - quarter_start + 1,
TRUE ~ 1)
)%>%
ungroup()
# Remove duplicated from multiple filings retaining the rows with the most recent "filed" date with the largest number of quarters covered
df_std_IS <- df_std_IS %>%
group_by(description, year_end, quarter_end) %>%
# Arrange by descending "filed" date and cumulative quarters
arrange(desc(filed), desc(cumulative_quarters)) %>%
# Retain the first in the group ordered by "filed" date
distinct(description, end, .keep_all = TRUE) %>%
# Keep only the first occurrence of each unique combination of description and end date
ungroup()
# Calculate the number of distinct quarters and the missing ones represented by each description in the dataset.
df_std_IS_quarter_summary <- df_std_IS %>%
group_by(description) %>%
# Summarize the number of distinct quarters represented for each description
summarise(total_quarters_end = n_distinct(quarter_end)) %>%
# Calculate number of quarters missing in the grouping
mutate(
"No. Quarters Missing" = ifelse(total_quarters_end == 4, 0, 4 - total_quarters_end)
) %>%
ungroup()
# Calculate preliminary quarterly_val based on the number of quarters within group_by description and year_end
df_std_IS <- df_std_IS %>%
# Group by year and description
group_by(description, year_end) %>%
# Calculate quarterly_Val based on the number of cumulative quarters
mutate(
quarterly_val = val / cumulative_quarters,
# Calculate the number of rows in the group_by
count_rows = n()
) %>%
ungroup()
# Adjust quarterly_val based on existing of cumulative values
df_std_IS <- df_std_IS %>%
# Group by description and year_end
group_by(description, year_end) %>%
# Arrange the dataframe to properly position lead() values
arrange(desc(cumulative_quarters), desc(quarter_end), quarter_start) %>%
mutate(
# Column to count the records in the group
count_rows = n(),
# Recalculate quarterly_val for specific cases as differences from lead() values
quarterly_val = case_when(
cumulative_quarters == 1 ~ quarterly_val,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 1 &
quarter_start == lead(quarter_start) ~ val - lead(val),
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 2 &
quarter_start == lead(quarter_start) ~ val - lead(val) - quarterly_val,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 3 &
quarter_start == lead(quarter_start) ~ val - lead(val) - 2 * quarterly_val,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end)&
quarter_start == lead(quarter_start) + 1 ~ val - lead(val),
TRUE ~ quarterly_val),
# Detect quarterly_val modified
modified_quarterly_val = case_when(
cumulative_quarters == 1 ~ FALSE,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 1 &
quarter_start == lead(quarter_start) ~ TRUE,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 2 &
quarter_start == lead(quarter_start) ~ TRUE,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 3 &
quarter_start == lead(quarter_start) ~ TRUE,
TRUE ~ FALSE)
) %>%
ungroup() %>%
select(end, standardized_label, val, quarterly_val, year_end, quarter_end, quarter_start, cumulative_quarters, count_rows, modified_quarterly_val, everything())
# Filter out rows with duplicated val for the same standardized label
df_std_IS <- df_std_IS %>%
# Group by the standardized label for the same year and same quarter
group_by(standardized_label, year_end, quarter_end) %>%
# Arrange to by quarters_end and descending date "filed"
arrange(desc(quarter_end),desc(filed)) %>%
# Keep only the first occurrence of 'val' within each group
filter(!duplicated(standardized_label,val)) %>%
ungroup()
# Prepare dataframe for pivot
df_std_IS_pivot <- df_std_IS %>%
# Group by standardized_lable and fiscal period
group_by(end,standardized_label,year_end,quarter_end, accn,cik,sic, sicDescription,tickers, Financial.Report) %>%
# Sum Quarterly_val within the group
summarise(
quarterly_val= sum(quarterly_val)
) %>%
ungroup() %>%
select(end, standardized_label, quarterly_val, year_end, quarter_end, everything())
# 03 - Pivot df_std_IS in a dataframe format
# This code transforms the data from a long format with multiple rows per observation to a wide format where each observation is represented by a single row with columns corresponding to different Concepts
df_std_IS <- df_std_IS_pivot %>%
select(end,standardized_label,quarterly_val) %>%
# Pivot the data using standardized_label as column
pivot_wider(
names_from = standardized_label,
values_from = quarterly_val
) %>%
# Arrange the dataframe in descending order based on the 'end' column
arrange(desc(end))
# 04 - Add new columns for standardization -----------------------------------
# This code add the missing columns to the df_std_IS based on the standardized_incomestatement.xls and perform checks
## Step 1 - Check key financial Concepts -----------------------------------
# It checks whether specific columns exist or are empty. If so it stops or remove corresponding rows
if (!("Gross Profit" %in% colnames(df_std_IS)) ||
!("Operating Income" %in% colnames(df_std_IS)) ||
!("Net Income (loss) (continous operations)" %in% colnames(df_std_IS))) {
stop("Gross Profit or Operating Income or Net Income (loss) is missing. The entity is not adequate for financial analysis.")
}
# Remove rows where key financial Concepts are empty (or NA)
df_std_IS <- df_std_IS %>%
filter(
any(!is.na(`Gross Profit`) | `Gross Profit` != ""),
any(!is.na(`Operating Income`) | `Operating Income` != ""),
any(!is.na(`Net Income (loss) (continous operations)`) | `Net Income (loss) (continous operations)` != "")
)
## Step 2 - Add missing columns -----------------------------------
# It checks which columns from columns_to_add are not already present in df_std_IS
columns_to_add <- setdiff(standardized_IS$standardized_label,colnames(df_std_IS))
#It then adds only the missing columns to df_std_IS and initializes them with NA.
if (length(columns_to_add) > 0) {
# Add columns to the dataframe
df_std_IS[,columns_to_add] <- NA
}
## Step 3 - Calculate newly added columns columns -----------------------------------
# Evaluate expressions for key financial Concepts
df_std_IS <- df_std_IS %>%
mutate(
`Revenue` = case_when(
is.na(`Revenue`) ~ coalesce(`Cost of Revenue`,0) + coalesce(`Gross Profit`,0),
TRUE ~ coalesce(`Revenue`,0)
),
`Cost of Revenue` = case_when(
is.na(`Cost of Revenue`) ~ coalesce(`Revenue`,0) - coalesce(`Gross Profit`,0),
TRUE ~ coalesce(`Cost of Revenue`,0)
),
`Other Non Operating Income (Loss) Net` = case_when(
is.na(`Other Non Operating Income (Loss) Net`) ~ coalesce(`Gross Profit`,0) - (coalesce(`Research and development`,0) + coalesce(`Sales general and administrative costs`,0) + coalesce(`Operating Income`,0)),
),
`Other income (expense) Net` = case_when(
is.na(`Other income (expense) Net`) ~ coalesce(`Operating Income`,0) - (coalesce(`Interest Income`,0) + coalesce(`Interest Expense`,0) + coalesce(`Income Before Income Tax`,0)),
),
) %>%
mutate_all(~round(., digits = 4)) # Adjust the number of digits as needed
## Step 4 - Order columns based on standardized_incomestatement_label -----------------------------------
custom_order <- unique(standardized_IS[,1])
# Reorder the columns as per standardized_incomestatement.xlsx
df_std_IS <- df_std_IS[, c("end", custom_order)]
# Add the columns with the metadata
df_std_IS <- df_std_IS %>%
mutate(
cik = df_Facts$cik[1],
entityName = df_Facts$entityName[1],
sic = df_Facts$sic[1],
sicDescription = df_Facts$sicDescription[1],
tickers = df_Facts$tickers[1]
)
return(df_std_IS)
}
# Function to rebuild the Cash Flow statements ---------------------------------------
# Function to create a dataframe representative of the quarterly Cash Flow statement of the entity. The basis for the dataframe is a Cash Flow statement (standardized_CF.xlsx). In case of quarters that are missing the data (Facts) are estimated. The estimate of the data of the missing quarters is calculated based on the yearly data available. The difference between the yearly data and the data from the available quarters is then allocated equally to the missing quarters.
CF_std <- function(df_Facts) {
# 01 - Join standardized Cashflow (CF) ------------------------------------------------------
# Define the standardized CF file path
CF_path <- here(data_dir, "standardized_CF.xlsx")
# Read the standardized_CF.xlsx file
standardized_CF <- read.xlsx(CF_path, sheet = "Sheet1")
# Rename standardized_label column df_Fact_Description to perform left_join
standardized_CF <- standardized_CF %>%
rename(description = df_Facts_Description)
# Merge df_Facts with standardized_CF based on description and period
df_std_CF <- df_Facts %>%
left_join(standardized_CF, by = "description") %>%
filter(Financial.Report == "CF") %>%
select(standardized_label, everything(), -df_Facts_us_gaap_references)
# 02 - Data cleaning ------------------------------------------------------
# This code filters rows based on whether there's a "/A" in the 'form' column. Rows with "/A" are retained if any row in their group contains it. Relevant columns are selected.
# Change format of start and end dates from characters to date
df_std_CF <- df_std_CF %>%
mutate(end = as.Date(end),
start = as.Date(start),
filed = as.Date(filed),
val = as.numeric(val))
df_std_CF <- df_std_CF %>%
# Filter out rows without standardized_label
filter(!is.na(standardized_label)) %>%
# Group by end period (end) and label
group_by(end, description) %>%
# Arrange by descending end date within each group
arrange(desc(end)) %>%
# Add a column indicating if any row in the group has a form ending with /A
mutate(
has_form_A = grepl("/A$", form)
) %>%
# Filter rows based on the condition:
# - Retain rows without /A
# - Retain rows with /A if there's at least one row with /A in the group
filter(!has_form_A | (has_form_A & grepl("/A$", form))) %>%
# Select relevant columns
select(end, standardized_label, everything(),-has_form_A) %>%
# Arrange by descending end date
arrange(desc(end)) %>%
# Remove grouping
ungroup()
# Split the 'end' and 'start' columns into 'year_end/start' and 'quarter_end/start'
df_std_CF <- df_std_CF %>%
mutate(
year_end = as.integer(lubridate::year(end)),
quarter_end = as.integer(lubridate::quarter(end)),
year_start = case_when(
Financial.Report == "BS" & is.na(as.integer(lubridate::year(start))) ~ as.integer(lubridate::year(end)), TRUE ~ as.integer(lubridate::year(start))),
quarter_start = case_when(
Financial.Report == "BS" & is.na(as.integer(lubridate::quarter(start))) ~ as.integer(lubridate::quarter(end)), TRUE ~ as.integer(lubridate::quarter(start)))
)
# 03 - Handling cumulative values and estimating missing quarters ------------------------------------------------------
# Perform additional data processing to clean data set and estimate cumulative values from existing data
# Estimate number of quarters underlying a Fact of financial item i.e. val
df_std_CF <- df_std_CF %>%
group_by(description, year_end) %>%
arrange(desc(quarter_end), desc(quarter_start)) %>%
mutate(
cumulative_quarters = case_when(
year_end == year_start & quarter_end != quarter_start ~ quarter_end - quarter_start + 1,
TRUE ~ 1)
)%>%
ungroup()
# Remove duplicated from multiple filings retaining the rows with the most recent "filed" date with the largest number of quarters covered
df_std_CF <- df_std_CF %>%
group_by( description, year_end, quarter_end) %>%
# Arrange by descending "filed" date and cumulative quarters
arrange(desc(filed), desc(cumulative_quarters)) %>%
# Retain the first in the group ordered by "filed" date
distinct(description, end, .keep_all = TRUE) %>%
# Keep only the first occurrence of each unique combination of description and end date
ungroup()
# Calculate the number of distinct quarters and the missing ones represented by each description in the dataset.
df_std_CF_quarter_summary <- df_std_CF %>%
group_by(description) %>%
# Summarize the number of distinct quarters represented for each description
summarise(total_quarters_end = n_distinct(quarter_end)) %>%
# Calculate number of quarters missing in the grouping
mutate(
"No. Quarters Missing" = ifelse(total_quarters_end == 4, 0, 4 - total_quarters_end)
) %>%
ungroup()
# Calculate preliminary quarterly_val based on the number of quarters within group_by description and year_end
df_std_CF <- df_std_CF %>%
# Group by year and description
group_by(description, year_end) %>%
# Calculate quarterly_Val based on the number of cumulative quarters
mutate(
quarterly_val = val / cumulative_quarters,
# Calculate the number of rows in the group_by
count_rows = n()
) %>%
ungroup()
# Adjust quarterly_val based on existing of cumulative values
df_std_CF <- df_std_CF %>%
# Group by description and year_end
group_by(description, year_end) %>%
# Arrange the dataframe to properly position lead() values
arrange(desc(cumulative_quarters), desc(quarter_end), quarter_start) %>%
mutate(
# Column to count the records in the group
count_rows = n(),
# Recalculate quarterly_val for specific cases as differences from lead() values
quarterly_val = case_when(
cumulative_quarters == 1 ~ quarterly_val,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 1 &
quarter_start == lead(quarter_start) ~ val - lead(val),
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 2 &
quarter_start == lead(quarter_start) ~ val - lead(val) - quarterly_val,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 3 &
quarter_start == lead(quarter_start) ~ val - lead(val) - 2 * quarterly_val,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end)&
quarter_start == lead(quarter_start) + 1 ~ val - lead(val),
TRUE ~ quarterly_val),
# Detect quarterly_val modified
modified_quarterly_val = case_when(
cumulative_quarters == 1 ~ FALSE,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 1 &
quarter_start == lead(quarter_start) ~ TRUE,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 2 &
quarter_start == lead(quarter_start) ~ TRUE,
cumulative_quarters >= 2 &
count_rows > 1 &
!is.na(lead(quarter_end)) &
!is.na(lead(quarter_start)) &
quarter_end == lead(quarter_end) + 3 &
quarter_start == lead(quarter_start) ~ TRUE,
TRUE ~ FALSE)
) %>%
ungroup() %>%
select(end, standardized_label, val, quarterly_val, year_end, quarter_end, quarter_start, cumulative_quarters, count_rows, modified_quarterly_val, everything())
# Filter out rows with duplicated val for the same standardized label
df_std_CF <- df_std_CF %>%
# Group by the standardized label for the same year and same quarter
group_by(standardized_label, year_end, quarter_end) %>%
# Arrange to by quarters_end and descending date "filed"
arrange(desc(quarter_end),desc(filed)) %>%
# Keep only the first occurrence of 'val' within each group
filter(!duplicated(standardized_label,val)) %>%
ungroup()
# Prepare dataframe for pivot
df_std_CF_pivot <- df_std_CF %>%
# Group by standardized_lable and fiscal period
group_by(end,standardized_label,year_end,quarter_end, accn,cik,sic, sicDescription,tickers, Financial.Report) %>%
# Sum Quarterly_val within the group
summarise(
quarterly_val= sum(quarterly_val)
) %>%
ungroup() %>%
select(end, standardized_label, quarterly_val, year_end, quarter_end, everything())
# 04 - Cash Flow - Pivot df_std_CF in horizontal format
# This code transforms the data from a long format with multiple rows per observation to a wide format where each observation is represented by a single row with columns corresponding to different Concepts
df_std_CF <- df_std_CF_pivot %>%
select(end,standardized_label,quarterly_val) %>%
# Pivot the data using standardized_cashflow_label as column names
pivot_wider(
names_from = standardized_label,
values_from = quarterly_val
) %>%
# Arrange the dataframe in descending order based on the 'end' column
arrange(desc(end))
# 04 - Add new columns for standardization -----------------------------------
# This code add the missing columns to the df_std_CF based on the standardized_cashflow.xls and perform checks
## Step 1 - Check key financial Concepts -----------------------------------
# It checks whether specific columns exist or are empty. If so it stops or remove corresponding rows
if (!("(Operating Activities) Cash Flow from Operating Activities" %in% colnames(df_std_CF)) || !("(Investing Activities) Cash Flow from Investing Activities" %in% colnames(df_std_CF)) || !("(Financing Activities) Cash Flow from Financing Activities" %in% colnames(df_std_CF))) {
stop("Cash Flow from Operating activities or Investing activities or Financing activities is missing. The entity is not adequate for financial analysis.")
}
# Remove rows where key financial Concepts are empty (or NA)
df_std_CF <- df_std_CF %>%
filter(
any(!is.na(`(Operating Activities) Cash Flow from Operating Activities`) | `(Operating Activities) Cash Flow from Operating Activities` != ""),
any(!is.na(`(Investing Activities) Cash Flow from Investing Activities`) | `(Investing Activities) Cash Flow from Investing Activities` != ""),
any(!is.na(`(Financing Activities) Cash Flow from Financing Activities`) | `(Financing Activities) Cash Flow from Financing Activities` != "")
)
## Step 2 - Add missing columns -----------------------------------
# It checks which columns from columns_to_add are not already present in df_std_CF
columns_to_add <- setdiff(standardized_CF$standardized_label,colnames(df_std_CF))
#Adds only the missing columns to df_std_CF and initializes them with NA.
if (length(columns_to_add) > 0) {
# Add columns to the dataframe
df_std_CF[,columns_to_add] <- NA
}
## Step 3 - Calculate newly added columns columns -----------------------------------
# Evaluate expressions for key financial Concepts
df_std_CF <- df_std_CF %>%
mutate(
`(Operating Activities) Change in Other Operating Activities` =
coalesce(`(Operating Activities) Cash Flow from Operating Activities`,0) -
(coalesce(`(Operating Activities) Cash Flow Depreciation, Depletion, Ammortization`,0) +
coalesce(`(Operating Activities) Change in Accounts Receivable`,0) +
coalesce(`(Operating Activities) Change in Inventory`,0) +
coalesce(`(Operating Activities) Change in Prepaid expenses and other assets`,0) +
coalesce(`(Operating Activities) Change in Accounts Payable`,0) +
coalesce(`(Operating Activities) Change in Accounts Taxes Payable`,0) +
coalesce(`(Operating Activities) Change in Reserve for Sales Return and allowances`,0) +
coalesce(`(Operating Activities) Deferred Income Tax`,0) +
coalesce(`(Operating Activities) Stock-based Compensation`,0)
),
,
`(Investing Activities) Change in Other Investing Activities` =
coalesce(`(Investing Activities) Cash Flow from Investing Activities`,0) -
(coalesce(`(Investing Activities) Purchase of Property, Plant and Equipment`,0) +
coalesce(`(Investing Activities) Proceeds from Asset Sales`,0) +
coalesce(`(Investing Activities) Purchase of Businesses`,0) +
coalesce(`(Investing Activities) Purchase of Marketable Securities and Investment`,0) +
coalesce(`(Investing Activities) Proceeds from sale or maturity of Marketable Securities and Investment`,0) +
coalesce(`(Investing Activities) Proceeds from maturities of Marketable Securities and Investment`,0)
),
,
`(Financing Activities) Impact of Stock Options and Other` =
coalesce(`(Financing Activities) Cash Flow from Financing Activities`,0) -
(coalesce(`(Financing Activities) Proceeds from Issuance of Stock`,0) +
coalesce(`(Financing Activities) Payment for Repurchase of Stock`,0) +
coalesce(`(Financing Activities) Proceeds from Issuance of Debt`,0) +
coalesce(`(Financing Activities) Payment of Debt`,0) +
coalesce(`(Financing Activities) Cash for Dividends`,0)
),
,
) %>%
mutate_all(~round(., digits = 4)) # Adjust the number of digits as needed
## Step 4 - Order columns based on standardized_cashflow_label -----------------------------------
custom_order <- unique(standardized_CF[,"standardized_label"])
# Reorder the columns as per standardized_CF.xlsx
df_std_CF <- df_std_CF[, c("end", custom_order)]
# Add the columns with the metadata
df_std_CF <- df_std_CF %>%
mutate(
cik = df_Facts$cik[1],
entityName = df_Facts$entityName[1],
sic = df_Facts$sic[1],
sicDescription = df_Facts$sicDescription[1],
tickers = df_Facts$tickers[1]
)
return(df_std_CF)
}