Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Created March 7, 2012 22:18
Show Gist options
  • Save timelyportfolio/1996628 to your computer and use it in GitHub Desktop.
Save timelyportfolio/1996628 to your computer and use it in GitHub Desktop.
japan trade and yen
require(quantmod)
#get data from Japan Ministry of Finance website in csv form
url = "http://www.customs.go.jp/toukei/suii/html/data/d41ma.csv"
japantrade <- read.csv(url,skip=2,stringsAsFactors=FALSE)
#start cleaning data and getting in xts form
japantrade.xts <- japantrade[2:NROW(japantrade),]
#remove trailing 0 for future data
japantrade.xts <- japantrade.xts[which(japantrade.xts[,2]!=0),]
#get dates in yyyy-mm-dd form for xts
origdate <- japantrade.xts[,1]
xtsdate <- paste(substr(origdate,0,4),substr(origdate,6,8),"01",sep="-")
japantrade.xts <- as.xts(japantrade.xts[,2:3], order.by=as.Date(xtsdate))
plot.zoo(merge(japantrade.xts,japantrade.xts[,1]-japantrade.xts[,2]))
#get Japanese Yen data from St. Louis Fed Fred
getSymbols("EXJPUS",src="FRED")
#combine Yen data with Japanese trade data
tradeyen <- na.omit(merge(japantrade.xts,japantrade.xts[,1]-japantrade.xts[,2],1/EXJPUS))
colnames(tradeyen) <- c("Exports","Imports","SurplusDeficit","JPYUSD")
panel.special <- function(...) {
titles = c("Japan Imports and Exports","Surplus or Deficit","JPY/USD")
lines(...)
plotdata <- parent.frame()$x
panel.number <- parent.frame()$panel.number
if(panel.number==1) {
axis(side=4)
} else if(panel.number==2) {
abline(h=0,col="grey30",lwd=2)
axis(side=2)
} else {
axis(side=4)
}
title(main=titles[parent.frame()$panel.number],adj=0, line=-1,col="grey30")
}
#add another to color deficit points
deficit <- ifelse(tradeyen[,3]>0,0,tradeyen[,3])
plot.zoo(merge(tradeyen,deficit),screens=c(1,1,2,3,2),lwd=2,
ylab=NA, xlab=NA, yaxt="n",
panel=panel.special,
col=c("steelblue2","steelblue4","darkolivegreen3","gray40","indianred4"),
main="Japan Trade and the Yen",cex.main=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment