[This article was first published on mickeymousemodels, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Here’s a graph in which nodes (and edges) represent currencies (and exchange rates):Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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")
# 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?
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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.