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

library(igraph)

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",

"http://download.finance.yahoo.com",

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()))

savePlot("exchange_rate_graph.png")

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)

shortest.paths(g)

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?

*Related*

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: 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...