diff --git a/.lintr b/.lintr index a645424..1ff6b85 100644 --- a/.lintr +++ b/.lintr @@ -1,12 +1,7 @@ -linters: linters_with_defaults( - cyclocomp_linter = NULL, - line_length_linter = NULL, - indentation_linter = NULL, - object_usage_linter = NULL, - trailing_whitespace_linter = NULL, - object_length_linter = NULL, - assignment_linter = NULL, - commas_linter = NULL, - trailing_blank_lines_linter = NULL, - commented_code_linter = NULL +linters: all_linters( + object_usage_linter = NULL + ) +exclusions: list( + "inst/extdata/translation/", + "tests/testthat.R" ) diff --git a/DESCRIPTION b/DESCRIPTION index 772492d..be12d31 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: workflow.pacta.dashboard Title: Run PACTA dashboard JSON generation -Version: 0.0.0.9009 +Version: 0.0.0.9010 Authors@R: c(person(given = "Alex", family = "Axthelm", @@ -30,15 +30,19 @@ Imports: glue, jsonlite, logger, - magrittr, pacta.portfolio.utils, pacta.workflow.utils, readr, rlang, - stringr, tidyr, workflow.pacta Remotes: RMI-PACTA/pacta.portfolio.utils, RMI-PACTA/pacta.workflow.utils, RMI-PACTA/workflow.pacta +Suggests: + testthat (>= 3.0.0), + tibble +Config/testthat/edition: 3 +Depends: + R (>= 4.1.0) diff --git a/NAMESPACE b/NAMESPACE index b047321..de8e384 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -8,45 +8,11 @@ export(prep_key_bars_portfolio) export(prep_techmix_sector) export(prepare_schema_files) export(run_dashboard_workflow) -importFrom(dplyr,across) -importFrom(dplyr,all_of) -importFrom(dplyr,arrange) -importFrom(dplyr,bind_rows) -importFrom(dplyr,case_when) -importFrom(dplyr,desc) -importFrom(dplyr,distinct) -importFrom(dplyr,everything) -importFrom(dplyr,filter) -importFrom(dplyr,first) -importFrom(dplyr,group_by) -importFrom(dplyr,if_else) -importFrom(dplyr,inner_join) -importFrom(dplyr,join_by) -importFrom(dplyr,lag) -importFrom(dplyr,last) -importFrom(dplyr,left_join) -importFrom(dplyr,mutate) -importFrom(dplyr,mutate_at) -importFrom(dplyr,n) -importFrom(dplyr,pull) -importFrom(dplyr,reframe) -importFrom(dplyr,rename) -importFrom(dplyr,row_number) -importFrom(dplyr,select) -importFrom(dplyr,slice) -importFrom(dplyr,summarise) -importFrom(dplyr,tibble) -importFrom(dplyr,transmute) -importFrom(dplyr,ungroup) importFrom(logger,log_debug) importFrom(logger,log_error) importFrom(logger,log_info) importFrom(logger,log_trace) importFrom(logger,log_warn) -importFrom(magrittr,"%>%") importFrom(rlang,":=") importFrom(rlang,.data) importFrom(rlang,.env) -importFrom(tidyr,pivot_longer) -importFrom(tidyr,pivot_wider) -importFrom(tidyr,unite) diff --git a/R/build_dashboard.R b/R/build_dashboard.R index b9cf777..288f499 100644 --- a/R/build_dashboard.R +++ b/R/build_dashboard.R @@ -19,6 +19,7 @@ build_dashboard <- function( dashboard_skeleton_files_dir = dashboard_skeleton_files_dir, dashboard_output_dir = dashboard_output_dir ) + stopifnot(dashboard_copy_success) dashboard_output_data_dir <- file.path(dashboard_output_dir, "data") if (dashboard_data_dir != dashboard_output_data_dir) { @@ -31,6 +32,7 @@ build_dashboard <- function( to = dashboard_output_data_dir, recursive = TRUE ) + stopifnot(data_copy_success) } out <- list( diff --git a/R/choose_dictionary_language.R b/R/choose_dictionary_language.R index a5ee7c8..e476877 100644 --- a/R/choose_dictionary_language.R +++ b/R/choose_dictionary_language.R @@ -1,12 +1,14 @@ -choose_dictionary_language <- - function(data, language) { - language <- tolower(language) +choose_dictionary_language <- function( + data, + language +) { + language <- tolower(language) - data %>% - transmute( - .data$id_data, - .data$id_column, - translate_key = .data$key, - translate_value = .data[[language]] - ) - } + data |> + dplyr::transmute( + .data[["id_data"]], + .data[["id_column"]], + translate_key = .data[["key"]], + translate_value = .data[[language]] + ) +} diff --git a/R/filter_scenarios_per_sector.R b/R/filter_scenarios_per_sector.R index 2608c0c..229844d 100644 --- a/R/filter_scenarios_per_sector.R +++ b/R/filter_scenarios_per_sector.R @@ -1,12 +1,14 @@ -filter_scenarios_per_sector <- - function(data, select_scenario_other, select_scenario) { - special_sectors <- c("Aviation") - rest_of_sectors <- setdiff(unique(data$ald_sector), special_sectors) - - data %>% - filter( - scenarios_found_in_sectors(.data, select_scenario_other, c("Aviation")) | - scenarios_found_in_sectors(.data, select_scenario, rest_of_sectors) - ) - } +filter_scenarios_per_sector <- function( + data, + select_scenario_other, + select_scenario +) { + special_sectors <- "Aviation" + rest_of_sectors <- setdiff(unique(data[["ald_sector"]]), special_sectors) + data |> + dplyr::filter( + scenarios_found_in_sectors(.data, select_scenario_other, "Aviation") | + scenarios_found_in_sectors(.data, select_scenario, rest_of_sectors) + ) +} diff --git a/R/get_scenario.R b/R/get_scenario.R index be60d10..7fa5c81 100644 --- a/R/get_scenario.R +++ b/R/get_scenario.R @@ -1,4 +1,37 @@ -get_scenario <- function(scenario_parameter) { - scenario <- unlist(stringr::str_split(scenario_parameter,"_", n = 2))[2] - scenario +get_scenario <- function( + scenario_parameter +) { + scenario_name <- split_scenario_parameter( + scenario_parameter = scenario_parameter + )[["scenario_name"]] + return(scenario_name) +} + +get_scenario_source <- function( + scenario_parameter +) { + scenario_source <- split_scenario_parameter( + scenario_parameter = scenario_parameter + )[["scenario_source"]] + return(scenario_source) +} + +split_scenario_parameter <- function( + scenario_parameter +) { + split_parameter <- unlist( + strsplit( + x = scenario_parameter, + split = "_", + fixed = TRUE + ) + ) + scenario_source <- split_parameter[[1L]] + scenario_name <- paste(split_parameter[-1L], collapse = "_") + return( + list( + scenario_source = scenario_source, + scenario_name = scenario_name + ) + ) } diff --git a/R/get_scenario_source.R b/R/get_scenario_source.R deleted file mode 100644 index e153edd..0000000 --- a/R/get_scenario_source.R +++ /dev/null @@ -1,4 +0,0 @@ -get_scenario_source <- function(scenario_parameter) { - source <- unlist(stringr::str_split(scenario_parameter,"_", n = 2))[1] - source -} diff --git a/R/prep_audit_table.R b/R/prep_audit_table.R index 4bc2a18..c2aa4f9 100644 --- a/R/prep_audit_table.R +++ b/R/prep_audit_table.R @@ -1,127 +1,167 @@ -prep_audit_table <- - function(audit_file, investor_name, portfolio_name, currency_exchange_value) { - sort_order <- c( - "Bonds", - "Equity", - "Other", - "Unclassified" - ) +prep_audit_table <- function( + audit_file, + investor_name, + portfolio_name, + currency_exchange_value +) { - audit_table_init <- - audit_file %>% - filter( - .data$investor_name == .env$investor_name, - .data$portfolio_name == .env$portfolio_name - ) %>% - mutate(asset_type = if_else( - .data$valid_input, .data$asset_type, "Unknown" - )) %>% - mutate(is_included = if_else( - .data$asset_type %in% c("Others", "Funds"), FALSE, .data$valid_input - )) %>% - mutate(included = if_else(.data$is_included, "Yes", "No")) %>% - mutate(asset_type_analysis = case_when( - .data$asset_type %in% c("Bonds", "Equity") ~ .data$asset_type, - .data$asset_type == "Others" ~ "Other", - (.data$asset_type == "Funds") & (.data$direct_holding) ~ "Other", + audit_table_init <- audit_file |> + dplyr::filter( + .data[["investor_name"]] == .env[["investor_name"]], + .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::mutate( + asset_type = dplyr::if_else( + .data[["valid_input"]], .data[["asset_type"]], "Unknown" + ) + ) |> + dplyr::mutate( + is_included = dplyr::if_else( + .data[["asset_type"]] %in% c("Others", "Funds"), + FALSE, + .data[["valid_input"]] + ) + ) |> + dplyr::mutate( + included = dplyr::if_else( + .data[["is_included"]], + "Yes", + "No" + ) + ) |> + dplyr::mutate( + asset_type_analysis = dplyr::case_when( + .data[["asset_type"]] %in% c("Bonds", "Equity") ~ .data[["asset_type"]], + .data[["asset_type"]] == "Others" ~ "Other", + ( + (.data[["asset_type"]] == "Funds") & (.data[["direct_holding"]]) + ) ~ "Other", TRUE ~ "Unclassified" - )) %>% - mutate( - asset_type_analysis = - factor(.data$asset_type_analysis, levels = .env$sort_order) - ) %>% - mutate(value_usd = if_else(.data$value_usd < 0, 0, .data$value_usd)) %>% - mutate(value_usd = .data$value_usd / .env$currency_exchange_value) - - included_table_totals <- - audit_table_init %>% - group_by(.data$asset_type_analysis, .data$included) %>% - summarise( - total_value_invested = sum(.data$value_usd, na.rm = TRUE), - .groups = "drop" - ) %>% - mutate( - percentage_value_invested = - .data$total_value_invested / sum(.data$total_value_invested) ) - - included_table_value_breakdown <- - audit_table_init %>% - mutate(investment_means = case_when( - (.data$asset_type == "Funds") & (.data$direct_holding) ~ "Unidentified Funds", - .data$direct_holding ~ "Direct", - !.data$direct_holding ~ "Via a Fund" - )) %>% - group_by(.data$asset_type_analysis, .data$investment_means) %>% - summarise( - value_invested = sum(.data$value_usd, na.rm = TRUE), - .groups = "drop" + ) |> + dplyr::mutate( + asset_type_analysis = factor( + .data[["asset_type_analysis"]], + levels = c( + "Bonds", + "Equity", + "Other", + "Unclassified" + ) ) + ) |> + dplyr::mutate(value_usd = pmax(.data[["value_usd"]], 0L)) |> + dplyr::mutate( + value_usd = .data[["value_usd"]] / .env[["currency_exchange_value"]] + ) - fields_totals <- - c( - "asset_type_analysis", - "included", - "total_value_invested", - "percentage_value_invested" + included_table_totals <- audit_table_init |> + dplyr::group_by(.data[["asset_type_analysis"]], .data[["included"]]) |> + dplyr::summarise( + total_value_invested = sum(.data[["value_usd"]], na.rm = TRUE), + .groups = "drop" + ) |> + dplyr::mutate( + percentage_value_invested = ( + .data[["total_value_invested"]] / sum(.data[["total_value_invested"]]) ) + ) - included_table_per_asset <- - included_table_totals %>% - left_join(included_table_value_breakdown, by = "asset_type_analysis") %>% - remove_duplicate_entries_totals(fields_totals) %>% - select( - "asset_type_analysis", - "total_value_invested", - "percentage_value_invested", - "included", - "value_invested", - "investment_means" + included_table_value_breakdown <- audit_table_init |> + dplyr::mutate( + investment_means = dplyr::case_when( + ( + (.data[["asset_type"]] == "Funds") & (.data[["direct_holding"]]) + ) ~ "Unidentified Funds", + .data[["direct_holding"]] ~ "Direct", + !.data[["direct_holding"]] ~ "Via a Fund" ) + ) |> + dplyr::group_by( + .data[["asset_type_analysis"]], + .data[["investment_means"]] + ) |> + dplyr::summarise( + value_invested = sum(.data[["value_usd"]], na.rm = TRUE), + .groups = "drop" + ) - sum_table <- - included_table_per_asset %>% - summarise( - asset_type_analysis = "Total", - total_value_invested = sum(.data$total_value_invested, na.rm = TRUE), - percentage_value_invested = sum(.data$percentage_value_invested, na.rm = TRUE), - included = NA, - value_invested = sum(.data$value_invested, na.rm = TRUE), - investment_means = NA - ) + fields_totals <- c( + "asset_type_analysis", + "included", + "total_value_invested", + "percentage_value_invested" + ) - bind_rows(included_table_per_asset, sum_table) - } + included_table_per_asset <- included_table_totals |> + dplyr::left_join( + included_table_value_breakdown, + by = dplyr::join_by("asset_type_analysis") + ) |> + remove_dupe_entries_totals(fields_totals) |> + dplyr::select( + "asset_type_analysis", + "total_value_invested", + "percentage_value_invested", + "included", + "value_invested", + "investment_means" + ) + + sum_table <- included_table_per_asset |> + dplyr::summarise( + asset_type_analysis = "Total", + total_value_invested = sum(.data[["total_value_invested"]], na.rm = TRUE), + percentage_value_invested = sum( + .data[["percentage_value_invested"]], + na.rm = TRUE + ), + included = NA, + value_invested = sum(.data[["value_invested"]], na.rm = TRUE), + investment_means = NA + ) + dplyr::bind_rows(included_table_per_asset, sum_table) +} -equal_adjacent_fields_totals <- - function(table, fields_totals, idx) { - are_equal <- TRUE - for (field in fields_totals) { - are_equal <- are_equal && - (pull(slice(table, idx - 1), field) == pull(slice(table, idx), field)) - } - are_equal + +equal_adjacent_fields_totals <- function( + table, + fields_totals, + idx +) { + are_equal <- TRUE + for (field in fields_totals) { + are_equal <- are_equal && + ( + dplyr::pull(dplyr::slice(table, idx - 1L), field) == + dplyr::pull(dplyr::slice(table, idx), field) + ) } + are_equal +} -remove_duplicate_entries_totals <- - function(table, fields_totals) { - for (asset in unique(table$asset_type_analysis)) { - idx_asset <- - table %>% - mutate(is_chosen_asset = .data$asset_type_analysis == .env$asset) %>% - pull(.data$is_chosen_asset) %>% - which() +remove_dupe_entries_totals <- function( + table, + fields_totals +) { + for (asset in unique(table[["asset_type_analysis"]])) { + idx_asset <- table |> + dplyr::mutate( + is_chosen_asset = .data[["asset_type_analysis"]] == .env[["asset"]] + ) |> + dplyr::pull(.data[["is_chosen_asset"]]) |> + which() - if (length(idx_asset) >= 2) { - for (i in length(idx_asset):2) { - idx <- idx_asset[i] - if (equal_adjacent_fields_totals(table, fields_totals, idx)) { - table[idx, fields_totals] <- NA - } + if (length(idx_asset) >= 2L) { + for (i in length(idx_asset):2L) { + idx <- idx_asset[i] + if (equal_adjacent_fields_totals(table, fields_totals, idx)) { + table[idx, fields_totals] <- NA } } } - table } + table +} diff --git a/R/prep_company_bubble.R b/R/prep_company_bubble.R index bf9a0db..8fb3fdc 100644 --- a/R/prep_company_bubble.R +++ b/R/prep_company_bubble.R @@ -15,73 +15,136 @@ #' @return (data.frame) suitible for serialization to JSON (using #' `jsonlite::toJSON`/`jsonlite::write_json`) #' @export -prep_company_bubble <- - function(equity_results_company, - bonds_results_company, - portfolio_name, - start_year, - green_techs) { - - equity_data <- - equity_results_company %>% - filter(.data$portfolio_name == .env$portfolio_name) %>% - filter(.data$ald_sector %in% c("Power", "Automotive")) %>% - filter(.data$equity_market == "GlobalMarket") %>% - filter(.data$scenario_geography == "Global") %>% - filter(.data$year %in% c(.env$start_year, .env$start_year + 5)) %>% - mutate( - plan_buildout = last(.data$plan_tech_prod, order_by = .data$year) - first(.data$plan_tech_prod, order_by = .data$year), - scen_buildout = last(.data$scen_tech_prod, order_by = .data$year) - first(.data$scen_tech_prod, order_by = .data$year), - .by = c("company_name", "technology", "scenario_source", "scenario", "allocation") - ) %>% - filter(.data$year == .env$start_year) %>% - mutate(green = .data$technology %in% .env$green_techs) %>% - reframe( - plan_tech_share = sum(.data$plan_tech_share, na.rm = TRUE), - plan_buildout = sum(.data$plan_buildout, na.rm = TRUE), - scen_buildout = sum(.data$scen_buildout, na.rm = TRUE), - plan_carsten = sum(.data$plan_carsten, na.rm = TRUE), - port_weight = unique(.data$port_weight), - .by = c("company_name", "allocation", "scenario_source", - "scenario", "ald_sector", "green", "year") - ) %>% - mutate(y = .data$plan_buildout / .data$scen_buildout) %>% - filter(.data$green) %>% - select(-"plan_buildout", -"scen_buildout", -"green") %>% - filter(!is.na(.data$plan_tech_share)) %>% - mutate(y = pmax(.data$y, 0, na.rm = TRUE)) %>% - mutate(asset_class = "Listed Equity") - - bonds_data <- - bonds_results_company %>% - filter(.data$portfolio_name == .env$portfolio_name) %>% - filter(.data$ald_sector %in% c("Power", "Automotive")) %>% - filter(.data$equity_market == "GlobalMarket") %>% - filter(.data$scenario_geography == "Global") %>% - filter(.data$year %in% c(.env$start_year, .env$start_year + 5)) %>% - mutate( - plan_buildout = last(.data$plan_tech_prod, order_by = .data$year) - first(.data$plan_tech_prod, order_by = .data$year), - scen_buildout = last(.data$scen_tech_prod, order_by = .data$year) - first(.data$scen_tech_prod, order_by = .data$year), - .by = c("company_name", "technology", "scenario_source", "scenario", "allocation") - ) %>% - filter(.data$year == .env$start_year) %>% - mutate(green = .data$technology %in% .env$green_techs) %>% - reframe( - plan_tech_share = sum(.data$plan_tech_share, na.rm = TRUE), - plan_buildout = sum(.data$plan_buildout, na.rm = TRUE), - scen_buildout = sum(.data$scen_buildout, na.rm = TRUE), - plan_carsten = sum(.data$plan_carsten, na.rm = TRUE), - port_weight = unique(.data$port_weight), - .by = c("company_name", "allocation", "scenario_source", - "scenario", "ald_sector", "green", "year") - ) %>% - mutate(y = .data$plan_buildout / .data$scen_buildout) %>% - filter(.data$green) %>% - select(-"plan_buildout", -"scen_buildout", -"green") %>% - filter(!is.na(.data$plan_tech_share)) %>% - mutate(y = pmax(.data$y, 0, na.rm = TRUE)) %>% - mutate(asset_class = "Corporate Bonds") - - bind_rows(equity_data, bonds_data) - } +prep_company_bubble <- function( + equity_results_company, + bonds_results_company, + portfolio_name, + start_year, + green_techs +) { + equity_data <- equity_results_company |> + dplyr::filter(.data[["portfolio_name"]] == .env[["portfolio_name"]]) |> + dplyr::filter(.data[["ald_sector"]] %in% c("Power", "Automotive")) |> + dplyr::filter(.data[["equity_market"]] == "GlobalMarket") |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::filter( + .data[["year"]] %in% c( + .env[["start_year"]], + .env[["start_year"]] + 5L + ) + ) |> + dplyr::mutate( + plan_buildout = ( + dplyr::last( + .data[["plan_tech_prod"]], + order_by = .data[["year"]] + ) - dplyr::first( + .data[["plan_tech_prod"]], + order_by = .data[["year"]] + ) + ), + scen_buildout = ( + dplyr::last( + .data[["scen_tech_prod"]], + order_by = .data[["year"]] + ) - dplyr::first( + .data[["scen_tech_prod"]], + order_by = .data[["year"]] + ) + ), + .by = c( + "company_name", + "technology", + "scenario_source", + "scenario", + "allocation" + ) + ) |> + dplyr::filter(.data[["year"]] == .env[["start_year"]]) |> + dplyr::mutate(green = .data[["technology"]] %in% .env[["green_techs"]]) |> + dplyr::reframe( + plan_tech_share = sum(.data[["plan_tech_share"]], na.rm = TRUE), + plan_buildout = sum(.data[["plan_buildout"]], na.rm = TRUE), + scen_buildout = sum(.data[["scen_buildout"]], na.rm = TRUE), + plan_carsten = sum(.data[["plan_carsten"]], na.rm = TRUE), + port_weight = unique(.data[["port_weight"]]), + .by = c( + "company_name", + "allocation", + "scenario_source", + "scenario", + "ald_sector", + "green", + "year" + ) + ) |> + dplyr::mutate(y = .data[["plan_buildout"]] / .data[["scen_buildout"]]) |> + dplyr::filter(.data[["green"]]) |> + dplyr::select(-"plan_buildout", -"scen_buildout", -"green") |> + dplyr::filter(!is.na(.data[["plan_tech_share"]])) |> + dplyr::mutate(y = pmax(.data[["y"]], 0L, na.rm = TRUE)) |> + dplyr::mutate(asset_class = "Listed Equity") + bonds_data <- bonds_results_company |> + dplyr::filter(.data[["portfolio_name"]] == .env[["portfolio_name"]]) |> + dplyr::filter(.data[["ald_sector"]] %in% c("Power", "Automotive")) |> + dplyr::filter(.data[["equity_market"]] == "GlobalMarket") |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::filter( + .data[["year"]] %in% c( + .env[["start_year"]], + .env[["start_year"]] + 5L + ) + ) |> + dplyr::mutate( + plan_buildout = dplyr::last( + .data[["plan_tech_prod"]], + order_by = .data[["year"]] + ) - dplyr::first( + .data[["plan_tech_prod"]], + order_by = .data[["year"]] + ), + scen_buildout = ( + dplyr::last( + .data[["scen_tech_prod"]], + order_by = .data[["year"]] + ) - dplyr::first( + .data[["scen_tech_prod"]], + order_by = .data[["year"]] + ) + ), + .by = c( + "company_name", + "technology", + "scenario_source", + "scenario", + "allocation" + ) + ) |> + dplyr::filter(.data[["year"]] == .env[["start_year"]]) |> + dplyr::mutate(green = .data[["technology"]] %in% .env[["green_techs"]]) |> + dplyr::reframe( + plan_tech_share = sum(.data[["plan_tech_share"]], na.rm = TRUE), + plan_buildout = sum(.data[["plan_buildout"]], na.rm = TRUE), + scen_buildout = sum(.data[["scen_buildout"]], na.rm = TRUE), + plan_carsten = sum(.data[["plan_carsten"]], na.rm = TRUE), + port_weight = unique(.data[["port_weight"]]), + .by = c( + "company_name", + "allocation", + "scenario_source", + "scenario", + "ald_sector", + "green", + "year" + ) + ) |> + dplyr::mutate(y = .data[["plan_buildout"]] / .data[["scen_buildout"]]) |> + dplyr::filter(.data[["green"]]) |> + dplyr::select(-"plan_buildout", -"scen_buildout", -"green") |> + dplyr::filter(!is.na(.data[["plan_tech_share"]])) |> + dplyr::mutate(y = pmax(.data[["y"]], 0L, na.rm = TRUE)) |> + dplyr::mutate(asset_class = "Corporate Bonds") + + dplyr::bind_rows(equity_data, bonds_data) +} diff --git a/R/prep_emissions_pie.R b/R/prep_emissions_pie.R index 52b9c2b..043cd59 100644 --- a/R/prep_emissions_pie.R +++ b/R/prep_emissions_pie.R @@ -1,15 +1,29 @@ -prep_emissions_pie <- - function(data, asset_type, investor_name, portfolio_name, pacta_sectors) { - data %>% - ungroup() %>% - filter(.data$investor_name == .env$investor_name & - .data$portfolio_name == .env$portfolio_name) %>% - filter(.data$asset_type %in% c("Bonds", "Equity")) %>% - select("asset_type", "sector", "weighted_sector_emissions") %>% - mutate(exploded = .data$sector %in% .env$pacta_sectors) %>% - arrange(.data$asset_type, desc(.data$exploded), .data$sector) %>% - rename(key = .data$sector, value = .data$weighted_sector_emissions) %>% - filter(!is.na(.data$key)) %>% - filter(.data$asset_type == .env$asset_type) %>% - select(-"asset_type") - } +prep_emissions_pie <- function( + data, + asset_type, + investor_name, + portfolio_name, + pacta_sectors +) { + data |> + dplyr::ungroup() |> + dplyr::filter( + .data[["investor_name"]] == .env[["investor_name"]], + .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::filter(.data[["asset_type"]] %in% c("Bonds", "Equity")) |> + dplyr::select("asset_type", "sector", "weighted_sector_emissions") |> + dplyr::mutate(exploded = .data[["sector"]] %in% .env[["pacta_sectors"]]) |> + dplyr::arrange( + .data[["asset_type"]], + dplyr::desc(.data[["exploded"]]), + .data[["sector"]] + ) |> + dplyr::rename( + key = .data[["sector"]], + value = .data[["weighted_sector_emissions"]] + ) |> + dplyr::filter(!is.na(.data[["key"]])) |> + dplyr::filter(.data[["asset_type"]] == .env[["asset_type"]]) |> + dplyr::select(-"asset_type") +} diff --git a/R/prep_emissions_trajectory.R b/R/prep_emissions_trajectory.R index 713052c..8f5681a 100644 --- a/R/prep_emissions_trajectory.R +++ b/R/prep_emissions_trajectory.R @@ -1,53 +1,68 @@ -prep_emissions_trajectory <- - function(equity_results_portfolio, - bonds_results_portfolio, - portfolio_name, - pacta_sectors, - year_span, - start_year - ) { - emissions_units <- - c( - Automotive = "tons of CO\U00002082 per km per cars produced", - Aviation = "tons of CO\U00002082 per passenger km per active planes", - Cement = "tons of CO\U00002082 per tons of cement", - Coal = "tons of CO\U00002082 per tons of coal", - `Oil&Gas` = "tons of CO\U00002082 per GJ", - Power = "tons of CO\U00002082 per MWh", - Steel = "tons of CO\U00002082 per tons of steel" - ) +prep_emissions_trajectory <- function( + equity_results_portfolio, + bonds_results_portfolio, + portfolio_name, + pacta_sectors, + year_span, + start_year +) { + emissions_units <- c( + Automotive = "tons of CO\U00002082 per km per cars produced", + Aviation = "tons of CO\U00002082 per passenger km per active planes", + Cement = "tons of CO\U00002082 per tons of cement", + Coal = "tons of CO\U00002082 per tons of coal", + `Oil&Gas` = "tons of CO\U00002082 per GJ", + Power = "tons of CO\U00002082 per MWh", + Steel = "tons of CO\U00002082 per tons of steel" + ) - list(`Listed Equity` = equity_results_portfolio, - `Corporate Bonds` = bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$portfolio_name == .env$portfolio_name) %>% - filter(.data$scenario_geography == "Global") %>% - select( - "asset_class", - "allocation", - "equity_market", - sector = "ald_sector", - "year", - plan = "plan_sec_emissions_factor", - scen = "scen_sec_emissions_factor", - "scenario", - "scenario_source" - ) %>% - distinct() %>% - filter(!is.nan(.data$plan)) %>% - pivot_longer(c("plan", "scen"), names_to = "plan") %>% - unite("name", "sector", "plan", remove = FALSE) %>% - mutate(disabled = !.data$sector %in% .env$pacta_sectors) %>% - mutate(unit = .env$emissions_units[.data$sector]) %>% - group_by(.data$asset_class) %>% - filter(!all(.data$disabled)) %>% - mutate(equity_market = case_when( - .data$equity_market == "GlobalMarket" ~ "Global Market", - .data$equity_market == "DevelopedMarket" ~ "Developed Market", - .data$equity_market == "EmergingMarket" ~ "Emerging Market", - TRUE ~ .data$equity_market) - ) %>% - filter(.data$year <= .env$start_year + .env$year_span) %>% - arrange(.data$asset_class, factor(.data$equity_market, levels = c("Global Market", "Developed Market", "Emerging Market"))) %>% - ungroup() - } + list( + `Listed Equity` = equity_results_portfolio, + `Corporate Bonds` = bonds_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter(.data[["portfolio_name"]] == .env[["portfolio_name"]]) |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::select( + "asset_class", + "allocation", + "equity_market", + sector = "ald_sector", + "year", + plan = "plan_sec_emissions_factor", + scen = "scen_sec_emissions_factor", + "scenario", + "scenario_source" + ) |> + dplyr::distinct() |> + dplyr::filter(!is.nan(.data[["plan"]])) |> + tidyr::pivot_longer(c("plan", "scen"), names_to = "plan") |> + tidyr::unite("name", "sector", "plan", remove = FALSE) |> + dplyr::mutate(disabled = !.data[["sector"]] %in% .env[["pacta_sectors"]]) |> + dplyr::mutate(unit = .env[["emissions_units"]][.data[["sector"]]]) |> + dplyr::group_by(.data[["asset_class"]]) |> + dplyr::filter(!all(.data[["disabled"]])) |> + dplyr::mutate( + equity_market = dplyr::case_when( + .data[["equity_market"]] == "GlobalMarket" ~ "Global Market", + .data[["equity_market"]] == "DevelopedMarket" ~ "Developed Market", + .data[["equity_market"]] == "EmergingMarket" ~ "Emerging Market", + TRUE ~ .data[["equity_market"]] + ) + ) |> + dplyr::filter( + .data[["year"]] <= .env[["start_year"]] + .env[["year_span"]] + ) |> + dplyr::arrange( + .data[["asset_class"]], + factor( + .data[["equity_market"]], + levels = c( + "Global Market", + "Developed Market", + "Emerging Market" + ) + ) + ) |> + dplyr::ungroup() +} diff --git a/R/prep_exposure_pie.R b/R/prep_exposure_pie.R index 8522127..624256d 100644 --- a/R/prep_exposure_pie.R +++ b/R/prep_exposure_pie.R @@ -12,36 +12,52 @@ #' @return (data.frame) suitible for serialization to JSON (using #' `jsonlite::toJSON`/`jsonlite::write_json`) #' @export -prep_exposure_pie <- - function(data, - asset_type, - investor_name, - portfolio_name, - pacta_sectors, - currency_exchange_value) { - data %>% - filter(.data$investor_name == .env$investor_name & - .data$portfolio_name == .env$portfolio_name) %>% - filter(.data$asset_type %in% c("Bonds", "Equity")) %>% - filter(.data$valid_input == TRUE) %>% - mutate(across(c("bics_sector", "financial_sector"), as.character)) %>% - mutate( - sector = - if_else(!.data$financial_sector %in% .env$pacta_sectors, - "Other", - .data$financial_sector - ) - ) %>% - group_by(.data$asset_type, .data$sector) %>% - summarise( - value = sum(.data$value_usd, na.rm = TRUE) / .env$currency_exchange_value, - .groups = "drop" - ) %>% - mutate(exploded = .data$sector %in% .env$pacta_sectors) %>% - arrange(.data$asset_type, desc(.data$exploded), .data$sector) %>% - rename(key = .data$sector) %>% - filter(!is.na(.data$key)) %>% - ungroup() %>% - filter(.data$asset_type == .env$asset_type) %>% - select(-"asset_type") - } +prep_exposure_pie <- function( + data, + asset_type, + investor_name, + portfolio_name, + pacta_sectors, + currency_exchange_value +) { + data |> + dplyr::filter( + .data[["investor_name"]] == .env[["investor_name"]], + .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::filter(.data[["asset_type"]] %in% c("Bonds", "Equity")) |> + dplyr::filter(.data[["valid_input"]]) |> + dplyr::mutate( + dplyr::across(c("bics_sector", "financial_sector"), as.character) + ) |> + dplyr::mutate( + sector = dplyr::if_else( + .data[["financial_sector"]] %in% .env[["pacta_sectors"]], + .data[["financial_sector"]], + "Other" + ) + ) |> + dplyr::group_by(.data[["asset_type"]], .data[["sector"]]) |> + dplyr::summarise( + value = ( + sum( + .data[["value_usd"]], + na.rm = TRUE + ) / ( + .env[["currency_exchange_value"]] + ) + ), + .groups = "drop" + ) |> + dplyr::mutate(exploded = .data[["sector"]] %in% .env[["pacta_sectors"]]) |> + dplyr::arrange( + .data[["asset_type"]], + dplyr::desc(.data[["exploded"]]), + .data[["sector"]] + ) |> + dplyr::rename(key = .data[["sector"]]) |> + dplyr::filter(!is.na(.data[["key"]])) |> + dplyr::ungroup() |> + dplyr::filter(.data[["asset_type"]] == .env[["asset_type"]]) |> + dplyr::select(-"asset_type") +} diff --git a/R/prep_exposure_stats.R b/R/prep_exposure_stats.R index 5751e8a..d000cae 100644 --- a/R/prep_exposure_stats.R +++ b/R/prep_exposure_stats.R @@ -1,4 +1,4 @@ -#' Prepare exposure statistics for inclusion in the dashboard +#' Prepare exposure statistics for inclusion in the dashboard #' #' Prepare JSON data for the exposure statistics. #' @@ -11,68 +11,110 @@ #' @return (data.frame) suitible for serialization to JSON (using #' `jsonlite::toJSON`/`jsonlite::write_json`) #' @export -prep_exposure_stats <- function(audit_file, investor_name, portfolio_name, pacta_sectors, currency_exchange_value) { +prep_exposure_stats <- function( + audit_file, + investor_name, + portfolio_name, + pacta_sectors, + currency_exchange_value +) { pacta_asset_classes <- c("Bonds", "Equity") - + audit_table <- prep_audit_table( - audit_file, - investor_name = investor_name, - portfolio_name = portfolio_name, - currency_exchange_value = currency_exchange_value - ) - - exposure_stats <- audit_file %>% - filter( - .data$investor_name == .env$investor_name & - .data$portfolio_name == .env$portfolio_name) %>% - filter(.data$asset_type %in% pacta_asset_classes) %>% - filter(.data$valid_input == TRUE) %>% - mutate(across(c("bics_sector", "financial_sector"), as.character)) %>% - mutate( - sector = - if_else(!.data$financial_sector %in% .env$pacta_sectors, - "Other", - .data$financial_sector + audit_file, + investor_name = investor_name, + portfolio_name = portfolio_name, + currency_exchange_value = currency_exchange_value + ) + + exposure_stats <- audit_file |> + dplyr::filter( + .data[["investor_name"]] == .env[["investor_name"]], + .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::filter(.data[["asset_type"]] %in% pacta_asset_classes) |> + dplyr::filter(.data[["valid_input"]]) |> + dplyr::mutate( + dplyr::across(c("bics_sector", "financial_sector"), as.character) + ) |> + dplyr::mutate( + sector = dplyr::if_else( + .data[["financial_sector"]] %in% .env[["pacta_sectors"]], + .data[["financial_sector"]], + "Other" + ) + ) |> + dplyr::summarise( + value = ( + sum( + .data[["value_usd"]], + na.rm = TRUE + ) / ( + .env[["currency_exchange_value"]] ) - ) %>% - summarise( - value = sum(.data$value_usd, na.rm = TRUE) / .env$currency_exchange_value, + ), .by = c("asset_type", "sector") - ) %>% - mutate( - perc_asset_val_sector = .data$value / sum(.data$value, na.rm = TRUE), - .by = c("asset_type") - ) %>% - inner_join(audit_table, by = join_by("asset_type" == "asset_type_analysis")) %>% - select("asset_type", "percentage_value_invested", "sector", "perc_asset_val_sector") - - asset_classes_in_portfolio <- intersect(pacta_asset_classes, unique(exposure_stats$asset_type)) - - all_stats_with_zero_sector_exposure <- expand.grid( + ) |> + dplyr::mutate( + perc_asset_val_sector = ( + .data[["value"]] / sum(.data[["value"]], na.rm = TRUE) + ), + .by = "asset_type" + ) |> + dplyr::inner_join( + audit_table, + by = dplyr::join_by("asset_type" == "asset_type_analysis") + ) |> + dplyr::select( + "asset_type", + "percentage_value_invested", + "sector", + "perc_asset_val_sector" + ) + + asset_classes_in_portfolio <- intersect( + pacta_asset_classes, + unique(exposure_stats[["asset_type"]]) + ) + + all_stats_zero_sector_exposure <- expand.grid( asset_type = asset_classes_in_portfolio, sector = pacta_sectors, - val_sector = 0 - ) %>% inner_join( - distinct(select(exposure_stats, c("asset_type", "percentage_value_invested"))), - by = join_by("asset_type") - ) - - exposure_stats_all <- all_stats_with_zero_sector_exposure %>% - left_join(exposure_stats, by = join_by("asset_type", "sector", "percentage_value_invested")) %>% - mutate( - perc_asset_val_sector = if_else( - is.na(.data$perc_asset_val_sector), - .data$val_sector, - .data$perc_asset_val_sector + val_sector = 0L + ) |> dplyr::inner_join( + dplyr::distinct( + dplyr::select( + exposure_stats, + c("asset_type", "percentage_value_invested") + ) + ), + by = dplyr::join_by("asset_type") + ) + + exposure_stats_all <- all_stats_zero_sector_exposure |> + dplyr::left_join( + exposure_stats, + by = dplyr::join_by("asset_type", "sector", "percentage_value_invested") + ) |> + dplyr::mutate( + perc_asset_val_sector = dplyr::if_else( + is.na(.data[["perc_asset_val_sector"]]), + .data[["val_sector"]], + .data[["perc_asset_val_sector"]] ) - ) %>% - mutate( - asset_type = case_when( - .data$asset_type == "Bonds" ~ "Corporate Bonds", - .data$asset_type == "Equity" ~ "Listed Equity" + ) |> + dplyr::mutate( + asset_type = dplyr::case_when( + .data[["asset_type"]] == "Bonds" ~ "Corporate Bonds", + .data[["asset_type"]] == "Equity" ~ "Listed Equity" ) - ) %>% - select("asset_type", "percentage_value_invested", "sector", "perc_asset_val_sector") - + ) |> + dplyr::select( + "asset_type", + "percentage_value_invested", + "sector", + "perc_asset_val_sector" + ) + exposure_stats_all } diff --git a/R/prep_key_bars_company.R b/R/prep_key_bars_company.R index bb18d31..b85e143 100644 --- a/R/prep_key_bars_company.R +++ b/R/prep_key_bars_company.R @@ -17,62 +17,92 @@ #' @return (data.frame) suitible for serialization to JSON (using #' `jsonlite::toJSON`/`jsonlite::write_json`) #' @export -prep_key_bars_company <- - function(equity_results_company, - bonds_results_company, - portfolio_name, - start_year, - pacta_sectors_not_analysed, - all_tech_levels) { - - equity_data_company <- - equity_results_company %>% - filter(.data$portfolio_name == .env$portfolio_name) %>% - filter(.data$year %in% c(.env$start_year + 5)) %>% - filter(.data$equity_market %in% c("Global", "GlobalMarket")) %>% - filter(.data$scenario_geography == "Global") %>% - filter(.data$ald_sector %in% c("Power", "Automotive")) %>% - select(-"id") %>% - rename(id = "company_name") %>% - select("id", "ald_sector", "technology", "plan_tech_share", "port_weight", - "allocation", "scenario_source", "scenario", "year") %>% - arrange(desc(.data$port_weight)) %>% - mutate(asset_class = "Listed Equity") %>% - mutate_at("id", as.character) %>% # convert the col type to character to prevent errors in case empty df is binded by rows - group_by(.data$ald_sector, .data$technology) %>% # select at most 15 companies with the highest weigths per sector+technology - arrange(dplyr::desc(.data$port_weight), .by_group = TRUE) %>% - slice(1:15) %>% - filter(!is.null(.data$port_weight)) %>% - filter(!is.null(.data$plan_tech_share)) - - bonds_data_company <- - bonds_results_company %>% - filter(.data$portfolio_name == .env$portfolio_name) %>% - filter(.data$year %in% c(.env$start_year + 5)) %>% - filter(.data$equity_market %in% c("Global", "GlobalMarket")) %>% - filter(.data$scenario_geography == "Global") %>% - filter(.data$ald_sector %in% c("Power", "Automotive")) %>% - select(-"id") %>% - rename(id = "company_name") %>% - select("id", "ald_sector", "technology", "plan_tech_share", "port_weight", - "allocation", "scenario_source", "scenario", "year") %>% - group_by(.data$id, .data$ald_sector, .data$technology) %>% - mutate(port_weight = sum(.data$port_weight, na.rm = TRUE)) %>% - group_by(.data$id, .data$technology) %>% - filter(row_number() == 1) %>% - filter(!.data$ald_sector %in% .env$pacta_sectors_not_analysed | !grepl("Aligned", .data$id)) %>% - arrange(desc(.data$port_weight)) %>% - mutate(asset_class = "Corporate Bonds") %>% - mutate_at("id", as.character) %>% # convert the col type to character to prevent errors in case empty df is bound by rows - group_by(.data$ald_sector, .data$technology) %>% # select at most 15 companies with the highest weigths per sector+technology - arrange(.data$port_weight, .by_group = TRUE) %>% - slice(1:15) %>% - group_by(.data$ald_sector) %>% - arrange(factor(.data$technology, levels = .env$all_tech_levels)) %>% - arrange(dplyr::desc(.data$port_weight), .by_group = TRUE) %>% - filter(!is.null(.data$port_weight)) %>% - filter(!is.null(.data$plan_tech_share)) - - bind_rows(equity_data_company, bonds_data_company) - } +prep_key_bars_company <- function( + equity_results_company, + bonds_results_company, + portfolio_name, + start_year, + pacta_sectors_not_analysed, + all_tech_levels +) { + equity_data_company <- equity_results_company |> + dplyr::filter(.data[["portfolio_name"]] == .env[["portfolio_name"]]) |> + dplyr::filter(.data[["year"]] %in% c(.env[["start_year"]] + 5L)) |> + dplyr::filter(.data[["equity_market"]] %in% c("Global", "GlobalMarket")) |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::filter(.data[["ald_sector"]] %in% c("Power", "Automotive")) |> + dplyr::select(-"id") |> + dplyr::rename(id = "company_name") |> + dplyr::select( + "id", + "ald_sector", + "technology", + "plan_tech_share", + "port_weight", + "allocation", + "scenario_source", + "scenario", + "year" + ) |> + dplyr::arrange(dplyr::desc(.data[["port_weight"]])) |> + dplyr::mutate(asset_class = "Listed Equity") |> + dplyr::mutate_at("id", as.character) |> # convert the col type to character to prevent errors in case empty df is binded by rows #nolint + dplyr::group_by(.data[["ald_sector"]], .data[["technology"]]) |> # select at most 15 companies with the highest weigths per sector+technology #nolint + dplyr::arrange(dplyr::desc(.data[["port_weight"]]), .by_group = TRUE) |> + dplyr::slice(1L:15L) |> + dplyr::filter(!is.null(.data[["port_weight"]])) |> + dplyr::filter(!is.null(.data[["plan_tech_share"]])) + + bonds_data_company <- bonds_results_company |> + dplyr::filter(.data[["portfolio_name"]] == .env[["portfolio_name"]]) |> + dplyr::filter(.data[["year"]] %in% c(.env[["start_year"]] + 5L)) |> + dplyr::filter(.data[["equity_market"]] %in% c("Global", "GlobalMarket")) |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::filter(.data[["ald_sector"]] %in% c("Power", "Automotive")) |> + dplyr::select(-"id") |> + dplyr::rename(id = "company_name") |> + dplyr::select( + "id", + "ald_sector", + "technology", + "plan_tech_share", + "port_weight", + "allocation", + "scenario_source", + "scenario", + "year" + ) |> + dplyr::group_by( + .data[["id"]], .data[["ald_sector"]], .data[["technology"]] + ) |> + dplyr::mutate(port_weight = sum(.data[["port_weight"]], na.rm = TRUE)) |> + dplyr::group_by(.data[["id"]], .data[["technology"]]) |> + dplyr::filter(dplyr::row_number() == 1L) |> + dplyr::filter( + !(.data[["ald_sector"]] %in% .env[["pacta_sectors_not_analysed"]]) | + !grepl( + pattern = "Aligned", + x = .data[["id"]], + fixed = TRUE + ) + ) |> + dplyr::arrange(dplyr::desc(.data[["port_weight"]])) |> + dplyr::mutate(asset_class = "Corporate Bonds") |> + dplyr::mutate_at("id", as.character) |> # convert the col type to character to prevent errors in case empty df is bound by rows #nolint + dplyr::group_by(.data[["ald_sector"]], .data[["technology"]]) |> # select at most 15 companies with the highest weigths per sector+technology #nolint + dplyr::arrange(.data[["port_weight"]], .by_group = TRUE) |> + dplyr::slice(1L:15L) |> + dplyr::group_by(.data[["ald_sector"]]) |> + dplyr::arrange( + factor( + .data[["technology"]], + levels = .env[["all_tech_levels"]] + ) + ) |> + dplyr::arrange(dplyr::desc(.data[["port_weight"]]), .by_group = TRUE) |> + dplyr::filter(!is.null(.data[["port_weight"]])) |> + dplyr::filter(!is.null(.data[["plan_tech_share"]])) + + dplyr::bind_rows(equity_data_company, bonds_data_company) +} diff --git a/R/prep_key_bars_portfolio.R b/R/prep_key_bars_portfolio.R index 5cabdf0..8eba515 100644 --- a/R/prep_key_bars_portfolio.R +++ b/R/prep_key_bars_portfolio.R @@ -1,7 +1,3 @@ -# prep_key_bars_portfolio ------------------------------------------------------ -# based on pacta.portfolio.report:::prep_key_bars_portfolio, but does not filter -# to allocation == "portfolio_weight" nor by scenario and scenario source - #' Prepare data for portfolio-level technology exposoure plot #' #' Prepare JSON data for the portfolio-level technology exposoure plot. @@ -21,51 +17,115 @@ #' @return (data.frame) suitible for serialization to JSON (using #' `jsonlite::toJSON`/`jsonlite::write_json`) #' @export -prep_key_bars_portfolio <- - function(equity_results_portfolio, - bonds_results_portfolio, - portfolio_name, - start_year, - pacta_sectors_not_analysed, - all_tech_levels) { - equity_data_portfolio <- - equity_results_portfolio %>% - filter(.data$portfolio_name == .env$portfolio_name) %>% - filter(.data$equity_market %in% c("Global", "GlobalMarket")) %>% - filter(.data$year %in% c(.env$start_year + 5)) %>% - filter(.data$ald_sector %in% c("Power", "Automotive")) %>% - filter(.data$scenario_geography == "Global") %>% - mutate(port_weight = 1) %>% - select("ald_sector", "technology", "plan_tech_share", "scen_tech_share", - "port_weight", "scenario", "scenario_source", "allocation", "year") %>% - pivot_longer(c("plan_tech_share", "scen_tech_share"), names_to = "plan") %>% - mutate(id = if_else(.data$plan == "plan_tech_share", "Portfolio", "Aligned* Portfolio")) %>% - rename(plan_tech_share = "value") %>% - select("id", "ald_sector", "technology", "plan_tech_share", "port_weight", - "scenario", "scenario_source", "allocation", "year") %>% - filter(!.data$ald_sector %in% .env$pacta_sectors_not_analysed | !grepl("Aligned", .data$id)) %>% - mutate(asset_class = "Listed Equity") %>% - mutate_at("id", as.character) # convert the col type to character to prevent errors in case empty df is bound by rows - - bonds_data_portfolio <- - bonds_results_portfolio %>% - filter(.data$portfolio_name == .env$portfolio_name) %>% - filter(.data$equity_market %in% c("Global", "GlobalMarket")) %>% - filter(.data$year %in% c(.env$start_year + 5)) %>% - filter(.data$ald_sector %in% c("Power", "Automotive")) %>% - filter(.data$scenario_geography == "Global") %>% - mutate(port_weight = 1) %>% - select("ald_sector", "technology", "plan_tech_share", "scen_tech_share", - "port_weight", "scenario", "scenario_source", "allocation", "year") %>% - pivot_longer(c("plan_tech_share", "scen_tech_share"), names_to = "plan") %>% - mutate(id = if_else(.data$plan == "plan_tech_share", "Portfolio", "Aligned* Portfolio")) %>% - rename(plan_tech_share = "value") %>% - select("id", "ald_sector", "technology", "plan_tech_share", "port_weight", - "scenario", "scenario_source", "allocation", "year") %>% - mutate(asset_class = "Corporate Bonds") %>% - mutate_at("id", as.character) %>% - arrange(factor(.data$technology, levels = .env$all_tech_levels)) - - bind_rows(equity_data_portfolio, bonds_data_portfolio) - } +prep_key_bars_portfolio <- function( + equity_results_portfolio, + bonds_results_portfolio, + portfolio_name, + start_year, + pacta_sectors_not_analysed, + all_tech_levels +) { + equity_data_portfolio <- equity_results_portfolio |> + dplyr::filter(.data[["portfolio_name"]] == .env[["portfolio_name"]]) |> + dplyr::filter(.data[["equity_market"]] %in% c("Global", "GlobalMarket")) |> + dplyr::filter(.data[["year"]] %in% c(.env[["start_year"]] + 5L)) |> + dplyr::filter(.data[["ald_sector"]] %in% c("Power", "Automotive")) |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::mutate(port_weight = 1L) |> + dplyr::select( + "ald_sector", + "technology", + "plan_tech_share", + "scen_tech_share", + "port_weight", + "scenario", + "scenario_source", + "allocation", + "year" + ) |> + tidyr::pivot_longer( + c("plan_tech_share", "scen_tech_share"), + names_to = "plan" + ) |> + dplyr::mutate( + id = dplyr::if_else( + .data[["plan"]] == "plan_tech_share", + "Portfolio", + "Aligned* Portfolio" + ) + ) |> + dplyr::rename(plan_tech_share = "value") |> + dplyr::select( + "id", + "ald_sector", + "technology", + "plan_tech_share", + "port_weight", + "scenario", + "scenario_source", + "allocation", + "year" + ) |> + dplyr::filter( + !(.data[["ald_sector"]] %in% .env[["pacta_sectors_not_analysed"]]) | + !grepl( + pattern = "Aligned", + x = .data[["id"]], + fixed = TRUE + ) + ) |> + dplyr::mutate(asset_class = "Listed Equity") |> + dplyr::mutate_at("id", as.character) # convert the col type to character to prevent errors in case empty df is bound by rows # nolint + + bonds_data_portfolio <- bonds_results_portfolio |> + dplyr::filter(.data[["portfolio_name"]] == .env[["portfolio_name"]]) |> + dplyr::filter(.data[["equity_market"]] %in% c("Global", "GlobalMarket")) |> + dplyr::filter(.data[["year"]] %in% c(.env[["start_year"]] + 5L)) |> + dplyr::filter(.data[["ald_sector"]] %in% c("Power", "Automotive")) |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::mutate(port_weight = 1L) |> + dplyr::select( + "ald_sector", + "technology", + "plan_tech_share", + "scen_tech_share", + "port_weight", + "scenario", + "scenario_source", + "allocation", + "year" + ) |> + tidyr::pivot_longer( + c("plan_tech_share", "scen_tech_share"), + names_to = "plan" + ) |> + dplyr::mutate( + id = dplyr::if_else( + .data[["plan"]] == "plan_tech_share", + "Portfolio", + "Aligned* Portfolio" + ) + ) |> + dplyr::rename(plan_tech_share = "value") |> + dplyr::select( + "id", + "ald_sector", + "technology", + "plan_tech_share", + "port_weight", + "scenario", + "scenario_source", + "allocation", + "year" + ) |> + dplyr::mutate(asset_class = "Corporate Bonds") |> + dplyr::mutate_at("id", as.character) |> + dplyr::arrange( + factor( + .data[["technology"]], + levels = .env[["all_tech_levels"]] + ) + ) + dplyr::bind_rows(equity_data_portfolio, bonds_data_portfolio) +} diff --git a/R/prep_techexposure.R b/R/prep_techexposure.R index 37d2f34..43eaa0e 100644 --- a/R/prep_techexposure.R +++ b/R/prep_techexposure.R @@ -1,97 +1,156 @@ -prep_techexposure <- - function( - equity_results_portfolio, - bonds_results_portfolio, - investor_name, - portfolio_name, - indices_equity_results_portfolio, - indices_bonds_results_portfolio, - peers_equity_results_portfolio, - peers_bonds_results_portfolio, - peer_group, - select_scenario_other, - select_scenario, - start_year, - green_techs, - equity_market_levels, - all_tech_levels - ) { - portfolio <- - list(`Listed Equity` = equity_results_portfolio, - `Corporate Bonds` = bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$investor_name == .env$investor_name, - .data$portfolio_name == .env$portfolio_name) %>% - filter(!is.na(.data$ald_sector)) +prep_techexposure <- function( + equity_results_portfolio, + bonds_results_portfolio, + investor_name, + portfolio_name, + indices_eq_results_portfolio, + indices_cb_results_portfolio, + peers_equity_results_portfolio, + peers_bonds_results_portfolio, + peer_group, + select_scenario_other, + select_scenario, + start_year, + green_techs, + equity_market_levels, + all_tech_levels +) { + portfolio <- list( + `Listed Equity` = equity_results_portfolio, + `Corporate Bonds` = bonds_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter( + .data[["investor_name"]] == .env[["investor_name"]], + .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::filter(!is.na(.data[["ald_sector"]])) - asset_classes <- - portfolio %>% - pull("asset_class") %>% - unique() + asset_classes <- portfolio |> + dplyr::pull("asset_class") |> + unique() - equity_sectors <- - portfolio %>% - filter(.data$asset_class == "Listed Equity") %>% - pull("ald_sector") %>% - unique() + equity_sectors <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Listed Equity") |> + dplyr::pull("ald_sector") |> + unique() - bonds_sectors <- - portfolio %>% - filter(.data$asset_class == "Corporate Bonds") %>% - pull("ald_sector") %>% - unique() + bonds_sectors <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Corporate Bonds") |> + dplyr::pull("ald_sector") |> + unique() - indices <- - list(`Listed Equity` = indices_equity_results_portfolio, - `Corporate Bonds` = indices_bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$asset_class %in% .env$asset_classes) %>% - filter(.data$asset_class == "Listed Equity" & .data$ald_sector %in% .env$equity_sectors | - .data$asset_class == "Corporate Bonds" & .data$ald_sector %in% .env$bonds_sectors) + indices <- list( + `Listed Equity` = indices_eq_results_portfolio, + `Corporate Bonds` = indices_cb_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter(.data[["asset_class"]] %in% .env[["asset_classes"]]) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["ald_sector"]] %in% .env[["equity_sectors"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["ald_sector"]] %in% .env[["bonds_sectors"]] + ) + ) - peers <- - list(`Listed Equity` = peers_equity_results_portfolio, - `Corporate Bonds` = peers_bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$asset_class %in% .env$asset_classes) %>% - filter(.data$asset_class == "Listed Equity" & .data$ald_sector %in% .env$equity_sectors | - .data$asset_class == "Corporate Bonds" & .data$ald_sector %in% .env$bonds_sectors) %>% - filter(.data$investor_name == .env$peer_group) + peers <- list( + `Listed Equity` = peers_equity_results_portfolio, + `Corporate Bonds` = peers_bonds_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter(.data[["asset_class"]] %in% .env[["asset_classes"]]) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["ald_sector"]] %in% .env[["equity_sectors"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["ald_sector"]] %in% .env[["bonds_sectors"]] + ) + ) |> + dplyr::filter(.data[["investor_name"]] == .env[["peer_group"]]) - bind_rows(portfolio, peers, indices) %>% - filter(.data$allocation == "portfolio_weight") %>% - filter_scenarios_per_sector( - select_scenario_other, - select_scenario - ) %>% - filter(.data$scenario_geography == "Global") %>% - filter(.data$year == .env$start_year) %>% - filter(.data$equity_market == "GlobalMarket") %>% - mutate(green = .data$technology %in% .env$green_techs) %>% - group_by(.data$asset_class, .data$equity_market, .data$portfolio_name, .data$ald_sector) %>% - arrange(.data$asset_class, .data$portfolio_name, - factor(.data$technology, levels = all_tech_levels), desc(.data$green)) %>% - mutate(sector_sum = sum(.data$plan_carsten)) %>% - mutate(sector_prcnt = .data$plan_carsten / sum(.data$plan_carsten)) %>% - mutate(sector_cumprcnt = cumsum(.data$sector_prcnt)) %>% - mutate(sector_cumprcnt = lag(.data$sector_cumprcnt, default = 0)) %>% - mutate(cumsum = cumsum(.data$plan_carsten)) %>% - mutate(cumsum = lag(.data$cumsum, default = 0)) %>% - ungroup() %>% - group_by(.data$asset_class, .data$equity_market, .data$portfolio_name, .data$ald_sector, .data$green) %>% - mutate(green_sum = sum(.data$plan_carsten)) %>% - mutate(green_prcnt = sum(.data$plan_carsten) / .data$sector_sum) %>% - ungroup() %>% - mutate(this_portfolio = .data$portfolio_name == .env$portfolio_name) %>% - mutate(equity_market = case_when( - .data$equity_market == "GlobalMarket" ~ "Global Market", - .data$equity_market == "DevelopedMarket" ~ "Developed Market", - .data$equity_market == "EmergingMarket" ~ "Emerging Market", - TRUE ~ .data$equity_market) - ) %>% - arrange(.data$asset_class, factor(.data$equity_market, levels = equity_market_levels), desc(.data$this_portfolio), .data$portfolio_name, - factor(.data$technology, levels = all_tech_levels), desc(.data$green)) %>% - select("asset_class", "equity_market", "portfolio_name", "this_portfolio", "ald_sector", "technology", - "plan_carsten", "sector_sum", "sector_prcnt", "cumsum", "sector_cumprcnt", - "green", "green_sum", "green_prcnt") - } + dplyr::bind_rows(portfolio, peers, indices) |> + dplyr::filter(.data[["allocation"]] == "portfolio_weight") |> + filter_scenarios_per_sector( + select_scenario_other, + select_scenario + ) |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::filter(.data[["year"]] == .env[["start_year"]]) |> + dplyr::filter(.data[["equity_market"]] == "GlobalMarket") |> + dplyr::mutate(green = .data[["technology"]] %in% .env[["green_techs"]]) |> + dplyr::group_by( + .data[["asset_class"]], + .data[["equity_market"]], + .data[["portfolio_name"]], + .data[["ald_sector"]] + ) |> + dplyr::arrange( + .data[["asset_class"]], + .data[["portfolio_name"]], + factor(.data[["technology"]], levels = all_tech_levels), + dplyr::desc(.data[["green"]]) + ) |> + dplyr::mutate(sector_sum = sum(.data[["plan_carsten"]])) |> + dplyr::mutate( + sector_prcnt = .data[["plan_carsten"]] / sum(.data[["plan_carsten"]]) + ) |> + dplyr::mutate(sector_cumprcnt = cumsum(.data[["sector_prcnt"]])) |> + dplyr::mutate( + sector_cumprcnt = dplyr::lag(.data[["sector_cumprcnt"]], default = 0L) + ) |> + dplyr::mutate(cumsum = cumsum(.data[["plan_carsten"]])) |> + dplyr::mutate(cumsum = dplyr::lag(.data[["cumsum"]], default = 0L)) |> + dplyr::ungroup() |> + dplyr::group_by( + .data[["asset_class"]], + .data[["equity_market"]], + .data[["portfolio_name"]], + .data[["ald_sector"]], + .data[["green"]] + ) |> + dplyr::mutate(green_sum = sum(.data[["plan_carsten"]])) |> + dplyr::mutate( + green_prcnt = sum(.data[["plan_carsten"]]) / .data[["sector_sum"]] + ) |> + dplyr::ungroup() |> + dplyr::mutate( + this_portfolio = .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::mutate( + equity_market = dplyr::case_when( + .data[["equity_market"]] == "GlobalMarket" ~ "Global Market", + .data[["equity_market"]] == "DevelopedMarket" ~ "Developed Market", + .data[["equity_market"]] == "EmergingMarket" ~ "Emerging Market", + TRUE ~ .data[["equity_market"]] + ) + ) |> + dplyr::arrange( + .data[["asset_class"]], + factor(.data[["equity_market"]], levels = equity_market_levels), + dplyr::desc(.data[["this_portfolio"]]), + .data[["portfolio_name"]], + factor(.data[["technology"]], levels = all_tech_levels), + dplyr::desc(.data[["green"]]) + ) |> + dplyr::select( + "asset_class", + "equity_market", + "portfolio_name", + "this_portfolio", + "ald_sector", + "technology", + "plan_carsten", + "sector_sum", + "sector_prcnt", + "cumsum", + "sector_cumprcnt", + "green", + "green_sum", + "green_prcnt" + ) +} diff --git a/R/prep_techmix_sector.R b/R/prep_techmix_sector.R index ac46992..6b8eb4e 100644 --- a/R/prep_techmix_sector.R +++ b/R/prep_techmix_sector.R @@ -1,4 +1,4 @@ -#' Prepare techmix data for plot +#' Prepare techmix data for plot #' #' Prepare JSON data for the technology mix plot. #' @@ -6,9 +6,9 @@ #' `workflow.pacta` for listed equity #' @param bonds_results_portfolio (data.frame) Portfolio-level results from #' `workflow.pacta` for corporate bonds -#' @param indices_equity_results_portfolio (data.frame) Benchmark results from +#' @param indices_eq_results_portfolio (data.frame) Benchmark results from #' `workflow.pacta` for listed equity -#' @param indices_bonds_results_portfolio (data.frame) Benchmark results from +#' @param indices_cb_results_portfolio (data.frame) Benchmark results from #' `workflow.pacta` for corporate bonds #' @param peers_equity_results_portfolio (data.frame) Peer group results from #' `workflow.pacta` for listed equity @@ -25,134 +25,245 @@ #' @return (data.frame) suitible for serialization to JSON (using #' `jsonlite::toJSON`/`jsonlite::write_json`) #' @export -prep_techmix_sector <- - function(equity_results_portfolio, - bonds_results_portfolio, - indices_equity_results_portfolio, - indices_bonds_results_portfolio, - peers_equity_results_portfolio, - peers_bonds_results_portfolio, - investor_name, - portfolio_name, - start_year, - year_span, - peer_group, - green_techs, - all_tech_levels - ) { +prep_techmix_sector <- function( + equity_results_portfolio, + bonds_results_portfolio, + indices_eq_results_portfolio, + indices_cb_results_portfolio, + peers_equity_results_portfolio, + peers_bonds_results_portfolio, + investor_name, + portfolio_name, + start_year, + year_span, + peer_group, + green_techs, + all_tech_levels +) { - portfolio <- - list(`Listed Equity` = equity_results_portfolio, - `Corporate Bonds` = bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$investor_name == .env$investor_name, - .data$portfolio_name == .env$portfolio_name) %>% - filter(!is.na(.data$ald_sector)) + portfolio <- list( + `Listed Equity` = equity_results_portfolio, + `Corporate Bonds` = bonds_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter( + .data[["investor_name"]] == .env[["investor_name"]], + .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::filter(!is.na(.data[["ald_sector"]])) -asset_classes <- - portfolio %>% - pull("asset_class") %>% - unique() + asset_classes <- portfolio |> + dplyr::pull("asset_class") |> + unique() -equity_sectors <- - portfolio %>% - filter(.data$asset_class == "Listed Equity") %>% - filter(.data$allocation == "portfolio_weight") %>% - pull("ald_sector") %>% - unique() + equity_sectors <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Listed Equity") |> + dplyr::filter(.data[["allocation"]] == "portfolio_weight") |> + dplyr::pull("ald_sector") |> + unique() -bonds_sectors <- - portfolio %>% - filter(.data$asset_class == "Corporate Bonds") %>% - pull("ald_sector") %>% - unique() + bonds_sectors <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Corporate Bonds") |> + dplyr::pull("ald_sector") |> + unique() -indices <- - list(`Listed Equity` = indices_equity_results_portfolio, - `Corporate Bonds` = indices_bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$asset_class %in% .env$asset_classes) %>% - filter(.data$asset_class == "Listed Equity" & .data$ald_sector %in% .env$equity_sectors | - .data$asset_class == "Corporate Bonds" & .data$ald_sector %in% .env$bonds_sectors) - -peers <- - list(`Listed Equity` = peers_equity_results_portfolio, - `Corporate Bonds` = peers_bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$asset_class %in% .env$asset_classes) %>% - filter(.data$asset_class == "Listed Equity" & .data$ald_sector %in% .env$equity_sectors | - .data$asset_class == "Corporate Bonds" & .data$ald_sector %in% .env$bonds_sectors) %>% - filter(.data$investor_name == .env$peer_group) + indices <- list( + `Listed Equity` = indices_eq_results_portfolio, + `Corporate Bonds` = indices_cb_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter(.data[["asset_class"]] %in% .env[["asset_classes"]]) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["ald_sector"]] %in% .env[["equity_sectors"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["ald_sector"]] %in% .env[["bonds_sectors"]] + ) + ) -techexposure_data <- - bind_rows(portfolio, peers, indices) %>% - filter(.data$allocation == "portfolio_weight") %>% - filter(.data$scenario_geography == "Global") %>% - filter(.data$year %in% c(.env$start_year, .env$start_year + .env$year_span)) + peers <- list( + `Listed Equity` = peers_equity_results_portfolio, + `Corporate Bonds` = peers_bonds_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter(.data[["asset_class"]] %in% .env[["asset_classes"]]) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["ald_sector"]] %in% .env[["equity_sectors"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["ald_sector"]] %in% .env[["bonds_sectors"]] + ) + ) |> + dplyr::filter(.data[["investor_name"]] == .env[["peer_group"]]) -if (nrow(techexposure_data) > 0) { - techexposure_data <- - techexposure_data %>% - mutate(green = .data$technology %in% .env$green_techs) %>% - group_by(.data$asset_class, .data$equity_market, .data$portfolio_name, - .data$ald_sector, .data$scenario, .data$year) %>% - mutate(plan_alloc_wt_sec_prod = sum(.data$plan_alloc_wt_tech_prod), - scen_alloc_wt_sec_prod = sum(.data$scen_alloc_wt_tech_prod)) %>% - mutate(production_plan = if_else(.data$plan_alloc_wt_tech_prod > 0, .data$plan_alloc_wt_tech_prod / .data$plan_alloc_wt_sec_prod, 0), - scenario_plan = if_else(.data$scen_alloc_wt_tech_prod > 0, .data$scen_alloc_wt_tech_prod / .data$scen_alloc_wt_sec_prod, 0)) %>% - group_by(.data$asset_class, .data$equity_market, .data$portfolio_name, - .data$ald_sector, .data$scenario, .data$year, .data$green) %>% - mutate(green_sum_prod = sum(.data$production_plan), - green_sum_scenario = sum(.data$scenario_plan)) %>% - ungroup() %>% - select("asset_class", "investor_name", "portfolio_name", "scenario_source", - "scenario", "allocation", "equity_market", "year", "ald_sector", - "technology", "production_plan", "scenario_plan", "green", - "green_sum_prod", "green_sum_scenario") %>% - pivot_longer( - cols = -c("asset_class", "investor_name", "portfolio_name", "scenario_source", - "scenario", "allocation", "equity_market", "year", "ald_sector", - "technology", "green","green_sum_prod", "green_sum_scenario"), - names_to = "val_type", values_to = "value") %>% - mutate( - green_sum = if_else(.data$val_type == "production_plan", .data$green_sum_prod, .data$green_sum_scenario) - ) %>% - select(-c("green_sum_prod", "green_sum_scenario")) %>% - ungroup() %>% - mutate(this_portfolio = .data$portfolio_name == .env$portfolio_name, - val_type = if_else(.data$this_portfolio == TRUE, paste0(.data$val_type, "_portfolio"), paste0(.data$val_type, "_benchmark"))) %>% - mutate(equity_market = case_when( - .data$equity_market == "GlobalMarket" ~ "Global Market", - .data$equity_market == "DevelopedMarket" ~ "Developed Market", - .data$equity_market == "EmergingMarket" ~ "Emerging Market", - TRUE ~ .data$equity_market) - ) %>% - # no need for showing scenario mix for the benchmark - filter( - .data$val_type != "scenario_plan_benchmark" - ) %>% - mutate(val_type = case_when( - .data$val_type == "production_plan_portfolio" ~ "Portfolio", - .data$val_type == "scenario_plan_portfolio" ~ "Scenario", - .data$val_type == "production_plan_benchmark" ~ "Benchmark", - TRUE ~ .data$val_type) - ) %>% - arrange( - .data$asset_class, - factor(.data$equity_market, levels = c("Global Market", "Developed Market", "Emerging Market")), - desc(.data$this_portfolio), - factor(.data$val_type, levels = c("Portfolio", "Scenario", "Benchmark")), - .data$portfolio_name, - factor(.data$technology, levels = .env$all_tech_levels) - ) %>% - select("asset_class", "equity_market", "portfolio_name", "scenario", "scenario_source", - "this_portfolio", "val_type", "ald_sector", "technology", "value", - "green", "green_sum", "year") %>% - filter( - !(.data$year == .env$start_year & .data$val_type == "Scenario") + techexposure_data <- dplyr::bind_rows(portfolio, peers, indices) |> + dplyr::filter(.data[["allocation"]] == "portfolio_weight") |> + dplyr::filter(.data[["scenario_geography"]] == "Global") |> + dplyr::filter( + .data[["year"]] %in% c( + .env[["start_year"]], + .env[["start_year"]] + .env[["year_span"]] + ) ) -} -techexposure_data + if (nrow(techexposure_data) > 0L) { + techexposure_data <- techexposure_data |> + dplyr::mutate(green = .data[["technology"]] %in% .env[["green_techs"]]) |> + dplyr::group_by( + .data[["asset_class"]], + .data[["equity_market"]], + .data[["portfolio_name"]], + .data[["ald_sector"]], + .data[["scenario"]], + .data[["year"]] + ) |> + dplyr::mutate( + plan_alloc_wt_sec_prod = sum(.data[["plan_alloc_wt_tech_prod"]]), + scen_alloc_wt_sec_prod = sum(.data[["scen_alloc_wt_tech_prod"]]) + ) |> + dplyr::mutate( + production_plan = dplyr::if_else( + .data[["plan_alloc_wt_tech_prod"]] > 0L, + ( + .data[["plan_alloc_wt_tech_prod"]] / + .data[["plan_alloc_wt_sec_prod"]] + ), + 0L + ), + scenario_plan = dplyr::if_else( + .data[["scen_alloc_wt_tech_prod"]] > 0L, + ( + .data[["scen_alloc_wt_tech_prod"]] / + .data[["scen_alloc_wt_sec_prod"]] + ), + 0L + ) + ) |> + dplyr::group_by( + .data[["asset_class"]], + .data[["equity_market"]], + .data[["portfolio_name"]], + .data[["ald_sector"]], + .data[["scenario"]], + .data[["year"]], + .data[["green"]] + ) |> + dplyr::mutate( + green_sum_prod = sum(.data[["production_plan"]]), + green_sum_scenario = sum(.data[["scenario_plan"]]) + ) |> + dplyr::ungroup() |> + dplyr::select( + "asset_class", + "investor_name", + "portfolio_name", + "scenario_source", + "scenario", + "allocation", + "equity_market", + "year", + "ald_sector", + "technology", + "production_plan", + "scenario_plan", + "green", + "green_sum_prod", + "green_sum_scenario" + ) |> + tidyr::pivot_longer( + cols = -c( #nolint + "asset_class", + "investor_name", + "portfolio_name", + "scenario_source", + "scenario", + "allocation", + "equity_market", + "year", + "ald_sector", + "technology", + "green", + "green_sum_prod", + "green_sum_scenario" + ), + names_to = "val_type", values_to = "value") |> + dplyr::mutate( + green_sum = dplyr::if_else( + .data[["val_type"]] == "production_plan", + .data[["green_sum_prod"]], + .data[["green_sum_scenario"]] + ) + ) |> + dplyr::select(-c("green_sum_prod", "green_sum_scenario")) |> + dplyr::ungroup() |> + dplyr::mutate( + this_portfolio = .data[["portfolio_name"]] == .env[["portfolio_name"]], + val_type = dplyr::if_else( + .data[["this_portfolio"]], + paste0(.data[["val_type"]], "_portfolio"), + paste0(.data[["val_type"]], "_benchmark") + ) + ) |> + dplyr::mutate( + equity_market = dplyr::case_when( + .data[["equity_market"]] == "GlobalMarket" ~ "Global Market", + .data[["equity_market"]] == "DevelopedMarket" ~ "Developed Market", + .data[["equity_market"]] == "EmergingMarket" ~ "Emerging Market", + TRUE ~ .data[["equity_market"]] + ) + ) |> + # no need for showing scenario mix for the benchmark + dplyr::filter( + .data[["val_type"]] != "scenario_plan_benchmark" + ) |> + dplyr::mutate( + val_type = dplyr::case_when( + .data[["val_type"]] == "production_plan_portfolio" ~ "Portfolio", + .data[["val_type"]] == "scenario_plan_portfolio" ~ "Scenario", + .data[["val_type"]] == "production_plan_benchmark" ~ "Benchmark", + TRUE ~ .data[["val_type"]] + ) + ) |> + dplyr::arrange( + .data[["asset_class"]], + factor( + .data[["equity_market"]], + levels = c("Global Market", "Developed Market", "Emerging Market") + ), + dplyr::desc(.data[["this_portfolio"]]), + factor( + .data[["val_type"]], + levels = c("Portfolio", "Scenario", "Benchmark") + ), + .data[["portfolio_name"]], + factor(.data[["technology"]], levels = .env[["all_tech_levels"]]) + ) |> + dplyr::select( + "asset_class", + "equity_market", + "portfolio_name", + "scenario", + "scenario_source", + "this_portfolio", + "val_type", + "ald_sector", + "technology", + "value", + "green", + "green_sum", + "year" + ) |> + dplyr::filter( + !( + .data[["year"]] == .env[["start_year"]] & + .data[["val_type"]] == "Scenario" + ) + ) } + techexposure_data +} diff --git a/R/prep_trajectory_alignment.R b/R/prep_trajectory_alignment.R index 3074e24..02c149e 100644 --- a/R/prep_trajectory_alignment.R +++ b/R/prep_trajectory_alignment.R @@ -1,146 +1,236 @@ -prep_trajectory_alignment <- - function(equity_results_portfolio, - bonds_results_portfolio, - peers_equity_results_portfolio, - peers_bonds_results_portfolio, - indices_equity_results_portfolio, - indices_bonds_results_portfolio, - investor_name, - portfolio_name, - tech_roadmap_sectors, - peer_group, - start_year, - year_span, - scen_geo_levels, - all_tech_levels) { +prep_trajectory_alignment <- function( + equity_results_portfolio, + bonds_results_portfolio, + peers_equity_results_portfolio, + peers_bonds_results_portfolio, + indices_eq_results_portfolio, + indices_cb_results_portfolio, + investor_name, + portfolio_name, + tech_roadmap_sectors, + peer_group, + start_year, + year_span, + scen_geo_levels, + all_tech_levels +) { - portfolio <- - list(`Listed Equity` = equity_results_portfolio, - `Corporate Bonds` = bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$investor_name == .env$investor_name, - .data$portfolio_name == .env$portfolio_name) %>% - filter(.data$ald_sector %in% .env$tech_roadmap_sectors) %>% - filter(.data$scenario_geography != "GlobalAggregate") %>% - group_by(.data$asset_class, - .data$allocation, - .data$equity_market, - .data$technology, - .data$scenario) %>% - filter(n() > 1) %>% - ungroup() + portfolio <- list( + `Listed Equity` = equity_results_portfolio, + `Corporate Bonds` = bonds_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter( + .data[["investor_name"]] == .env[["investor_name"]], + .data[["portfolio_name"]] == .env[["portfolio_name"]] + ) |> + dplyr::filter(.data[["ald_sector"]] %in% .env[["tech_roadmap_sectors"]]) |> + dplyr::filter(.data[["scenario_geography"]] != "GlobalAggregate") |> + dplyr::group_by( + .data[["asset_class"]], + .data[["allocation"]], + .data[["equity_market"]], + .data[["technology"]], + .data[["scenario"]] + ) |> + dplyr::filter(dplyr::n() > 1L) |> + dplyr::ungroup() - asset_classes <- - portfolio %>% - pull("asset_class") %>% - unique() + asset_classes <- portfolio |> + dplyr::pull("asset_class") |> + unique() - equity_markets <- - portfolio %>% - filter(.data$asset_class == "Listed Equity") %>% - pull("equity_market") %>% - unique() + equity_markets <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Listed Equity") |> + dplyr::pull("equity_market") |> + unique() - bonds_markets <- - portfolio %>% - filter(.data$asset_class == "Corporate Bonds") %>% - pull("equity_market") %>% - unique() + bonds_markets <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Corporate Bonds") |> + dplyr::pull("equity_market") |> + unique() - equity_techs <- - portfolio %>% - filter(.data$asset_class == "Listed Equity") %>% - pull("technology") %>% - unique() + equity_techs <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Listed Equity") |> + dplyr::pull("technology") |> + unique() - equity_scenario_geography <- - portfolio %>% - filter(.data$asset_class == "Listed Equity") %>% - pull("scenario_geography") %>% - unique() + equity_scenario_geography <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Listed Equity") |> + dplyr::pull("scenario_geography") |> + unique() - bonds_scenario_geography <- - portfolio %>% - filter(.data$asset_class == "Corporate Bonds") %>% - pull("scenario_geography") %>% - unique() + bonds_scenario_geography <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Corporate Bonds") |> + dplyr::pull("scenario_geography") |> + unique() - bonds_techs <- - portfolio %>% - filter(.data$asset_class == "Corporate Bonds") %>% - pull("technology") %>% - unique() + bonds_techs <- portfolio |> + dplyr::filter(.data[["asset_class"]] == "Corporate Bonds") |> + dplyr::pull("technology") |> + unique() - peers <- - list(`Listed Equity` = peers_equity_results_portfolio, - `Corporate Bonds` = peers_bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$ald_sector %in% .env$tech_roadmap_sectors) %>% - filter(.data$scenario_geography != "GlobalAggregate") %>% - filter(.data$asset_class %in% .env$asset_classes) %>% - filter(.data$asset_class == "Listed Equity" & .data$equity_market %in% .env$equity_markets | - .data$asset_class == "Corporate Bonds" & .data$equity_market %in% .env$bonds_markets) %>% - filter(.data$asset_class == "Listed Equity" & .data$technology %in% .env$equity_techs | - .data$asset_class == "Corporate Bonds" & .data$technology %in% .env$bonds_techs) %>% - filter(.data$asset_class == "Listed Equity" & .data$scenario_geography %in% .env$equity_scenario_geography | - .data$asset_class == "Corporate Bonds" & .data$scenario_geography %in% .env$bonds_scenario_geography) %>% - filter(.data$investor_name == .env$peer_group) + peers <- list( + `Listed Equity` = peers_equity_results_portfolio, + `Corporate Bonds` = peers_bonds_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter(.data[["ald_sector"]] %in% .env[["tech_roadmap_sectors"]]) |> + dplyr::filter(.data[["scenario_geography"]] != "GlobalAggregate") |> + dplyr::filter(.data[["asset_class"]] %in% .env[["asset_classes"]]) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["equity_market"]] %in% .env[["equity_markets"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["equity_market"]] %in% .env[["bonds_markets"]] + ) + ) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["technology"]] %in% .env[["equity_techs"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["technology"]] %in% .env[["bonds_techs"]] + ) + ) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["scenario_geography"]] %in% .env[["equity_scenario_geography"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["scenario_geography"]] %in% .env[["bonds_scenario_geography"]] + ) + ) |> + dplyr::filter(.data[["investor_name"]] == .env[["peer_group"]]) - indices <- - list(`Listed Equity` = indices_equity_results_portfolio, - `Corporate Bonds` = indices_bonds_results_portfolio) %>% - bind_rows(.id = "asset_class") %>% - filter(.data$ald_sector %in% .env$tech_roadmap_sectors) %>% - filter(.data$scenario_geography != "GlobalAggregate") %>% - filter(.data$asset_class %in% .env$asset_classes) %>% - filter(.data$asset_class == "Listed Equity" & .data$equity_market %in% .env$equity_markets | - .data$asset_class == "Corporate Bonds" & .data$equity_market %in% .env$bonds_markets) %>% - filter(.data$asset_class == "Listed Equity" & .data$technology %in% .env$equity_techs | - .data$asset_class == "Corporate Bonds" & .data$technology %in% .env$bonds_techs) %>% - filter(.data$asset_class == "Listed Equity" & .data$scenario_geography %in% .env$equity_scenario_geography | - .data$asset_class == "Corporate Bonds" & .data$scenario_geography %in% .env$bonds_scenario_geography) + indices <- list( + `Listed Equity` = indices_eq_results_portfolio, + `Corporate Bonds` = indices_cb_results_portfolio + ) |> + dplyr::bind_rows(.id = "asset_class") |> + dplyr::filter(.data[["ald_sector"]] %in% .env[["tech_roadmap_sectors"]]) |> + dplyr::filter(.data[["scenario_geography"]] != "GlobalAggregate") |> + dplyr::filter(.data[["asset_class"]] %in% .env[["asset_classes"]]) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["equity_market"]] %in% .env[["equity_markets"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["equity_market"]] %in% .env[["bonds_markets"]] + ) + ) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["technology"]] %in% .env[["equity_techs"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["technology"]] %in% .env[["bonds_techs"]] + ) + ) |> + dplyr::filter( + ( + .data[["asset_class"]] == "Listed Equity" & + .data[["scenario_geography"]] %in% .env[["equity_scenario_geography"]] + ) | ( + .data[["asset_class"]] == "Corporate Bonds" & + .data[["scenario_geography"]] %in% .env[["bonds_scenario_geography"]] + ) + ) - benchmark_data <- bind_rows(peers, indices) + benchmark_data <- dplyr::bind_rows(peers, indices) - cols_with_supporting_info <- c("benchmark", "portfolio_name", "asset_class", "equity_market", - "scenario_source", "scenario_geography", "allocation", - "ald_sector", "technology", "year", "unit") + cols_with_supporting_info <- c( + "benchmark", + "portfolio_name", + "asset_class", + "equity_market", + "scenario_source", + "scenario_geography", + "allocation", + "ald_sector", + "technology", + "year", + "unit" + ) - list(portfolio = portfolio, - benchmark = benchmark_data) %>% - bind_rows(.id = "benchmark") %>% - mutate(benchmark = .data$benchmark == "benchmark") %>% - mutate(unit = case_when( - .data$ald_sector == "Power" ~ "MW", - .data$ald_sector == "Oil&Gas" ~ "GJ/a", - .data$ald_sector == "Coal" ~ "t/a", - .data$ald_sector == "Automotive" ~ "number of cars", - .data$ald_sector == "Aviation" ~ "number of planes", - .data$ald_sector == "Cement" ~ "t/a", - .data$ald_sector == "Steel" ~ "t/a" - )) %>% - select(all_of(cols_with_supporting_info), "scenario", - production = "plan_alloc_wt_tech_prod", "scen_alloc_wt_tech_prod") %>% - pivot_wider(names_from = "scenario", values_from = "scen_alloc_wt_tech_prod") %>% - pivot_longer(cols = -cols_with_supporting_info, names_to = "scenario", values_to = "value", - values_drop_na = TRUE) %>% - mutate(value = if_else(.data$year > min(.data$year + 5) & .data$value == 0, NA_real_, .data$value)) %>% - filter(!is.na(.data$value)) %>% - filter(.data$scenario == "production" | !.data$benchmark) %>% - mutate(equity_market = case_when( - .data$equity_market == "GlobalMarket" ~ "Global Market", - .data$equity_market == "DevelopedMarket" ~ "Developed Market", - .data$equity_market == "EmergingMarket" ~ "Emerging Market", - TRUE ~ .data$equity_market) - ) %>% - mutate(allocation = case_when( - .data$allocation == "portfolio_weight" ~ "Portfolio Weight", - .data$allocation == "ownership_weight" ~ "Ownership Weight", - )) %>% - filter(.data$year <= .env$start_year + .env$year_span) %>% - arrange(.data$asset_class, - factor(.data$equity_market, levels = c("Global Market", "Developed Market", "Emerging Market")), - factor(.data$scenario_source, levels = c("WEO2021", "GECO2021", "ETP2020", "IPR2021", "ISF2021")), - factor(.data$scenario_geography, levels = .env$scen_geo_levels), - factor(.data$technology, levels = .env$all_tech_levels)) - } + list( + portfolio = portfolio, + benchmark = benchmark_data + ) |> + dplyr::bind_rows(.id = "benchmark") |> + dplyr::mutate(benchmark = .data[["benchmark"]] == "benchmark") |> + dplyr::mutate( + unit = dplyr::case_when( + .data[["ald_sector"]] == "Power" ~ "MW", + .data[["ald_sector"]] == "Oil&Gas" ~ "GJ/a", + .data[["ald_sector"]] == "Coal" ~ "t/a", + .data[["ald_sector"]] == "Automotive" ~ "number of cars", + .data[["ald_sector"]] == "Aviation" ~ "number of planes", + .data[["ald_sector"]] == "Cement" ~ "t/a", + .data[["ald_sector"]] == "Steel" ~ "t/a" + ) + ) |> + dplyr::select( + dplyr::all_of(cols_with_supporting_info), + "scenario", + production = "plan_alloc_wt_tech_prod", + "scen_alloc_wt_tech_prod" + ) |> + tidyr::pivot_wider( + names_from = "scenario", + values_from = "scen_alloc_wt_tech_prod" + ) |> + tidyr::pivot_longer( + cols = -cols_with_supporting_info, + names_to = "scenario", + values_to = "value", + values_drop_na = TRUE + ) |> + dplyr::mutate( + value = dplyr::if_else( + .data[["year"]] > min(.data[["year"]] + 5L) & .data[["value"]] == 0L, + NA_real_, + .data[["value"]] + ) + ) |> + dplyr::filter(!is.na(.data[["value"]])) |> + dplyr::filter( + .data[["scenario"]] == "production" | !.data[["benchmark"]] + ) |> + dplyr::mutate( + equity_market = dplyr::case_when( + .data[["equity_market"]] == "GlobalMarket" ~ "Global Market", + .data[["equity_market"]] == "DevelopedMarket" ~ "Developed Market", + .data[["equity_market"]] == "EmergingMarket" ~ "Emerging Market", + TRUE ~ .data[["equity_market"]] + ) + ) |> + dplyr::mutate( + allocation = dplyr::case_when( + .data[["allocation"]] == "portfolio_weight" ~ "Portfolio Weight", + .data[["allocation"]] == "ownership_weight" ~ "Ownership Weight" + ) + ) |> + dplyr::filter( + .data[["year"]] <= .env[["start_year"]] + .env[["year_span"]] + ) |> + dplyr::arrange( + .data[["asset_class"]], + factor( + .data[["equity_market"]], + levels = c("Global Market", "Developed Market", "Emerging Market") + ), + factor( + .data[["scenario_source"]], + levels = c("WEO2021", "GECO2021", "ETP2020", "IPR2021", "ISF2021") + ), + factor(.data[["scenario_geography"]], levels = .env[["scen_geo_levels"]]), + factor(.data[["technology"]], levels = .env[["all_tech_levels"]]) + ) +} diff --git a/R/prepare_pacta_dashboard_data.R b/R/prepare_pacta_dashboard_data.R index ee408d8..95f46f8 100644 --- a/R/prepare_pacta_dashboard_data.R +++ b/R/prepare_pacta_dashboard_data.R @@ -5,361 +5,452 @@ prepare_pacta_dashboard_data <- function( benchmarks_dir = Sys.getenv("BENCHMARKS_DIR") ) { -log_info("Preparing data for the PACTA dashboard.") + log_info("Preparing data for the PACTA dashboard.") -# portfolio/user parameters ---------------------------------------------------- -log_debug("Reading portfolio/user parameters.") + # portfolio/user parameters + log_debug("Reading parameters.") -investor_name <- params[["user"]][["name"]] -portfolio_name <- params[["portfolio"]][["name"]] -peer_group <- params[["user"]][["peerGroup"]] -language_select <- params[["user"]][["languageSelect"]] + investor_name <- params[["user"]][["name"]] + portfolio_name <- params[["portfolio"]][["name"]] + peer_group <- params[["user"]][["peerGroup"]] + language_select <- params[["user"]][["languageSelect"]] -currency_exchange_value <- params[["user"]][["currencyExchangeValue"]] -display_currency <- params[["user"]][["displayCurrency"]] + currency_exchange_value <- params[["user"]][["currencyExchangeValue"]] + display_currency <- params[["user"]][["displayCurrency"]] -select_scenario_other <- params[["reporting"]][["scenarioOther"]] -select_scenario <- params[["reporting"]][["selectScenario"]] + select_scenario_other <- params[["reporting"]][["scenarioOther"]] + select_scenario <- params[["reporting"]][["selectScenario"]] -green_techs <- params[["reporting"]][["greenTechs"]] -tech_roadmap_sectors <- params[["reporting"]][["techRoadmapSectors"]] -pacta_sectors_not_analysed <- params[["reporting"]][["pactaSectorsNotAnalysed"]] + green_techs <- params[["reporting"]][["greenTechs"]] + tech_roadmap_sectors <- params[["reporting"]][["techRoadmapSectors"]] + pacta_sectors_not_analysed <- params[["reporting"]][["pactaSectorsNotAnalysed"]] #nolint -power_tech_levels = c("RenewablesCap", "HydroCap", "NuclearCap", "GasCap", "OilCap", "CoalCap") -oil_gas_levels = c("Oil", "Gas") -coal_levels = c("Coal") -auto_levels = c("Electric", "Electric_HDV", "FuelCell","FuelCell_HDV", "Hybrid","Hybrid_HDV", "ICE", "ICE_HDV") -cement_levels = c("Integrated facility", "Grinding") -steel_levels = c("Electric Arc Furnace", "Open Hearth Furnace", "Basic Oxygen Furnace") -aviation_levels = c("Freight", "Passenger", "Mix", "Other") -all_tech_levels = c(power_tech_levels, auto_levels, oil_gas_levels, coal_levels, cement_levels, steel_levels, aviation_levels) + power_tech_levels <- c( + "RenewablesCap", + "HydroCap", + "NuclearCap", + "GasCap", + "OilCap", + "CoalCap" + ) + oil_gas_levels <- c( + "Oil", + "Gas" + ) + coal_levels <- "Coal" + auto_levels <- c( + "Electric", + "Electric_HDV", + "FuelCell", + "FuelCell_HDV", + "Hybrid", + "Hybrid_HDV", + "ICE", + "ICE_HDV" + ) + cement_levels <- c("Integrated facility", "Grinding") + steel_levels <- c( + "Electric Arc Furnace", + "Open Hearth Furnace", + "Basic Oxygen Furnace" + ) + aviation_levels <- c( + "Freight", + "Passenger", + "Mix", + "Other" + ) + all_tech_levels <- c( + power_tech_levels, + auto_levels, + oil_gas_levels, + coal_levels, + cement_levels, + steel_levels, + aviation_levels + ) -# config parameters from manifest ---------------------------------------------- -log_debug("Reading config parameters from analysis outputs manifest.") + # config parameters from manifest + log_debug("Reading config parameters from analysis outputs manifest.") -manifest <- jsonlite::read_json(path = file.path(analysis_output_dir, "manifest.json")) + manifest <- jsonlite::read_json( + path = file.path(analysis_output_dir, "manifest.json") + ) -start_year <- manifest$params$analysis$startYear -year_span <- manifest$params$analysis$timeHorizon -pacta_sectors <- unlist(manifest$params$analysis$sectorList) -equity_market_levels <- unlist(manifest$params$analysis$equityMarketList) -scen_geo_levels <- unlist(manifest$params$analysis$scenarioGeographiesList) + start_year <- manifest[["params"]][["analysis"]][["startYear"]] + year_span <- manifest[["params"]][["analysis"]][["timeHorizon"]] + pacta_sectors <- unlist(manifest[["params"]][["analysis"]][["sectorList"]]) + equity_market_levels <- unlist(manifest[["params"]][["analysis"]][["equityMarketList"]]) #nolint + scen_geo_levels <- unlist(manifest[["params"]][["analysis"]][["scenarioGeographiesList"]]) #nolint -# load results from input directory -------------------------------------------- -log_debug("Loading results from input directory.") + # load results from input directory + log_debug("Loading results from input directory.") -audit_file <- readRDS(file.path(analysis_output_dir, "audit_file.rds")) -emissions <- readRDS(file.path(analysis_output_dir, "emissions.rds")) -equity_results_portfolio <- readRDS(file.path(analysis_output_dir, "Equity_results_portfolio.rds")) -bonds_results_portfolio <- readRDS(file.path(analysis_output_dir, "Bonds_results_portfolio.rds")) -equity_results_company <- readRDS(file.path(analysis_output_dir, "Equity_results_company.rds")) -bonds_results_company <- readRDS(file.path(analysis_output_dir, "Bonds_results_company.rds")) + audit_file <- readRDS(file.path(analysis_output_dir, "audit_file.rds")) + emissions <- readRDS(file.path(analysis_output_dir, "emissions.rds")) + equity_results_portfolio <- readRDS( + file.path(analysis_output_dir, "Equity_results_portfolio.rds") + ) + bonds_results_portfolio <- readRDS( + file.path(analysis_output_dir, "Bonds_results_portfolio.rds") + ) + equity_results_company <- readRDS( + file.path(analysis_output_dir, "Equity_results_company.rds") + ) + bonds_results_company <- readRDS( + file.path(analysis_output_dir, "Bonds_results_company.rds") + ) -# data from PACTA inputs used to generate the results -------------------------- -log_debug("Loading benchmark results.") + # data from PACTA inputs used to generate the results + log_debug("Loading benchmark results.") -indices_bonds_results_portfolio <- readRDS(file.path(benchmarks_dir, "Indices_bonds_results_portfolio.rds")) -indices_equity_results_portfolio <- readRDS(file.path(benchmarks_dir, "Indices_equity_results_portfolio.rds")) + indices_cb_results_portfolio <- readRDS( + file.path(benchmarks_dir, "Indices_bonds_results_portfolio.rds") + ) + indices_eq_results_portfolio <- readRDS( + file.path(benchmarks_dir, "Indices_equity_results_portfolio.rds") + ) -log_debug("Loading peer results.") -peers_bonds_results_portfolio <- pacta.portfolio.utils::empty_portfolio_results() -peers_equity_results_portfolio <- pacta.portfolio.utils::empty_portfolio_results() + log_debug("Loading peer results.") + peers_bonds_results_portfolio <- pacta.portfolio.utils::empty_portfolio_results() #nolint + peers_equity_results_portfolio <- pacta.portfolio.utils::empty_portfolio_results() #nolint -# translations ----------------------------------------------------------------- -log_debug("Loading translations.") + # translations + log_debug("Loading translations.") -dataframe_translations <- readr::read_csv( - system.file("extdata/translation/dataframe_labels.csv", package = "workflow.pacta.dashboard"), - col_types = readr::cols() -) + dataframe_translations <- readr::read_csv( + system.file( + "extdata", "translation", "dataframe_labels.csv", + package = "workflow.pacta.dashboard" + ), + col_types = readr::cols() + ) -header_dictionary <- readr::read_csv( - system.file("extdata/translation/dataframe_headers.csv", package = "workflow.pacta.dashboard"), - col_types = readr::cols() -) + header_dictionary <- readr::read_csv( + system.file( + "extdata", "translation", "dataframe_headers.csv", + package = "workflow.pacta.dashboard" + ), + col_types = readr::cols() + ) -js_translations <- jsonlite::fromJSON( - txt = system.file("extdata/translation/js_labels.json", package = "workflow.pacta.dashboard") -) + js_translations <- jsonlite::fromJSON( + txt = system.file( + "extdata", "translation", "js_labels.json", + package = "workflow.pacta.dashboard" + ) + ) -sector_order <- readr::read_csv( - system.file("extdata/sector_order/sector_order.csv", package = "workflow.pacta.dashboard"), - col_types = readr::cols() -) + sector_order <- readr::read_csv( + system.file( + "extdata", "sector_order", "sector_order.csv", + package = "workflow.pacta.dashboard" + ), + col_types = readr::cols() + ) -dictionary <- - choose_dictionary_language( + dictionary <- choose_dictionary_language( data = dataframe_translations, language = language_select ) -header_dictionary <- replace_contents(header_dictionary, display_currency) + header_dictionary <- replace_contents(header_dictionary, display_currency) -# add investor_name and portfolio_name to results data frames because ---------- -# pacta.portfolio.report functions expect that --------------------------------- -log_debug("Adding investor_name and portfolio_name to results data frames.") + # add investor_name and portfolio_name to results data frames because + # pacta.portfolio.report functions expect that + log_debug("Adding investor_name and portfolio_name to results data frames.") -audit_file <- - audit_file %>% - mutate( - investor_name = investor_name, - portfolio_name = portfolio_name - ) + audit_file <- audit_file |> + dplyr::mutate( + investor_name = investor_name, + portfolio_name = portfolio_name + ) -emissions <- - emissions %>% - mutate( - investor_name = investor_name, - portfolio_name = portfolio_name - ) + emissions <- emissions |> + dplyr::mutate( + investor_name = investor_name, + portfolio_name = portfolio_name + ) -equity_results_portfolio <- - equity_results_portfolio %>% - mutate( - investor_name = investor_name, - portfolio_name = portfolio_name - ) + equity_results_portfolio <- equity_results_portfolio |> + dplyr::mutate( + investor_name = investor_name, + portfolio_name = portfolio_name + ) -bonds_results_portfolio <- - bonds_results_portfolio %>% - mutate( - investor_name = investor_name, - portfolio_name = portfolio_name - ) + bonds_results_portfolio <- bonds_results_portfolio |> + dplyr::mutate( + investor_name = investor_name, + portfolio_name = portfolio_name + ) -equity_results_company <- - equity_results_company %>% - mutate( - investor_name = investor_name, - portfolio_name = portfolio_name - ) + equity_results_company <- equity_results_company |> + dplyr::mutate( + investor_name = investor_name, + portfolio_name = portfolio_name + ) + + bonds_results_company <- bonds_results_company |> + dplyr::mutate( + investor_name = investor_name, + portfolio_name = portfolio_name + ) + + + # data_included_table.json + + log_info("Preparing data_included_table.json.") + audit_file |> + prep_audit_table( + investor_name = investor_name, + portfolio_name = portfolio_name, + currency_exchange_value = currency_exchange_value + ) |> + translate_df_contents("data_included_table", dictionary, inplace = TRUE) |> + translate_df_headers( + "data_included_table", + language_select, + header_dictionary + ) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_included_table.json") + ) + + + # data_value_pie_bonds.json + + log_info("Preparing data_value_pie_bonds.json.") + audit_file |> + prep_exposure_pie( + asset_type = "Bonds", + investor_name = investor_name, + portfolio_name = portfolio_name, + pacta_sectors = pacta_sectors, + currency_exchange_value = currency_exchange_value + ) |> + translate_df_contents("data_value_pie_bonds", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_value_pie_bonds.json") + ) + + + # data_emissions_equity.json -bonds_results_company <- - bonds_results_company %>% - mutate( + log_info("Preparing data_emissions_equity.json.") + emissions |> + prep_emissions_pie( + asset_type = "Equity", + investor_name = investor_name, + portfolio_name = portfolio_name, + pacta_sectors = pacta_sectors + ) |> + translate_df_contents("data_emissions_pie_equity", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_emissions_pie_equity.json") + ) + + + # data_emissions_bonds.json + + log_info("Preparing data_emissions_bonds.json.") + emissions |> + prep_emissions_pie( + asset_type = "Bonds", + investor_name = investor_name, + portfolio_name = portfolio_name, + pacta_sectors = pacta_sectors + ) |> + translate_df_contents("data_emissions_pie_bonds", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_emissions_pie_bonds.json") + ) + + + # data_value_pie_equity.json + + log_info("Preparing data_value_pie_equity.json.") + audit_file |> + prep_exposure_pie( + asset_type = "Equity", + investor_name = investor_name, + portfolio_name = portfolio_name, + pacta_sectors = pacta_sectors, + currency_exchange_value = currency_exchange_value + ) |> + translate_df_contents("data_value_pie_equity", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_value_pie_equity.json") + ) + + + # data_techmix.json + + log_info("Preparing data_techmix.json.") + prep_techexposure( + equity_results_portfolio = equity_results_portfolio, + bonds_results_portfolio = bonds_results_portfolio, investor_name = investor_name, - portfolio_name = portfolio_name - ) + portfolio_name = portfolio_name, + indices_eq_results_portfolio = indices_eq_results_portfolio, + indices_cb_results_portfolio = indices_cb_results_portfolio, + peers_equity_results_portfolio = peers_equity_results_portfolio, + peers_bonds_results_portfolio = peers_bonds_results_portfolio, + peer_group = peer_group, + select_scenario_other = select_scenario_other, + select_scenario = select_scenario, + start_year = start_year, + green_techs = green_techs, + equity_market_levels = equity_market_levels, + all_tech_levels = all_tech_levels + ) |> + translate_df_contents("techexposure_data", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_techexposure.json") + ) -# data_included_table.json ----------------------------------------------------- + # data_techmix_sector.json + + log_info("Preparing data_techmix_sector.json.") + prep_techmix_sector( + equity_results_portfolio, + bonds_results_portfolio, + indices_eq_results_portfolio, + indices_cb_results_portfolio, + peers_equity_results_portfolio, + peers_bonds_results_portfolio, + investor_name, + portfolio_name, + start_year, + year_span, + peer_group, + green_techs, + all_tech_levels + ) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_techmix_sector.json") + ) + + # data_trajectory_alignment.json -log_info("Preparing data_included_table.json.") -audit_file %>% - prep_audit_table( + log_info("Preparing data_trajectory_alignment.json.") + prep_trajectory_alignment( + equity_results_portfolio = equity_results_portfolio, + bonds_results_portfolio = bonds_results_portfolio, + peers_equity_results_portfolio = peers_equity_results_portfolio, + peers_bonds_results_portfolio = peers_bonds_results_portfolio, + indices_eq_results_portfolio = indices_eq_results_portfolio, + indices_cb_results_portfolio = indices_cb_results_portfolio, investor_name = investor_name, portfolio_name = portfolio_name, - currency_exchange_value = currency_exchange_value - ) %>% - translate_df_contents("data_included_table", dictionary, inplace = TRUE) %>% - translate_df_headers("data_included_table", language_select, header_dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_included_table.json")) + tech_roadmap_sectors = tech_roadmap_sectors, + peer_group = peer_group, + start_year = start_year, + year_span = year_span, + scen_geo_levels = scen_geo_levels, + all_tech_levels = all_tech_levels + ) |> + translate_df_contents("data_trajectory_alignment", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_trajectory_alignment.json") + ) + + # data_emissions.json -# data_value_pie_bonds.json ---------------------------------------------------- + log_info("Preparing data_emissions.json.") + prep_emissions_trajectory( + equity_results_portfolio = equity_results_portfolio, + bonds_results_portfolio = bonds_results_portfolio, + portfolio_name = portfolio_name, + pacta_sectors = pacta_sectors, + year_span = year_span, + start_year = start_year + ) |> + translate_df_contents("data_emissions", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_emissions.json") + ) -log_info("Preparing data_value_pie_bonds.json.") -audit_file %>% - prep_exposure_pie( - asset_type = "Bonds", + # data_exposure_stats.json + + log_info("Preparing data_exposure_stats.json.") + prep_exposure_stats( + audit_file = audit_file, investor_name = investor_name, portfolio_name = portfolio_name, pacta_sectors = pacta_sectors, currency_exchange_value = currency_exchange_value - ) %>% - translate_df_contents("data_value_pie_bonds", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_value_pie_bonds.json")) + ) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_exposure_stats.json") + ) -# data_emissions_equity.json --------------------------------------------------- + # data_company_bubble.json -log_info("Preparing data_emissions_equity.json.") -emissions %>% - prep_emissions_pie( - asset_type = "Equity", - investor_name = investor_name, + log_info("Preparing data_company_bubble.json.") + prep_company_bubble( + equity_results_company = equity_results_company, + bonds_results_company = bonds_results_company, portfolio_name = portfolio_name, - pacta_sectors = pacta_sectors - ) %>% - translate_df_contents("data_emissions_pie_equity", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_emissions_pie_equity.json")) + start_year = start_year, + green_techs = green_techs + ) |> + translate_df_contents("data_company_bubble", dictionary) |> + jsonlite::write_json( + path = file.path(dashboard_data_dir, "data_company_bubble.json") + ) -# data_emissions_bonds.json ---------------------------------------------------- + # data_techexposure_company_companies.json -log_info("Preparing data_emissions_bonds.json.") -emissions %>% - prep_emissions_pie( - asset_type = "Bonds", - investor_name = investor_name, + log_info("Preparing data_techexposure_company_companies.json.") + prep_key_bars_company( + equity_results_company = equity_results_company, + bonds_results_company = bonds_results_company, portfolio_name = portfolio_name, - pacta_sectors = pacta_sectors - ) %>% - translate_df_contents("data_emissions_pie_bonds", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_emissions_pie_bonds.json")) + start_year = start_year, + pacta_sectors_not_analysed = pacta_sectors_not_analysed, + all_tech_levels = all_tech_levels + ) |> + translate_df_contents("data_key_bars_company", dictionary) |> + jsonlite::write_json( + path = file.path( + dashboard_data_dir, + "data_techexposure_company_companies.json" + ) + ) -# data_value_pie_equity.json --------------------------------------------------- + # data_techexposure_company_portfolio.json -log_info("Preparing data_value_pie_equity.json.") -audit_file %>% - prep_exposure_pie( - asset_type = "Equity", - investor_name = investor_name, + log_info("Preparing data_techexposure_company_portfolio.json.") + prep_key_bars_portfolio( + equity_results_portfolio = equity_results_portfolio, + bonds_results_portfolio = bonds_results_portfolio, portfolio_name = portfolio_name, - pacta_sectors = pacta_sectors, - currency_exchange_value = currency_exchange_value - ) %>% - translate_df_contents("data_value_pie_equity", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_value_pie_equity.json")) - - -# data_techmix.json ------------------------------------------------------------ - -log_info("Preparing data_techmix.json.") -prep_techexposure( - equity_results_portfolio = equity_results_portfolio, - bonds_results_portfolio = bonds_results_portfolio, - investor_name = investor_name, - portfolio_name = portfolio_name, - indices_equity_results_portfolio = indices_equity_results_portfolio, - indices_bonds_results_portfolio = indices_bonds_results_portfolio, - peers_equity_results_portfolio = peers_equity_results_portfolio, - peers_bonds_results_portfolio = peers_bonds_results_portfolio, - peer_group = peer_group, - select_scenario_other = select_scenario_other, - select_scenario = select_scenario, - start_year = start_year, - green_techs = green_techs, - equity_market_levels = equity_market_levels, - all_tech_levels = all_tech_levels - ) %>% - translate_df_contents("techexposure_data", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_techexposure.json")) - - -# data_techmix_sector.json ----------------------------------------------------- - -log_info("Preparing data_techmix_sector.json.") -prep_techmix_sector( - equity_results_portfolio, - bonds_results_portfolio, - indices_equity_results_portfolio, - indices_bonds_results_portfolio, - peers_equity_results_portfolio, - peers_bonds_results_portfolio, - investor_name, - portfolio_name, - start_year, - year_span, - peer_group, - green_techs, - all_tech_levels - ) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_techmix_sector.json")) - -# data_trajectory_alignment.json ----------------------------------------------- - -log_info("Preparing data_trajectory_alignment.json.") -prep_trajectory_alignment( - equity_results_portfolio = equity_results_portfolio, - bonds_results_portfolio = bonds_results_portfolio, - peers_equity_results_portfolio = peers_equity_results_portfolio, - peers_bonds_results_portfolio = peers_bonds_results_portfolio, - indices_equity_results_portfolio = indices_equity_results_portfolio, - indices_bonds_results_portfolio = indices_bonds_results_portfolio, - investor_name = investor_name, - portfolio_name = portfolio_name, - tech_roadmap_sectors = tech_roadmap_sectors, - peer_group = peer_group, - start_year = start_year, - year_span = year_span, - scen_geo_levels = scen_geo_levels, - all_tech_levels = all_tech_levels - ) %>% - translate_df_contents("data_trajectory_alignment", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_trajectory_alignment.json")) - - -# data_emissions.json ---------------------------------------------------------- - -log_info("Preparing data_emissions.json.") -prep_emissions_trajectory( - equity_results_portfolio = equity_results_portfolio, - bonds_results_portfolio = bonds_results_portfolio, - portfolio_name = portfolio_name, - pacta_sectors = pacta_sectors, - year_span = year_span, - start_year = start_year - ) %>% - translate_df_contents("data_emissions", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_emissions.json")) - -# data_exposure_stats.json - -log_info("Preparing data_exposure_stats.json.") -prep_exposure_stats( - audit_file = audit_file, - investor_name = investor_name, - portfolio_name = portfolio_name, - pacta_sectors = pacta_sectors, - currency_exchange_value = currency_exchange_value - ) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_exposure_stats.json")) - - -# data_company_bubble.json ----------------------------------------------------- - -log_info("Preparing data_company_bubble.json.") -prep_company_bubble( - equity_results_company = equity_results_company, - bonds_results_company = bonds_results_company, - portfolio_name = portfolio_name, - start_year = start_year, - green_techs = green_techs - ) %>% - translate_df_contents("data_company_bubble", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_company_bubble.json")) - - -# data_techexposure_company_companies.json ------------------------------------- - -log_info("Preparing data_techexposure_company_companies.json.") -prep_key_bars_company( - equity_results_company = equity_results_company, - bonds_results_company = bonds_results_company, - portfolio_name = portfolio_name, - start_year = start_year, - pacta_sectors_not_analysed = pacta_sectors_not_analysed, - all_tech_levels = all_tech_levels - ) %>% - translate_df_contents("data_key_bars_company", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_techexposure_company_companies.json")) - - -# data_techexposure_company_portfolio.json ------------------------------------- - -log_info("Preparing data_techexposure_company_portfolio.json.") -prep_key_bars_portfolio( - equity_results_portfolio = equity_results_portfolio, - bonds_results_portfolio = bonds_results_portfolio, - portfolio_name = portfolio_name, - start_year = start_year, - pacta_sectors_not_analysed = pacta_sectors_not_analysed, - all_tech_levels = all_tech_levels - ) %>% - translate_df_contents("data_key_bars_portfolio", dictionary) %>% - jsonlite::write_json(path = file.path(dashboard_data_dir, "data_techexposure_company_portfolio.json")) - - -# put JSON and CSV outputs into a zip archive ---------------------------------- - -zip_outputs(dashboard_data_dir) + start_year = start_year, + pacta_sectors_not_analysed = pacta_sectors_not_analysed, + all_tech_levels = all_tech_levels + ) |> + translate_df_contents("data_key_bars_portfolio", dictionary) |> + jsonlite::write_json( + path = file.path( + dashboard_data_dir, + "data_techexposure_company_portfolio.json" + ) + ) + + + # put JSON and CSV outputs into a zip archive + + zip_outputs(dashboard_data_dir) } @@ -367,23 +458,23 @@ zip_outputs(dashboard_data_dir) zip_outputs <- function(dashboard_data_dir) { log_debug("Preparing outputs zip archive.") json_filenames <- list.files(dashboard_data_dir, pattern = "[.]json$") - + zip_temp <- file.path(tempdir(), "zip_temp") dir.create(zip_temp, showWarnings = FALSE) - + for (json_filename in json_filenames) { log_trace(paste("Adding", json_filename, "to zip archive.")) file.copy( from = file.path(dashboard_data_dir, json_filename), to = file.path(zip_temp, json_filename) ) - + csv_filename <- sub("[.]json$", ".csv", json_filename) - + df <- jsonlite::read_json( path = file.path(dashboard_data_dir, json_filename), simplifyVector = TRUE - ) + ) if (inherits(df, "data.frame")) { log_trace(paste("Adding", csv_filename, "to zip archive.")) @@ -395,7 +486,7 @@ zip_outputs <- function(dashboard_data_dir) { ) } } - + log_debug("Creating zip archive.") utils::zip( zipfile = file.path(dashboard_data_dir, "archive.zip"), diff --git a/R/prepare_schema_files.R b/R/prepare_schema_files.R index 40d9749..319422d 100644 --- a/R/prepare_schema_files.R +++ b/R/prepare_schema_files.R @@ -8,7 +8,9 @@ #' @return directory #' #' @export -prepare_schema_files <- function(directory) { +prepare_schema_files <- function( + directory +) { log_debug("Preparing schema files.") log_debug("Schema tempdir: ", directory) dashboard_schema_files <- list.files( diff --git a/R/replace_contents.R b/R/replace_contents.R index 07e01c4..e2a29f8 100644 --- a/R/replace_contents.R +++ b/R/replace_contents.R @@ -1,5 +1,17 @@ -replace_contents <- function(data, display_currency) { - mutate(data, across(.cols = everything(), .fns = ~ gsub("_CUR_", display_currency, .x))) +replace_contents <- function( + data, + display_currency +) { + dplyr::mutate( + data, + dplyr::across( + .cols = dplyr::everything(), + .fns = ~ gsub( + pattern = "_CUR_", + replacement = display_currency, + x = .x, + fixed = TRUE + ) + ) + ) } - - diff --git a/R/run_dashboard_workflow.R b/R/run_dashboard_workflow.R index 0a71c2f..c2af79b 100644 --- a/R/run_dashboard_workflow.R +++ b/R/run_dashboard_workflow.R @@ -81,4 +81,3 @@ run_dashboard_workflow <- function( } return(invisible(TRUE)) } - diff --git a/R/scenarios_found_in_sectors.R b/R/scenarios_found_in_sectors.R index c675ad1..447e5fb 100644 --- a/R/scenarios_found_in_sectors.R +++ b/R/scenarios_found_in_sectors.R @@ -1,7 +1,10 @@ -scenarios_found_in_sectors <- function(data, select_scenario_param, sectors) { - out <- (data$ald_sector %in% sectors) & - (data$scenario == get_scenario(select_scenario_param)) & - (data$scenario_source == get_scenario_source(select_scenario_param)) +scenarios_found_in_sectors <- function( + data, + select_scenario_param, + sectors +) { + out <- (data[["ald_sector"]] %in% sectors) & + (data[["scenario"]] == get_scenario(select_scenario_param)) & + (data[["scenario_source"]] == get_scenario_source(select_scenario_param)) out } - diff --git a/R/translate_column_contents.R b/R/translate_column_contents.R index 4a3ec71..0b12e0d 100644 --- a/R/translate_column_contents.R +++ b/R/translate_column_contents.R @@ -1,27 +1,30 @@ -translate_column_contents <- - function(data, dictionary, column, inplace = FALSE) { - dictionary_column <- - dictionary %>% - filter(.data$id_column == .env$column) %>% - select(-"id_column") +translate_column_contents <- function( + data, + dictionary, + column, + inplace = FALSE +) { + dictionary_column <- dictionary |> + dplyr::filter(.data[["id_column"]] == .env[["column"]]) |> + dplyr::select(-"id_column") - if (inplace) { - new_column <- column - } else { - new_column <- glue::glue(column, "_translation") - } - - data %>% - left_join( - dictionary_column, - by = rlang::set_names("translate_key", column) - ) %>% - mutate( - !!new_column := if_else( - is.na(.data$translate_value), - .data[[!!column]], - .data$translate_value - ) - ) %>% - select(-"translate_value") + if (inplace) { + new_column <- column + } else { + new_column <- glue::glue(column, "_translation") } + + data |> + dplyr::left_join( + dictionary_column, + by = rlang::set_names("translate_key", column) + ) |> + dplyr::mutate( + !!new_column := dplyr::if_else( + is.na(.data[["translate_value"]]), + .data[[!!column]], + .data[["translate_value"]] + ) + ) |> + dplyr::select(-"translate_value") +} diff --git a/R/translate_df_contents.R b/R/translate_df_contents.R index 9a6d33b..b497921 100644 --- a/R/translate_df_contents.R +++ b/R/translate_df_contents.R @@ -1,30 +1,34 @@ -translate_df_contents <- - function(data, id_data, dictionary, inplace = FALSE) { - if (!(id_data %in% dictionary$id_data)) { - rlang::abort( - class = "dataset not in dictionary", - glue::glue("the dataset {id_data} is not defined in translation dictionary.") - ) - } - - dictionary_subset <- - dictionary %>% - filter(.data$id_data == .env$id_data) %>% - transmute( - .data$id_column, - .data$translate_key, - .data$translate_value +translate_df_contents <- function( + data, + id_data, + dictionary, + inplace = FALSE +) { + if (!(id_data %in% dictionary[["id_data"]])) { + rlang::abort( + class = "dataset not in dictionary", + glue::glue( + "the dataset {id_data} is not defined in translation dictionary." ) + ) + } - for (column in unique(dictionary_subset$id_column)) { - data <- - translate_column_contents( - data = data, - dictionary = dictionary_subset, - column = column, - inplace = inplace - ) - } + dictionary_subset <- dictionary |> + dplyr::filter(.data[["id_data"]] == .env[["id_data"]]) |> + dplyr::transmute( + .data[["id_column"]], + .data[["translate_key"]], + .data[["translate_value"]] + ) - data + for (column in unique(dictionary_subset[["id_column"]])) { + data <- translate_column_contents( + data = data, + dictionary = dictionary_subset, + column = column, + inplace = inplace + ) } + + data +} diff --git a/R/translate_df_headers.R b/R/translate_df_headers.R index 7907e85..36c1ba1 100644 --- a/R/translate_df_headers.R +++ b/R/translate_df_headers.R @@ -1,26 +1,30 @@ -translate_df_headers <- - function(data, id_data, language_select, dictionary) { - language <- tolower(language_select) +translate_df_headers <- function( + data, + id_data, + language_select, + dictionary +) { + language <- tolower(language_select) - if (!(id_data %in% dictionary$id_data)) { - rlang::abort( - class = "dataset not in dictionary", - glue::glue("the dataset {id_data} is not defined in translation dictionary.") + if (!(id_data %in% dictionary[["id_data"]])) { + rlang::abort( + class = "dataset not in dictionary", + glue::glue( + "the dataset {id_data} is not defined in translation dictionary." ) - } + ) + } - column_tibble <- tibble(column_name = names(data)) + column_tibble <- dplyr::tibble(column_name = names(data)) - dictionary_subset <- - dictionary %>% - filter(.data$id_data == .env$id_data) %>% - transmute(.data$id_column, .data[[!!language]]) + dictionary_subset <- dictionary |> + dplyr::filter(.data[["id_data"]] == .env[["id_data"]]) |> + dplyr::transmute(.data[["id_column"]], .data[[!!language]]) - translated_headers <- - dictionary_subset %>% - left_join(column_tibble, by = c(id_column = "column_name")) + translated_headers <- dictionary_subset |> + dplyr::left_join(column_tibble, by = c(id_column = "column_name")) - names(data) <- translated_headers[[language]] + names(data) <- translated_headers[[language]] - data - } + data +} diff --git a/R/workflow.pacta.dashboard-package.R b/R/workflow.pacta.dashboard-package.R index 4fd1011..032eea1 100644 --- a/R/workflow.pacta.dashboard-package.R +++ b/R/workflow.pacta.dashboard-package.R @@ -2,47 +2,13 @@ "_PACKAGE" ## usethis namespace: start -#' @importFrom dplyr across -#' @importFrom dplyr all_of -#' @importFrom dplyr arrange -#' @importFrom dplyr bind_rows -#' @importFrom dplyr case_when -#' @importFrom dplyr desc -#' @importFrom dplyr distinct -#' @importFrom dplyr everything -#' @importFrom dplyr filter -#' @importFrom dplyr first -#' @importFrom dplyr group_by -#' @importFrom dplyr if_else -#' @importFrom dplyr inner_join -#' @importFrom dplyr join_by -#' @importFrom dplyr lag -#' @importFrom dplyr last -#' @importFrom dplyr left_join -#' @importFrom dplyr mutate -#' @importFrom dplyr mutate_at -#' @importFrom dplyr n -#' @importFrom dplyr pull -#' @importFrom dplyr reframe -#' @importFrom dplyr rename -#' @importFrom dplyr row_number -#' @importFrom dplyr select -#' @importFrom dplyr slice -#' @importFrom dplyr summarise -#' @importFrom dplyr tibble -#' @importFrom dplyr transmute -#' @importFrom dplyr ungroup #' @importFrom logger log_debug #' @importFrom logger log_error #' @importFrom logger log_info #' @importFrom logger log_trace #' @importFrom logger log_warn -#' @importFrom magrittr %>% #' @importFrom rlang := #' @importFrom rlang .data #' @importFrom rlang .env -#' @importFrom tidyr pivot_longer -#' @importFrom tidyr pivot_wider -#' @importFrom tidyr unite ## usethis namespace: end NULL diff --git a/inst/extdata/scripts/prepare_dashboard_data.R b/inst/extdata/scripts/prepare_dashboard_data.R index ceb6413..22946d7 100644 --- a/inst/extdata/scripts/prepare_dashboard_data.R +++ b/inst/extdata/scripts/prepare_dashboard_data.R @@ -1,7 +1,7 @@ logger::log_threshold(Sys.getenv("LOG_LEVEL", "INFO")) schema_tempdir <- tempdir() -workflow.pacta.dashboard:::prepare_schema_files( +workflow.pacta.dashboard::prepare_schema_files( directory = schema_tempdir ) @@ -12,18 +12,18 @@ params <- pacta.workflow.utils::parse_raw_params( system.file( "extdata", "parameters", package = "workflow.pacta.dashboard" - ), + ), system.file( "extdata", "parameters", package = "workflow.pacta" - ) + ) ), schema_file = file.path(schema_tempdir, "reportingParameters.json"), raw_schema_file = file.path(schema_tempdir, "rawParameters.json"), force_array = c("portfolio", "files") ) -manifest_info <- workflow.pacta.dashboard:::run_dashboard_workflow( +manifest_info <- workflow.pacta.dashboard::run_dashboard_workflow( params = params, raw_params = raw_params ) diff --git a/man/prep_techmix_sector.Rd b/man/prep_techmix_sector.Rd index f959926..d625fe6 100644 --- a/man/prep_techmix_sector.Rd +++ b/man/prep_techmix_sector.Rd @@ -7,8 +7,8 @@ prep_techmix_sector( equity_results_portfolio, bonds_results_portfolio, - indices_equity_results_portfolio, - indices_bonds_results_portfolio, + indices_eq_results_portfolio, + indices_cb_results_portfolio, peers_equity_results_portfolio, peers_bonds_results_portfolio, investor_name, @@ -27,10 +27,10 @@ prep_techmix_sector( \item{bonds_results_portfolio}{(data.frame) Portfolio-level results from \code{workflow.pacta} for corporate bonds} -\item{indices_equity_results_portfolio}{(data.frame) Benchmark results from +\item{indices_eq_results_portfolio}{(data.frame) Benchmark results from \code{workflow.pacta} for listed equity} -\item{indices_bonds_results_portfolio}{(data.frame) Benchmark results from +\item{indices_cb_results_portfolio}{(data.frame) Benchmark results from \code{workflow.pacta} for corporate bonds} \item{peers_equity_results_portfolio}{(data.frame) Peer group results from diff --git a/tests/testthat.R b/tests/testthat.R new file mode 100644 index 0000000..320e18b --- /dev/null +++ b/tests/testthat.R @@ -0,0 +1,12 @@ +# This file is part of the standard setup for testthat. +# It is recommended that you do not modify it. +# +# Where should you do additional test configuration? +# Learn more about the roles of various files in: +# * https://r-pkgs.org/testing-design.html#sec-tests-files-overview +# * https://testthat.r-lib.org/articles/special-files.html + +library(testthat) +library(workflow.pacta.dashboard) + +test_check("workflow.pacta.dashboard") diff --git a/tests/testthat/test-get_scenario.R b/tests/testthat/test-get_scenario.R new file mode 100644 index 0000000..1edd921 --- /dev/null +++ b/tests/testthat/test-get_scenario.R @@ -0,0 +1,44 @@ +test_that("get_scenario splits on underscore", { + scenario_string <- "SOURCE_SCENARIO" + results <- get_scenario(scenario_string) + expect_identical( + object = results, + expected = "SCENARIO" + ) +}) + +test_that("get_scenario respects case of original string", { + scenario_string <- "source_scenario" + results <- get_scenario(scenario_string) + expect_identical( + object = results, + expected = "scenario" + ) +}) + +test_that("get_scenario respects mixed case of original string", { + scenario_string <- "sOuRcE_ScEnArIo" + results <- get_scenario(scenario_string) + expect_identical( + object = results, + expected = "ScEnArIo" + ) +}) + +test_that("get_scenario extracts scenario name string with 1 underscore", { + scenario_string <- "GECO2022_1.5C" + results <- get_scenario(scenario_string) + expect_identical( + object = results, + expected = "1.5C" + ) +}) + +test_that("get_scenario extracts scenario name string with 2 underscores", { + scenario_string <- "WEO2022_NZE_2050" + results <- get_scenario(scenario_string) + expect_identical( + object = results, + expected = "NZE_2050" + ) +}) diff --git a/tests/testthat/test-get_scenario_source.R b/tests/testthat/test-get_scenario_source.R new file mode 100644 index 0000000..6f630d3 --- /dev/null +++ b/tests/testthat/test-get_scenario_source.R @@ -0,0 +1,44 @@ +test_that("get_scenario_source splits on underscore", { + scenario_string <- "SOURCE_SCENARIO" + results <- get_scenario_source(scenario_string) + expect_identical( + object = results, + expected = "SOURCE" + ) +}) + +test_that("get_scenario_source respects case of original string", { + scenario_string <- "source_scenario" + results <- get_scenario_source(scenario_string) + expect_identical( + object = results, + expected = "source" + ) +}) + +test_that("get_scenario_source respects mixed case of original string", { + scenario_string <- "sOuRcE_ScEnArIo" + results <- get_scenario_source(scenario_string) + expect_identical( + object = results, + expected = "sOuRcE" + ) +}) + +test_that("get_scenario_source extracts source name with 1 underscore", { + scenario_string <- "GECO2022_1.5C" + results <- get_scenario_source(scenario_string) + expect_identical( + object = results, + expected = "GECO2022" + ) +}) + +test_that("get_scenario_source extracts source name with 2 underscores", { + scenario_string <- "WEO2022_NZE_2050" + results <- get_scenario_source(scenario_string) + expect_identical( + object = results, + expected = "WEO2022" + ) +}) diff --git a/tests/testthat/test-replace_contents.R b/tests/testthat/test-replace_contents.R new file mode 100644 index 0000000..f494e94 --- /dev/null +++ b/tests/testthat/test-replace_contents.R @@ -0,0 +1,76 @@ +test_that("replace_contents replaces currency _CUR_ in column values", { + test_data <- data.frame( + id = LETTERS[1L:5L], + currency = "_CUR_", + stringsAsFactors = FALSE + ) + result <- replace_contents(test_data, "USD") + expect_identical( + object = result, + expected = data.frame( + id = LETTERS[1L:5L], + currency = "USD", + stringsAsFactors = FALSE + ) + ) +}) + +test_that("replace_contents replaces currency _CUR_ as substrings", { + test_data <- data.frame( + id = LETTERS[1L:5L], + currency = "Foo_CUR_ Bar", + stringsAsFactors = FALSE + ) + result <- replace_contents(test_data, "USD") + expect_identical( + object = result, + expected = data.frame( + id = LETTERS[1L:5L], + currency = "FooUSD Bar", + stringsAsFactors = FALSE + ) + ) +}) + +test_that("replace_contents operates on tibbles", { + test_data <- tibble::tibble( + id = LETTERS[1L:5L], + currency = "_CUR_" + ) + result <- replace_contents(test_data, "USD") + expect_identical( + object = result, + expected = tibble::tibble( + id = LETTERS[1L:5L], + currency = "USD" + ) + ) +}) + +test_that("replace_contents casts all columns as character", { + test_data <- data.frame( + id = LETTERS[1L:5L], + value = 1L:5L, + currency = "_CUR_", + stringsAsFactors = FALSE + ) + result <- replace_contents(test_data, "USD") + expect_true( + all( + vapply( + X = result, + FUN = is.character, + FUN.VALUE = logical(1L) + ) + ) + ) + expect_identical( + object = result, + expected = data.frame( + id = LETTERS[1L:5L], + value = as.character(1L:5L), + currency = "USD", + stringsAsFactors = FALSE + ) + ) +})