rcurrency-exchange-rates

Exchange Rate for specific date and currency on a data frame


I need for each observation (each with different currency and date-stamp) the exchange rate for the specifica date and curreny.

This is my code so far:

library(priceR)
library(ggplot2)
library(tidyverse)
library(tibble)
library(dplyr)

#Data frame
df <- data.frame(
  currency = c("DKK", "USD", "DKK"),
  price = c(580.9, 539.75, 567.8),
  Date = c("2020-01-01", "2020-02-15", "2020-03-15")
)

#Function to pull conversions
avg_ex <- function(x){
  historical_exchange_rates(x, to = "EUR",start_date = "2020-01-01", end_date = "2020-03-15") %>%
    `colnames<-`(c('date','conv')) %>% summarise(mean(conv)) %>% as.numeric
}

#Apply across all needed
conversions = sapply(unique(df$currency),avg_ex) %>% data.frame() %>% rownames_to_column() %>%
  `colnames<-`(c('currency','conv'))

#Join and convert
df %>% left_join(conversions,by='currency') %>%
  mutate(price_euro = price*conv)

  currency  price       Date      conv price_euro
1      DKK 580.90 2020-01-01 0.1338419   77.74876
2      USD 539.75 2020-02-15 0.9047106  488.31752
3      DKK 567.80 2020-03-15 0.1338419   75.99543

The output is nearly what i need. Except, that the conversion rate is acutal just the average from "2020-01-01" to "2020-03-15"

for example i need for the 1. Observation: 0.133754 instead on 0.1338419


Solution

  • Solution:

    #Data frame
    df <- data.frame(
      currency = c("USD", "DKK", "USD", NA),
      price = c(10, 11, 12, 13),
      date = as.Date(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01"))
    )
    head(df)
    
    #Function to pull conversions
    avg_ex <- function(x, y){
      if (is.na(x)) 0 
      else historical_exchange_rates(x, to = "EUR", start_date = y, end_date = y) %>%
        `colnames<-`(c('date','conv')) %>% summarise(conv) %>% as.numeric
    }
    
    
    #Apply across all needed
    df$conv = mapply(avg_ex, df$currency, df$date) %>% data.frame() %>% rownames_to_column() %>%
      `colnames<-`(c('currency','conv'))
    df