This repository has been archived by the owner on Dec 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
0_portfolio_input_check_functions.R
1791 lines (1394 loc) · 53.9 KB
/
0_portfolio_input_check_functions.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
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
# devtools::load_all()
# ridiculous hack to avoid janitor::clean_names() throwing numerous warnings when running in our
# docker image: https://github.com/Tazinho/snakecase/issues/191
# explanation: I believe snakecase:::replace_special_characters_internal is only a promise until
# the first time it is called, so simply printing the function to stdout causes the function to
# be loaded for the first time, triggering the warnings, thereby relieving any further calls
# to it from additional warnings
# because janitor::clean_names() is used in multiple functions here, this is the cleanest way
# to deal with them all at once up front
suppressWarnings(invisible(snakecase:::replace_special_characters_internal))
### Portfolio cleaning functions
read_raw_portfolio_file <- function(project_name) {
portfolio <- NA
input_path <- paste0(project_location, "/20_Raw_Inputs/")
csv_to_read <- list.files(path = input_path, pattern = "_Input.csv")
txt_to_read <- list.files(path = input_path, pattern = "_Input.txt")
if (length(csv_to_read) == 1) {
portfolio <- read_csv(paste0(input_path, csv_to_read))
}
if (length(txt_to_read) == 1) {
enc <- guess_encoding(paste0(input_path, txt_to_read))$encoding[1]
portfolio <- read.table(paste0(input_path, txt_to_read), sep = ",", header = T, fileEncoding = enc)
}
# Reads in Files saved with a ; not a ,
if (ncol(portfolio) == 1 & length(csv_to_read) == 1) {
portfolio <- read.csv(paste0(input_path, csv_to_read), strip.white = T, stringsAsFactors = F, sep = ";")
}
if (ncol(portfolio) == 1 & length(txt_to_read) == 1) {
portfolio <- read.table(paste0(input_path, txt_to_read), sep = "\t", header = T, fileEncoding = enc)
}
if (ncol(portfolio) == 1 & length(txt_to_read) == 1) {
portfolio <- read.table(paste0(input_path, txt_to_read), sep = ";", header = T, fileEncoding = enc)
}
if (!data_check(portfolio)) {
stop("No portfolio Input File")
}
portfolio
}
clean_colnames_portfolio_input_file <- function(portfolio) {
if (is.data.frame(portfolio)) {
# Removes additional columns added by Excel on saving
portfolio <- portfolio[, !grepl("X", colnames(portfolio))]
} else {
stop("No portfolio Data readable")
}
portfolio <- janitor::clean_names(portfolio)
if ("numberof_shares" %in% colnames(portfolio)) {
portfolio <- portfolio %>% rename(number_of_shares = numberof_shares)
}
portfolio
}
clean_portfolio_col_types <- function(portfolio, grouping_variables) {
# portfolio[,grouping_variables] <- lapply(portfolio[,grouping_variables], clean_punctuation)
if (is.character(portfolio$investor_name) == FALSE) {
write_log(msg = paste0(
"Wrong variable class for investor_name. Should be character, but is ",
class(portfolio$investor_name),
". This can introduce errors in further calculations!"
),
file_path = log_path)
}
if (is.character(portfolio$portfolio_name) == FALSE) {
write_log(msg = paste0(
"Wrong variable class for portfolio_name Should be character, but is ",
class(portfolio$portfolio_name),
". This can introduce errors in further calculations!"
),
file_path = log_path)
}
if (is.numeric(portfolio$market_value) == FALSE) {
write_log(msg = paste0(
"Wrong variable class for market_value Should be numeric, but is ",
class(portfolio$market_value),
". This can introduce errors in further calculations!"
),
file_path = log_path)
}
if("number_of_shares" %in% colnames(portfolio)){
if (is.numeric(portfolio$number_of_shares) == FALSE) {
write_log(msg = paste0(
"Wrong variable class for number_of_shares Should be numeric, but is ",
class(portfolio$number_of_shares),
". This can introduce errors in further calculations!"
),
file_path = log_path)
}
portfolio$number_of_shares <- suppressWarnings(as.numeric(portfolio$number_of_shares))
}
if (is.character(portfolio$currency) == FALSE) {
write_log(msg = paste0(
"Wrong variable class for currency Should be character, but is ",
class(portfolio$currency),
". This can introduce errors in further calculations!"
),
file_path = log_path)
}
if (is.character(portfolio$isin) == FALSE) {
write_log(msg = paste0(
"Wrong variable class for isin Should be character, but is ",
class(portfolio$isin),
". This can introduce errors in further calculations!"
),
file_path = log_path)
}
portfolio$market_value <- as.numeric(portfolio$market_value)
portfolio$currency <- as.character(portfolio$currency)
portfolio$currency <- if_else(portfolio$currency == "Euro", "EUR", portfolio$currency)
portfolio
}
clear_portfolio_input_blanks <- function(portfolio) {
if (any(portfolio[, grouping_variables] == "" | is.na(portfolio[, grouping_variables]))) {
print("Warning: missing grouping variables, corresponding rows removed")
write_log(msg = paste(
"Warning: some entries of the uploaded portfolio file were removed
because of missing values in at least one of the variables", str_c(grouping_variables, collapse = ", "),
"\n To ensure complete analysis, please upload a file without
missing values in these columns."
),
file_path = log_path)
portfolio <- portfolio %>% filter_at(
grouping_variables, all_vars(!is.na(.))
)
}
portfolio
}
add_meta_portfolio <- function(portfolio, inc_meta_portfolio) {
portfolio_meta <- portfolio
# Group at a level
# lvl <- 1
#
#
# gv <- grouping_variables[1:lvl]
# ngv <- grouping_variables[seq(lvl+1,length(grouping_variables))]
#
# portfolio_1 <- portfolio_meta %>% mutate(!!!rlang::syms(ngv) = "Meta")
#
#
# # loop through grouping variables
# # the order of gv defines this
#
# for (g in length(grouping_variables)){
#
# gv <- grouping_variables[g]
#
# # portfolio_meta_sub <- [,gv]
#
# portfolio_0 <- portfolio %>%
# mutate(country_group = "meta",
# investor_name = "meta",
# portfolio_name = "meta")
#
# portfolio_1 <- portfolio %>%
# group_by(country_group) %>%
# mutate(investor_name = paste(country_group, "meta"),
# portfolio_name = paste(country_group, "meta"))
#
# portfolio_2 <- portfolio %>%
# group_by(country_group, investor_name) %>%
# mutate(portfolio_name = paste(investor_name, "meta"))
#
# portfolio_all <- bind_rows(portfolio,portfolio_0, portfolio_1, portfolio_2)
#
# }
if (inc_meta_portfolio) {
portfolio_meta$portfolio_name <- meta_portfolio_name
portfolio_meta$investor_name <- meta_investor_name
portfolio <- rbind(portfolio, portfolio_meta)
}
portfolio
}
add_holding_id <- function(portfolio) {
if (length(setdiff("holding_id", names(portfolio))) != 0) {
portfolio$holding_id <- row.names(portfolio)
}
portfolio
}
check_missing_cols <- function(portfolio, grouping_variables) {
required_input_cols <- c("holding_id", "market_value", "currency", "isin", grouping_variables, "number_of_shares")
if (!"number_of_shares" %in% colnames(portfolio)) {
portfolio$number_of_shares <- NA_real_
}
missing_columns <- setdiff(required_input_cols, colnames(portfolio))
if (length(missing_columns) > 0) {
write_log(
msg = paste0("The input file is missing the following data columns: ", missing_columns),
file_path = log_path
)
stop(paste0("The input file is missing the following data columns: ", missing_columns))
}
portfolio <- as_tibble(portfolio)
portfolio
}
set_currency_timestamp <- function(currencies) {
currencies <- currencies %>% mutate(ExchangeRate_2019Q2 = 1)
currencies <- currencies %>%
select(Currency_abbr, paste0("ExchangeRate_", financial_timestamp)) %>%
filter(!is.na(Currency_abbr), Currency_abbr != "") %>%
distinct()
names(currencies) <- c("currency", "exchange_rate")
currencies$exchange_rate <- as.numeric(currencies$exchange_rate)
currencies
}
### Fin data cleaning functions
map_security_sectors <- function(fin_data, sector_bridge) {
initial_no_rows <- nrow(fin_data)
fin_data <- fin_data %>%
left_join(sector_bridge %>% filter(source == "BICS") %>% select(-source),
by = c("security_bics_subgroup" = "industry_classification")
) %>%
mutate(security_icb_subsector = as.character(security_icb_subsector))
fin_data_na <- fin_data %>%
filter(is.na(sector)) %>%
select(-c(sector,sector_boe,subsector_boe,sector_dnb,sector_ipr,subsector_ipr))
fin_data <- fin_data %>% filter(!is.na(sector))
fin_data_na <- fin_data_na %>% left_join(sector_bridge %>% filter(source == "ICB") %>% select(-source),
by = c("security_icb_subsector" = "industry_classification")
)
fin_data <- fin_data %>% bind_rows(fin_data_na)
fin_data <- fin_data %>%
select(-security_mapped_sector) %>%
rename(security_mapped_sector = sector)
fin_data %>%
group_by(security_mapped_sector) %>%
filter(is.na(security_mapped_sector)) %>%
summarise(count = n())
fin_data_na <- fin_data %>% filter(is.na(security_mapped_sector))
if (nrow(fin_data) != initial_no_rows) {
stop("Rows being dropped in mapping sectors")
}
return(fin_data)
}
map_comp_sectors <- function(comp_fin_data, sector_bridge) {
initial_no_rows <- nrow(comp_fin_data)
comp_fin_data <- comp_fin_data %>% left_join(sector_bridge %>% filter(source == "BICS") %>% select(-source),
by = c("bics_subgroup" = "industry_classification")
)
comp_fin_data_na <- comp_fin_data %>%
filter(is.na(sector)) %>%
select(-sector)
comp_fin_data <- comp_fin_data %>% filter(!is.na(sector))
comp_fin_data_na <- comp_fin_data_na %>% left_join(sector_bridge %>% filter(source == "ICB") %>% select(-source),
by = c("icb_subgroup" = "industry_classification")
)
comp_fin_data <- comp_fin_data %>% bind_rows(comp_fin_data_na)
comp_fin_data <- comp_fin_data %>%
select(-financial_sector) %>%
rename(financial_sector = sector)
comp_fin_data %>%
group_by(financial_sector) %>%
filter(is.na(financial_sector)) %>%
summarise(count = n())
comp_fin_data_na <- comp_fin_data %>% filter(is.na(financial_sector))
if (nrow(comp_fin_data) != initial_no_rows) {
stop("Rows being dropped in mapping sectors")
}
return(comp_fin_data)
}
override_sector_classification <- function(fin_data, overrides) {
start_rows <- nrow(fin_data)
overrides <- overrides %>%
mutate_at(vars(company_name, corporate_bond_ticker, fin_sector_override), list(as.character))
overrides$sector_override <- TRUE
# Merge in by company corp ticker
overrides_cbt <- overrides %>%
filter(corporate_bond_ticker != "", !is.na(corporate_bond_ticker)) %>%
select(corporate_bond_ticker, fin_sector_override, sector_override) %>%
distinct()
fin_data <- left_join(fin_data, overrides_cbt, by = "corporate_bond_ticker")
# Merge in by bloomberg_id
overrides_bbg <- overrides %>%
filter(is.na(corporate_bond_ticker) | corporate_bond_ticker == "") %>%
select(bloomberg_id, fin_sector_override, sector_override) %>%
distinct()
fin_data <- left_join(fin_data, overrides_bbg, by = "bloomberg_id")
# Clean resulting financial data
fin_data <- fin_data %>%
mutate(
sector_override = sector_override.x,
sector_override = if_else(sector_override.y != "" & !is.na(sector_override.y), sector_override.y, sector_override),
fin_sector_override = fin_sector_override.x,
fin_sector_override = if_else(!is.na(fin_sector_override.y) & fin_sector_override.y != "", fin_sector_override.y, fin_sector_override),
sector_override = if_else(is.na(sector_override), FALSE, TRUE)
) %>%
select(-sector_override.x, -sector_override.y, -fin_sector_override.x, -fin_sector_override.y)
fin_data <- fin_data %>%
mutate(security_mapped_sector = if_else(sector_override, fin_sector_override, security_mapped_sector)) %>%
select(-fin_sector_override)
if (nrow(fin_data) != start_rows) {
stop("Additional rows being added by fin sector override")
}
fin_data
}
check_asset_types <- function(fin_data) {
fin_data <- fin_data %>%
mutate(
asset_type = if_else(asset_type == "Other", "Others", asset_type),
asset_type = if_else(is.na(asset_type), "Others", asset_type),
)
fin_data$asset_type <- first_char_up(fin_data$asset_type)
### TEST
# if (!any(unique(fin_data$asset_type) %in% allowable_asset_list())) {
# stop("Check Financial Data Asset Types")
# }
fin_data
}
check_mapped_assets_flag <- function(fin_data) {
# convert old naming of "mapped to assets" column to be mapped_to_assets
if ("EQ.mapped_to_assets" %in% colnames(fin_data) | "CB.mapped_to_assets" %in% colnames(fin_data) | "has_prod_after_2018" %in% colnames(fin_data)) {
if ("EQ.mapped_to_assets" %in% colnames(fin_data) | "CB.mapped_to_assets" %in% colnames(fin_data)) {
fin_data <- fin_data %>%
mutate(
mapped_to_assets = case_when(
Asset.Type == "Equity" ~ EQ.mapped_to_assets,
Asset.Type == "Bonds" ~ CB.mapped_to_assets,
TRUE ~ 0
)
) %>%
select(-CB.mapped_to_assets, -EQ.mapped_to_assets)
} else if ("has_prod_after_2018" %in% colnames(fin_data)) {
fin_data <- fin_data %>%
mutate(
mapped_to_assets = has_prod_after_2018
) %>%
select(-has_prod_after_2018)
}
}
unique(fin_data$mapped_to_assets)
# Ensure that flag is a logical
fin_data <- fin_data %>%
mutate(mapped_to_assets = case_when(
mapped_to_assets %in% c("t", 1) ~ TRUE,
mapped_to_assets %in% c("f", 0) ~ FALSE
))
### TEST
any(!fin_data$mapped_to_assets %in% c(TRUE, FALSE))
###
fin_data
}
check_fin_mapped_sectors <- function(fin_data) {
fin_data <- fin_data %>%
mutate(security_mapped_sector = case_when(
security_mapped_sector == "Others" ~ "Other",
security_mapped_sector == "OIl&Gas" ~ "Oil&Gas",
is.na(security_mapped_sector) ~ "Other",
TRUE ~ security_mapped_sector
))
actual_sectors <- unique(fin_data$security_mapped_sector)
if (any(!actual_sectors %in% c(sector_list, pacta_sectors_not_analysed, "Other"))) {
stop("Additional Sectors in fin_data")
}
fin_data
}
convert_corporate_bonds <- function(fin_data) {
cb_groups <- c("Convertible Bonds", "Corporate Bonds", "Corporate inflation linked Bonds", "Convertible Preferreds")
fin_data <- fin_data %>%
mutate(
asset_type = if_else(security_type %in% cb_groups, "Bonds", asset_type),
asset_type = if_else(!security_type %in% cb_groups & asset_type == "Bonds", "Others", asset_type),
)
fin_data
}
identify_sb <- function(fin_data) {
sb_groups <- c("Sovereign Debt", "Sovereign Agency Debt", "Government inflation linked Bonds", "Sovereign", "Sovereign Agency", "Sovereigns")
fin_data <- fin_data %>%
mutate(is_sb = case_when(
security_type %in% sb_groups ~ TRUE,
security_bics_subgroup %in% sb_groups ~ TRUE,
TRUE ~ FALSE
))
fin_data
}
classify_all_funds <- function(fin_data) {
nrow(fin_data[fin_data$asset_type == "Funds", ])
fin_data <- fin_data %>%
mutate(asset_type = case_when(
grepl("Fund", security_type) ~ "Funds",
grepl("ETF", security_type) ~ "Funds",
grepl("Fund", security_bclass4) ~ "Funds",
grepl("ETF", security_bclass4) ~ "Funds",
grepl("Fund", security_icb_subsector) ~ "Funds",
grepl("ETF", security_icb_subsector) ~ "Funds",
TRUE ~ asset_type
))
### TEST?
fin_data
}
normalise_fund_data <- function(fund_data) {
if (data_check(fund_data)) {
fund_data <- fund_data %>%
group_by(fund_isin) %>%
mutate(total_weight = sum(isin_weight, na.rm = T))
fund_data_large <- fund_data %>%
group_by(fund_isin) %>%
filter(total_weight > 1) %>%
mutate(isin_weight = isin_weight / total_weight) %>%
select(-total_weight)
fund_data_small <- fund_data %>%
group_by(fund_isin) %>%
filter(total_weight <= 1) %>%
select(-total_weight)
fund_data_missing <- fund_data_small %>%
summarise(isin_weight = 1 - sum(isin_weight, na.rm = T)) %>%
mutate(holding_isin = "MissingValue")
fund_data <- bind_rows(fund_data_large, fund_data_small, fund_data_missing)
fund_data
} else {
stop("No fund data")
}
fund_data
}
### Portfolio Check Functions
convert_currencies <- function(portfolio, currencies) {
portfolio <- left_join(portfolio, currencies, by = "currency")
portfolio$value_usd <- portfolio$market_value * portfolio$exchange_rate
portfolio
}
add_fin_data <- function(portfolio, fin_data) {
left_join(portfolio, fin_data, by = "isin")
}
calculate_value_usd_with_fin_data <- function(portfolio) {
# check correct inputs
necessary_columns <- c("currency", "unit_share_price")
### TEST
if (!any(necessary_columns %in% colnames(portfolio))) {
stop("Portfolio not structured correctly")
}
# add missing currency for number of shares
portfolio <- portfolio %>%
mutate(currency = if_else(!is.na(number_of_shares), "USD", currency))
# calculates the value_usd where number of shares are given
portfolio <- portfolio %>%
mutate(value_usd = if_else(
asset_type %in% c("Equity", "Funds") & is.na(value_usd),
number_of_shares * unit_share_price,
value_usd
))
portfolio
}
identify_fund_portfolio <- function(portfolio) {
fund_portfolio <- portfolio %>% filter(asset_type == "Funds", !is.na(isin))
fund_portfolio
}
calculate_fund_portfolio <- function(fund_portfolio, fund_data, cols_portfolio_no_bbg = cols_portfolio, cols_funds = cols_of_funds) {
if (data_check(fund_portfolio)) {
fund_portfolio <- left_join(fund_portfolio, fund_data, by = c("isin" = "fund_isin"), all.x = T)
fund_portfolio$direct_holding <- FALSE
fund_portfolio$original_value_usd <- fund_portfolio$value_usd
fund_portfolio$value_usd <- fund_portfolio$isin_weight * fund_portfolio$value_usd
fund_portfolio$fund_isin <- fund_portfolio$isin
fund_portfolio$isin <- fund_portfolio$holding_isin
# If there is no fund breakdown available, return the "original isin data" to the original locations
fund_portfolio <- fund_portfolio %>%
mutate(
value_usd = if_else(!fund_isin %in% fund_data$fund_isin, original_value_usd, value_usd),
isin = if_else(!fund_isin %in% fund_data$fund_isin, fund_isin, isin),
direct_holding = if_else(!fund_isin %in% fund_data$fund_isin, TRUE, direct_holding),
)
} else {
fund_portfolio <- fund_portfolio %>% bind_cols(data.frame(direct_holding = integer(0), fund_isin = character(0), original_value_usd = numeric(0)))
}
fund_portfolio <- fund_portfolio %>% select(all_of(cols_portfolio_no_bbg), all_of(cols_funds))
fund_portfolio
}
add_fund_portfolio <- function(portfolio, fund_portfolio, cols_of_funds) {
# Remove the fund lines from the portfolio
portfolio_no_funds <- portfolio %>% filter(!isin %in% fund_portfolio$fund_isin)
# Check that there are the correct number of isins in both portfolios
if (nrow(portfolio_no_funds) + length(unique(fund_portfolio$holding_id)) != nrow(portfolio)) {
stop("Something unexpected with fund portfolio merge")
}
# Add additional fund relevant lines to original portfolio
portfolio_no_funds <- portfolio_no_funds %>%
mutate(
direct_holding = TRUE,
fund_isin = NA,
original_value_usd = value_usd
)
# select same columns for both portfolios
portfolio_no_funds <- portfolio_no_funds %>% select(colnames(portfolio), all_of(cols_of_funds))
fund_portfolio <- fund_portfolio %>% select(colnames(portfolio), all_of(cols_of_funds))
if (!identical(colnames(portfolio_no_funds), colnames(fund_portfolio))) {
stop("Colnames not equal, funds vs no funds")
}
# Merge in the results
portfolio_total <- rbind(portfolio_no_funds, fund_portfolio)
portfolio_total <- as_tibble(portfolio_total)
portfolio_total
}
# Add Columns for missing or incorrect information
check_isin_format <- function(portfolio_total) {
portfolio_total <- portfolio_total %>%
mutate(has_valid_isin = case_when(
nchar(isin) != 12 ~ FALSE,
isin == "" ~ FALSE,
is.na(isin) ~ FALSE,
grepl("[^[:alnum:]]", isin) ~ FALSE,
TRUE ~ TRUE
))
portfolio_total
}
check_missing_currency <- function(portfolio_total) {
# Currency blank or not in our currency data frame
portfolio_total <- portfolio_total %>%
mutate(has_currency = case_when(
is.na(currency) ~ FALSE,
currency == "" ~ FALSE,
!currency %in% currencies$currency ~ FALSE,
TRUE ~ TRUE
))
portfolio_total
}
check_valid_input_value <- function(portfolio_total) {
# Currency negative or missing market value/number of shares
portfolio_total <- portfolio_total %>%
mutate(has_valid_input = case_when(
is.na(market_value) & is.na(number_of_shares) ~ FALSE,
market_value < 0 ~ FALSE,
number_of_shares < 0 ~ FALSE,
# !currency %in% currencies$currency ~ FALSE,
TRUE ~ TRUE
))
portfolio_total
}
check_valid_value_usd <- function(portfolio_total) {
portfolio_total <- portfolio_total %>%
mutate(
has_valid_value_usd = case_when(
is.na(value_usd) & is.na(number_of_shares) ~ FALSE,
value_usd < 0 ~ FALSE,
number_of_shares < 0 ~ FALSE,
TRUE ~ TRUE
)
)
portfolio_total
}
check_bloomberg_data <- function(portfolio_total) {
portfolio_total <- portfolio_total %>%
mutate(has_bbg_data = case_when(
(asset_type == "Equity" | asset_type == "Unclassifiable") & (is.na(bloomberg_id) | bloomberg_id == "") ~ FALSE,
(asset_type == "Bonds" | asset_type == "Unclassifiable") & (is.na(corporate_bond_ticker) | corporate_bond_ticker == "") ~ FALSE,
(asset_type == "" | asset_type == "Unclassifiable") ~ FALSE,
is.na(asset_type) ~ FALSE,
TRUE ~ TRUE
))
portfolio_total
}
add_flags <- function(portfolio) {
portfolio <- portfolio %>%
mutate(flag = case_when(
!has_currency ~ "Missing currency information",
!has_valid_input ~ "Negative or missing input value",
!has_valid_isin ~ "Invalid or missing ISIN",
!has_bbg_data ~ "Holding not in Bloomberg database",
TRUE ~ "Included in analysis"
))
portfolio
}
overall_validity_flag <- function(portfolio_total) {
portfolio_total <- portfolio_total %>%
mutate(valid_input = case_when(
!has_currency ~ FALSE,
!has_bbg_data ~ FALSE,
!has_valid_input ~ FALSE,
!has_valid_isin ~ FALSE,
TRUE ~ TRUE
))
portfolio_total
}
create_ald_flag <- function(portfolio, comp_fin_data, debt_fin_data) {
portfolio_eq <- portfolio %>% filter(asset_type == "Equity")
portfolio_cb <- portfolio %>% filter(asset_type == "Bonds")
portfolio_other <- portfolio %>% filter(!asset_type %in% c("Equity", "Bonds"))
portfolio_eq <- check_for_ald(portfolio_eq, "Equity", comp_fin_data)
portfolio_cb <- check_for_ald(portfolio_cb, "Bonds", debt_fin_data)
if (data_check(portfolio_other)) {
portfolio_other <- portfolio_other %>% mutate(
has_asset_level_data = NA,
sectors_with_assets = NA,
has_ald_in_fin_sector = NA
)
} else {
portfolio_other <- portfolio_other %>% add_column("has_asset_level_data", "sectors_with_assets", "has_ald_in_fin_sector")
}
portfolio <- rbind(portfolio_eq, portfolio_cb, portfolio_other)
}
check_for_ald <- function(portfolio_subset, portfolio_type, relevant_fin_data) {
if (data_check(portfolio_subset)) {
initial_port_value <- sum(portfolio_subset$value_usd, na.rm = T)
if (portfolio_type == "Equity") {
joining_id <- "company_id"
} else if (portfolio_type == "Bonds") {
joining_id <- "corporate_bond_ticker"
}
ald_markers <- relevant_fin_data %>%
select(all_of(joining_id), has_asset_level_data, sectors_with_assets) %>%
distinct()
portfolio_subset <- left_join(portfolio_subset, ald_markers, by = joining_id)
portfolio_subset <- portfolio_subset %>%
rowwise() %>%
mutate(has_ald_in_fin_sector = if_else(grepl(financial_sector, sectors_with_assets), TRUE, FALSE)) %>%
ungroup()
if (sum(portfolio_subset$value_usd, na.rm = T) != initial_port_value) {
stop("Merge over company id changes portfolio value")
}
} else {
portfolio_subset <- portfolio_subset %>% add_column("has_asset_level_data", "sectors_with_assets", "has_ald_in_fin_sector")
}
return(portfolio_subset)
}
add_revenue_split <- function(has_revenue, portfolio, revenue_data) {
if (has_revenue) {
revenue_data_min <- revenue_data %>%
filter(!is.na(company_id)) %>%
select(-company_name, -equity_ticker, -corporate_bond_ticker, -bloomberg_id)
initial_portfolio_value <- sum(portfolio$value_usd, na.rm = T)
port_rev <- left_join(portfolio, revenue_data_min, by = "company_id", all.x = T)
# Fill in gaps where possible
port_rev <- port_rev %>%
mutate(
has_revenue_data = if_else(is.na(has_revenue_data), FALSE, has_revenue_data),
tot_rev = if_else(is.na(tot_rev), 1, tot_rev),
revenue_sector = if_else(is.na(revenue_sector), "Other", revenue_sector),
value_usd = value_usd * tot_rev
) %>%
rename(financial_sector = revenue_sector)
if (sum(port_rev$value_usd, na.rm = T) != initial_portfolio_value) {
stop("Revenue data causing duplications")
}
} else {
port_rev <- portfolio %>%
mutate(
has_revenue_data = FALSE,
financial_sector = security_mapped_sector
)
}
return(port_rev)
}
calculate_number_of_shares <- function(portfolio) {
portfolio <- portfolio %>%
mutate(number_of_shares = ifelse(is.na(number_of_shares) & asset_type == "Equity", value_usd / unit_share_price, number_of_shares))
return(portfolio)
}
create_id_columns <- function(portfolio, portfolio_type) {
if (portfolio_type == "Equity") {
portfolio <- portfolio %>%
rename(id = bloomberg_id) %>%
mutate(
id_name = "bloomberg_id",
id = as.character(id)
)
}
if (portfolio_type == "Bonds") {
portfolio <- portfolio %>%
rename(id = corporate_bond_ticker) %>%
mutate(
id_name = "corporate_bond_ticker",
id = as.character(id)
)
}
return(portfolio)
}
# FINAL SCRIPTS
get_and_clean_total_fund_list_data <- function() {
total_fund_list <- read_rda("data/total_fund_list.rds")
total_fund_list
}
get_and_clean_currency_data <- function() {
currencies <- readRDS("data/currencies.rds")
currencies <- set_currency_timestamp(currencies)
if (all(currencies$exchange_rate) == 1){print("currency data temporary. todo: update")}
currencies
}
get_and_clean_fund_data <- function() {
fund_data <- NA
# Fund Data
if (file.exists(paste0(analysis_inputs_path, "/fund_data_", financial_timestamp, ".rda"))) {
fund_data <- readRDS(paste0(analysis_inputs_path, "/fund_data_", financial_timestamp, ".rda"))
} else if (file.exists(paste0(analysis_inputs_path, "/fund_data_2018Q4.rda"))) {
fund_data <- readRDS(paste0(analysis_inputs_path, "/fund_data_2018Q4.rda"))
print("Old Fund Data being used. Replace FundsData2018Q4 or check name of file.")
} else if (file.exists(paste0(analysis_inputs_path, "/SFC_26052020_funds.csv"))) {
fund_data <- read_csv(paste0(analysis_inputs_path, "/SFC_26052020_funds.csv"))
print("2020Q2 SFC fund data being used")
} else {
if (!data_check(fund_data)) {
warning("No fund data available")
}
}
if (data_check(fund_data)) {
fund_data <- fund_data %>% janitor::clean_names()
fund_data <- fund_data %>% filter(!is.na(holding_isin) & holding_isin != "")
fund_data$holding_isin <- as.character(fund_data$holding_isin)
fund_data$fund_isin <- as.character(fund_data$fund_isin)
fund_data <- normalise_fund_data(fund_data)
}
return(fund_data)
}
get_and_clean_fin_data <- function(fund_data) {
# Financial Data
fin_data_raw <- read_rda(paste0(analysis_inputs_path, "/security_financial_data.rda")) %>% as_tibble()
# remove unclear duplicates from raw financial data. This should be moved to DataStore.
rm_duplicates <- read_csv("non_distinct_isins.csv")
rm_duplicates <- rm_duplicates %>%
distinct(isin) %>%
pull(isin)
fin_data_raw <- fin_data_raw %>%
filter(!(isin %in% rm_duplicates))
if (!unique(fin_data_raw$financial_timestamp) == financial_timestamp) {
print("Financial timestamp not equal")
}
overrides <- read_csv("data/fin_sector_overrides.csv",
col_types = "ccdc"
)
sector_bridge <- read_csv("data/sector_bridge.csv", col_types = "cccccccc")
fin_data <- fin_data_raw
fin_data <- fin_data %>% filter(!is.na(isin))
fin_data <- map_security_sectors(fin_data, sector_bridge)
# Adds in the manual sector classification overrides
fin_data <- override_sector_classification(fin_data, overrides)
# Checks that only eq, cb, funds and others are in the fin_data
fin_data <- check_asset_types(fin_data)
# Checks for other mapped sectors not within the sector lists
fin_data <- check_fin_mapped_sectors(fin_data)
# TODO: find alternative here, calling in data from company financial data
# Cleans and normalises the mapped_to_assets flag
# fin_data <- check_mapped_assets_flag(fin_data)
# Limits the Bonds category to corporate bonds only
fin_data <- convert_corporate_bonds(fin_data)
# Checks whether the bond is sovereign or not
fin_data <- identify_sb(fin_data)
# Checks to ensure all finds are classified as such
fin_data <- classify_all_funds(fin_data)
fin_data <- add_bics_sector(fin_data)
# Select relevant columns
fin_data <- fin_data %>%
select(
company_id, company_name, bloomberg_id, corporate_bond_ticker,
country_of_domicile,
isin,
unit_share_price, exchange_rate_usd,
asset_type, security_type,
security_mapped_sector, security_icb_subsector, security_bics_subgroup, bics_sector, # bclass4,
maturity_date, coupon_value, amount_issued, current_shares_outstanding_all_classes, unit_share_price,
sector_override, sector_boe, subsector_boe, sector_dnb, sector_ipr, subsector_ipr,
is_sb
) %>%
distinct()
### TEST
if (nrow(fin_data) > nrow(fin_data_raw)) {
stop("Additional rows added to fin data")
}
return(fin_data)
}
add_bics_sector <- function(fin_data) {
bics_bridge <- read_csv("data/bics_bridge.csv")
fin_data <- left_join(fin_data, bics_bridge, by = c("security_bics_subgroup" = "bics_subgroup"))
}
get_and_clean_revenue_data <- function() {
revenue_data <- data.frame()
if (has_revenue) {
revenue_data <- read_rda(paste0(analysis_inputs_path, "/revenue_data_member_ticker.rda"))
# col_types = "dcdcclcd")
revenue_data <- revenue_data %>%
filter(tot_rev > 0) %>%
rename(revenue_sector = sector) %>%
ungroup()
}
return(revenue_data)
}
get_and_clean_company_fin_data <- function() {
comp_fin_data_raw <- read_rds(paste0(analysis_inputs_path, "/consolidated_financial_data.rda"))
comp_fin_data_raw <- comp_fin_data_raw %>% select(
company_id, company_name, bloomberg_id, country_of_domicile, corporate_bond_ticker, bics_subgroup, bics_sector,
icb_subgroup, financial_sector, has_asset_level_data, has_assets_in_matched_sector, sectors_with_assets, current_shares_outstanding_all_classes,
market_cap, bond_debt_out, financial_timestamp
)
sector_bridge <- read_csv("data/sector_bridge.csv", col_types = "cccccccc")