[R] currency conversion function?

Henrique Dallazuanna wwwhsd at gmail.com
Thu Oct 15 18:59:42 CEST 2009


Hi Liviu,

Try this function now:

foo <- function(from, to, date){
       url <- "http://www.oanda.com/convert/classic?script=..%2Fconvert%2Fclassic&language=en&value=1"
     params <-
sprintf("%s&date=%s&exch=%s&exch2=&margin_fixed=0&expr=%s&expr2=&SUBMIT=Convert+Now&lang=en&date_fmt=us",
url, format(as.Date(date), "%m/%d/%y"), to, from)
       Lines <- readLines(params)
       value <- gsub(".*(.+[0-9]\\.[0-9]+).*", "\\1",
                      grep("nl", grep(from, grep(to, Lines, value =
TRUE), value = TRUE), value = TRUE))
       as.numeric(value)
}

foo('EUR', 'RUB', '2009-10-15')
foo('EUR', 'USD', '2009-10-15')

On Wed, Oct 14, 2009 at 1:45 PM, Liviu Andronic <landronimirc at gmail.com> wrote:
> Hello
>
> On 10/14/09, Henrique Dallazuanna <wwwhsd at gmail.com> wrote:
>>  foo('BRL', 'USD', '2009-10-14')
>>
> Nice function, thank you. Two issues, though:
> - it seems to provide reverse output. Example:
> ## how many dollars do you get "from" one euro?
>> foo('EUR', 'USD', '2009-10-14')
> [1] 0.67544
> ## however, the equivalent of 1 Euro would be ..
>> 1/foo('EUR', 'USD', '2009-10-14')
> [1] 1.4805
> ## .. dollars
> ## 1 Euro = 1.48051 US Dollar ## taken from the on-line converter
>
> The dirty hack is to use "1/as.numeric(value)" as a return value. For
> describing the next issue I will use the improved version of the
> function.
>
> - second issue, for weaker currencies (that is, with more digits) the
> reported value is not necessarily correct. Example:
> ## fine
>> foo('EUR', 'RUB', '2009-10-14')
> [1] 43.745
> ## fine
>> 1/foo('EUR', 'RUB', '2009-10-14')
> [1] 0.02286
> ## wrong
>> foo('RUB', 'EUR', '2009-10-14')
> [1] 0.26878
> ## taken from the on-line converter
> ## 1 Euro = 43.75188 Russian Rouble
> ## 1 Russian Rouble (RUB) = 0.02286 Euro (EUR)
>
> I am not sure on how to fix this one. Thank you
> Liviu
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O




More information about the R-help mailing list