求R语言优化方案:按年度末汇率将多币种列批量转换为USD
简化年末汇率批量获取与币种转换流程
核心思路
一次性生成所有币种+所有年末日期的组合,批量获取汇率后通过关联原数据完成转换,避免重复循环每年的操作,让代码更简洁、可维护。
步骤1:生成所需的年末日期与币种组合
先定义年份范围和币种列表,生成每年12月31日的日期序列,再和币种列表生成全量组合:
library(priceR) library(dplyr) library(purrr) # 替换为你的18种币种列表 currency_codes <- c("EUR", "CAD", "GBP", ...) # 替换为你的11年范围(示例为2011-2021) target_years <- 2011:2021 # 生成每年年末日期(12-31) year_end_dates <- as.Date(paste0(target_years, "-12-31")) # 生成币种+日期的全量组合 currency_date_pairs <- expand.grid( currency = currency_codes, date = year_end_dates, stringsAsFactors = FALSE )
步骤2:批量获取汇率
利用pmap_dfr批量调用historical_exchange_rates,直接生成整洁的结构化汇率表:
# 批量拉取汇率并整理格式 exchange_rates_df <- pmap_dfr(currency_date_pairs, function(currency, date) { historical_exchange_rates( from = currency, to = "USD", start_date = date, end_date = date ) %>% mutate(currency = currency) %>% select(currency, date, usd_exchange_rate = one_unit_in_terms_of) })
注:
one_unit_in_terms_of列代表1单位对应币种可兑换的USD金额,直接用于后续乘法转换即可。
步骤3:关联原数据完成USD转换
假设你的原数据框raw_data包含:
currency:交易币种transaction_year:交易所属年份original_amount:原币种金额
通过年份匹配年末日期,关联汇率后计算USD金额:
# 转换为USD raw_data_usd <- raw_data %>% # 生成对应年份的年末日期,用于关联汇率 mutate(year_end_date = as.Date(paste0(transaction_year, "-12-31"))) %>% # 关联汇率表 left_join(exchange_rates_df, by = c("currency" = "currency", "year_end_date" = "date")) %>% # 计算USD金额 mutate(amount_usd = original_amount * usd_exchange_rate)
优化点:处理年末非工作日的情况
如果12月31日是周末/节假日,priceR会自动返回最近工作日的汇率,也可以主动用lubridate调整日期到最近工作日:
library(lubridate) year_end_dates <- as.Date(paste0(target_years, "-12-31")) %>% map_dbl(~ { # 周日(1)减2天,周六(7)减1天,其他保持原日期 ifelse(wday(.x) %in% c(1,7), .x - days(ifelse(wday(.x)==1,2,1)), .x) }) %>% as.Date()
内容的提问来源于stack exchange,提问作者maplesyrup123
相关产品推荐
相关产品推荐

