A Currency Graph

July 27, 2011

(This article was first published on mickeymousemodels, and kindly contributed to R-bloggers)

Here’s a graph in which nodes (and edges) represent currencies (and exchange rates):

currencies <- factor(c("EUR", "USD", "JPY", "GBP"))
df <- subset(expand.grid(from=currencies, to=currencies),
from != to)
GetExchangeRates <- function(from, to) {
urls <- sprintf("%s/d/quotes.csv?s=%s%s=X&f=b",
from, to)
GetRateFromUrl <- function(str) {
message("Reading from ", str)
tryCatch(read.csv(url(str), header=FALSE)[1, 1],
error = function(e) NA)
sapply(urls, GetRateFromUrl)
# If a url connection fails, the corresponding rate will be NA
df$rate <- GetExchangeRates(df$from, df$to)
g <- graph.data.frame(df, directed=TRUE)
g$layout <- layout.fruchterman.reingold(g)
E(g)$label <- E(g)$rate
V(g)$label <- V(g)$name
dev.new(width=10, height=10)
plot(g, main=sprintf("Exchange Rates on %s", Sys.Date()))

I’d like to emulate this post and look for profitable cycles using R. Here’s a first attempt:

# Look for negative-cost cycles
E(g)$weight <- -log(E(g)$rate)

In this case, the shortest.paths function complains that it “cannot run the Bellman-Ford algorithm” because a “negative loop [was] detected while calculating shortest paths” — great! There’s a negative-cost cycle in there somewhere. But what’s the easiest way to actually find that cycle using R — does anyone have any tips?

To leave a comment for the author, please follow the link and comment on their blog: mickeymousemodels.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

plotly webpage

dominolab webpage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training





CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)