Showing posts with label japan. Show all posts
Showing posts with label japan. Show all posts

Thursday, May 30, 2013

If…then in Japan

If Japan starts to spiral out of control, then what do they do? A spiral would be a sudden move higher in JGB rates with a simultaneous crash in the Japanese Yen. Their response would be to try to slow the positive feedback loop through external intervention. Fortunately for Japan, they have amassed a significant reserve position of 1.2 trillion compared to a US reserve position of 135 billion, so they do have some firepower.
require(latticeExtra)
require(quantmod)

japanReserves <- getSymbols("TRESEGJPM052N", src = "FRED", 
    auto.assign = FALSE)
asTheEconomist(xyplot(japanReserves, scales = list(y = list(rot = 1)), 
    main = "Japan Foreign Reserves excluding Gold"))


From TimelyPortfolio

Based on data from the US Treasury, 1.1 trillion of the 1.2 trillion of Japanese foreign reserves are US Treasury bonds. If Japan decides (is forced) to liquidate, the only thing they have to liquidate are US Treasury bonds. Who will buy if they sell? What happens next?
# get data from US Treasury for top 10 foreign
# holders of US treasuries
foreignUSTreas <- read.csv("http://www.treasury.gov/resource-center/data-chart-center/tic/Documents/mfhhis01.csv", 
    skip = 4, nrows = 13, stringsAsFactors = FALSE)
top10 <- data.frame(foreignUSTreas[4:13, 1:2])
colnames(top10) <- c("Country", "Value")
top10$Value <- as.numeric(top10$Value)
top10$Country <- factor(top10$Country, levels = top10$Country[order(top10$Value)])

barchart(Country ~ Value, data = top10, origin = 0, 
    xlab = "Value (in $Billions)", main = "Foreign Holders of US Treasuries - Top 10", 
    scales = list(y = list(alternating = 3)), par.settings = theEconomist.theme(box = "transparent"), 
    lattice.options = theEconomist.opts())


From TimelyPortfolio



For those comparing the Federal Reserve H4 data to the US Treasury TIC data, this is a very good summary http://www.treasury.gov/resource-center/data-chart-center/tic/Pages/ticfaq2.aspx#q10.

Wednesday, May 15, 2013

Even More JGB Yield Charts with R lattice

See the last post for all the details. I just could not help creating a couple more.

Variations on Favorite Plot - Time Series Line of JGB Yields by Maturity

p2 <- xyplot(value ~ date | indexname, data = jgb.melt, 
type = "l", layout = c(length(unique(jgb.melt$indexname)),
1), panel = function(x, y, ...) {
panel.abline(h = c(min(y), max(y)))
panel.xyplot(x = x, y = y, ...)
panel.text(x = x[length(x)/2], y = max(y),
labels = levels(jgb.melt$indexname)[panel.number()],
cex = 0.7, pos = 3)
}, scales = list(x = list(tck = c(1, 0), alternating = 1),
y = list(tck = c(1, 0), lwd = c(0, 1))), strip = FALSE,
par.settings = list(axis.line = list(col = 0)),
xlab = NULL, ylab = "Yield", main = "JGB Yields by Maturity Since Jan 2012")
p2 <- p2 + layer(panel.abline(h = pretty(jgb.melt$value),
lty = 3))
p2


From TimelyPortfolio




jgb.xts.diff <- jgb.xts["2012::", ] - matrix(rep(jgb.xts["2012::",
][1, ], NROW(jgb.xts["2012::", ])), ncol = NCOL(jgb.xts),
byrow = TRUE)
jgb.diff.melt <- xtsMelt(jgb.xts.diff)
jgb.diff.melt$date <- as.Date(jgb.diff.melt$date)
jgb.diff.melt$value <- as.numeric(jgb.diff.melt$value)
jgb.diff.melt$indexname <- factor(jgb.diff.melt$indexname,
levels = colnames(jgb.xts))

p4 <- xyplot(value ~ date | indexname, data = jgb.diff.melt,
type = "h")

update(p2, ylim = c(min(jgb.diff.melt$value), max(jgb.melt$value) +
0.5)) + p4


From TimelyPortfolio



update(p2, ylim = c(min(jgb.diff.melt$value), max(jgb.melt$value) +
0.5), par.settings = list(axis.line = list(col = "gray70"))) +
update(p4, panel = function(x, y, col, ...) {
# do color scale from red(negative) to
# blue(positive)
cc.palette <- colorRampPalette(c(brewer.pal("Reds",
n = 9)[7], "white", brewer.pal("Blues",
n = 9)[7]))
cc.levpalette <- cc.palette(20)
cc.levels <- level.colors(y, at = do.breaks(c(-0.3,
0.3), 20), col.regions = cc.levpalette)
panel.xyplot(x = x, y = y, col = cc.levels,
...)
})


From TimelyPortfolio




p5 <- horizonplot(value ~ date | indexname, data = jgb.diff.melt,
layout = c(1, length(unique(jgb.diff.melt$indexname))),
scales = list(x = list(tck = c(1, 0))), xlab = NULL,
ylab = NULL)

p5



From TimelyPortfolio


update(p2, ylim = c(0, max(jgb.melt$value) + 0.5),
panel = panel.xyplot) + p5 + update(p2, ylim = c(0,
max(jgb.melt$value)))


From TimelyPortfolio


Variations on Yield Curve Evolution with Opacity Color Scale

# add alpha to colors
addalpha <- function(alpha = 180, cols) {
rgbcomp <- col2rgb(cols)
rgbcomp[4] <- alpha
return(rgb(rgbcomp[1], rgbcomp[2], rgbcomp[3],
rgbcomp[4], maxColorValue = 255))
}

p3 <- xyplot(value ~ indexname, group = date, data = jgb.melt,
type = "l", lwd = 2, col = sapply(400/(as.numeric(Sys.Date() -
jgb.melt$date) + 1), FUN = addalpha, cols = brewer.pal("Blues",
n = 9)[7]), main = "JGB Yield Curve Evolution Since Jan 2012")

p3 <- update(asTheEconomist(p3), scales = list(x = list(cex = 0.7))) +
layer(panel.text(x = length(levels(jgb.melt$indexname)),
y = 0.15, label = "source: Japanese Ministry of Finance",
col = "gray70", font = 3, cex = 0.8, adj = 1))

# make point rather than line
update(p3, type = "p")


From TimelyPortfolio



# make point with just most current curve as line
update(p3, type = "p") + xyplot(value ~ indexname,
data = jgb.melt[which(jgb.melt$date == max(jgb.melt$date)),
], type = "l", col = brewer.pal("Blues", n = 9)[7])


From TimelyPortfolio


Replicate Me with code at Gist

Japan - JGB Yields–More Lattice Charts

This blog is littered with posts about Japan. In one sentence, I think Japan presents opportunity and is a very interesting real-time test of much of my macro thinking. Proper visualization is absolutely essential for me to understand all of the dynamics. The R packages lattice and the new rCharts give me the power to see. I thought some of my recent lattice charts might help or interest some folks.

Get and Transform the Data

# get Japan yield data from the Ministry of
# Finance Japan data goes back to 1974

require(xts)
# require(clickme)
require(latticeExtra)

url <- "http://www.mof.go.jp/english/jgbs/reference/interest_rate/"
filenames <- paste("jgbcme", c("", "_2010", "_2000-2009",
"_1990-1999", "_1980-1989", "_1974-1979"), ".csv",
sep = "")

# load all data and combine into one jgb
# data.frame
jgb <- read.csv(paste(url, filenames[1], sep = ""),
stringsAsFactors = FALSE)
for (i in 2:length(filenames)) {
jgb <- rbind(jgb, read.csv(paste(url, "/historical/",
filenames[i], sep = ""), stringsAsFactors = FALSE))
}

# now clean up the jgb data.frame to make a jgb
# xts
jgb.xts <- as.xts(data.matrix(jgb[, 2:NCOL(jgb)]),
order.by = as.Date(jgb[, 1]))
colnames(jgb.xts) <- paste0(gsub("X", "JGB", colnames(jgb.xts)),
"Y")

# get Yen from the Fed
# getSymbols('DEXJPUS',src='FRED')

xtsMelt <- function(data) {
require(reshape2)

# translate xts to time series to json with date
# and data for this behavior will be more generic
# than the original data will not be transformed,
# so template.rmd will be changed to reflect


# convert to data frame
data.df <- data.frame(cbind(format(index(data),
"%Y-%m-%d"), coredata(data)))
colnames(data.df)[1] = "date"
data.melt <- melt(data.df, id.vars = 1, stringsAsFactors = FALSE)
colnames(data.melt) <- c("date", "indexname", "value")
# remove periods from indexnames to prevent
# javascript confusion these . usually come from
# spaces in the colnames when melted
data.melt[, "indexname"] <- apply(matrix(data.melt[,
"indexname"]), 2, gsub, pattern = "[.]", replacement = "")
return(data.melt)
# return(df2json(na.omit(data.melt)))

}

jgb.melt <- xtsMelt(jgb.xts["2012::", ])
jgb.melt$date <- as.Date(jgb.melt$date)
jgb.melt$value <- as.numeric(jgb.melt$value)
jgb.melt$indexname <- factor(jgb.melt$indexname, levels = colnames(jgb.xts))

Favorite Plot - Time Series Line of JGB Yields by Maturity

p2 <- xyplot(value ~ date | indexname, data = jgb.melt, 
type = "l", layout = c(length(unique(jgb.melt$indexname)),
1), panel = function(x, y, ...) {
panel.abline(h = c(min(y), max(y)))
panel.xyplot(x = x, y = y, ...)
panel.text(x = x[length(x)/2], y = max(y),
labels = levels(jgb.melt$indexname)[panel.number()],
cex = 0.7, pos = 3)
}, scales = list(x = list(tck = c(1, 0), alternating = 1),
y = list(tck = c(1, 0), lwd = c(0, 1))), strip = FALSE,
par.settings = list(axis.line = list(col = 0)),
xlab = NULL, ylab = "Yield", main = "JGB Yields by Maturity Since Jan 2012")
p2 + layer(panel.abline(h = pretty(jgb.melt$value),
lty = 3))



From TimelyPortfolio

Good Chart but Not a Favorite


As you can tell, I did not spend a lot of time formatting this one.

p1 <- xyplot(value ~ date | indexname, data = jgb.melt, 
type = "l")
p1




From TimelyPortfolio


Another Favorite - Yield Curve Evolution with Opacity Color Scale

# add alpha to colors
addalpha <- function(alpha = 180, cols) {
rgbcomp <- col2rgb(cols)
rgbcomp[4] <- alpha
return(rgb(rgbcomp[1], rgbcomp[2], rgbcomp[3],
rgbcomp[4], maxColorValue = 255))
}

p3 <- xyplot(value ~ indexname, group = date, data = jgb.melt,
type = "l", lwd = 2, col = sapply(255/(as.numeric(Sys.Date() -
jgb.melt$date) + 1), FUN = addalpha, cols = brewer.pal("Blues",
n = 9)[7]), main = "JGB Yield Curve Evolution Since Jan 2012")

update(asTheEconomist(p3), scales = list(x = list(cex = 0.7))) +
layer(panel.text(x = length(levels(jgb.melt$indexname)),
y = 0.15, label = "source: Japanese Ministry of Finance",
col = "gray70", font = 3, cex = 0.8, adj = 1))



From TimelyPortfolio

Replicate Me


code at Gist

Friday, March 22, 2013

Production Quality Report with R and knitr on Yen

Sometimes I actually use my experiments for real work.  For example, I wanted to send an update  on the Japanese Yen.  This was a great opportunity to use the chart created in Shading and Points with xtsExtra plot.xts.

I was fairly pleased with the finished product (click here if embed does not show).


R sweave file from GIST:

Thursday, February 28, 2013

Shading and Points with xtsExtra plot.xts

For some reason, I feel like have much better control with plot.xts function from the xtsExtra package described here over some of the other more refined R graphical packages. Maybe, it is just my simple mind, but recently I wanted to shade holding periods with points for buy and sale dates. With plot.xts from xtsExtra I was able to quickly and easily generate the following plot. I did have to slightly amend the original plot.xts function as seen here, but it seemed more natural and like much less of a struggle.

plot of chunk unnamed-chunk-1

I also enjoyed writing this post almost entirely in R markdown.

R code from Github:

Sunday, February 3, 2013

Japanese Government Bonds (JGB) Total Return Series

In a follow up to Yen and JGBs Short-Term vs Long Term and a series of posts on Japan, I thought the Bloomberg article "Japan Pension Fund’s Bonds Too Many If Abe Succeeds, Mitani Says" was particularly interesting.  It is difficult to find a total return series for the JGBS, so here is an example of how we might construct it in R with the JGB 9 year. Using the 9 year gets us about a decade more data than the 10 year.  The calculation is not perfect but it gets us very close.

The Japanese Pension Fund (GPIF) has been spoiled by a very pleasant ride with their JGBs.

From TimelyPortfolio

R code from GIST:

Friday, February 1, 2013

Yen and JGBs Short-Term vs Long Term

I have read some articles arguing that the recent move in the Japanese Yen is overdone.  However, considering the short-term without regard to the long-term context is naïve and potentially dangerous.  Although I do not have significant proof, I believe long-term mean reversion can completely dominate short-term mean reversion hopes.  Just to provide some longer-term context, I thought I would offer some graphical aids.

From TimelyPortfolio

In my mind, the Yen selloff is only in its infancy.  For the move to truly engage, I think we need Japanese Government Bond (JGB) yields to move higher also, and if it does we are in a different paradigm than the last 20 years.  But, what do I know?

R code from GIST:

Monday, October 22, 2012

Resurrect Posts on Japan and the Yen

As the Yen and Japan continue to get more interesting in my mind, I just wanted to resurrect some posts that I have done on Japan and the Yen and sort them by my favorites.

Japan Trade by Geographic Region
Japanese Trade and the Yen
Japan Intentional or Accidental Pursuit of Deflation
Japan Trade More Specifically with Korea

Just to add a chart, here is one using data from the Federal Reserve Bank of St. Louis (FRED).  While the extreme correlation between the Yen and the S&P 500 has limited the opportunity available in the Yen, the correlation has recently weakened as Japanese deficits have worsened and the Yen stopped getting stronger.

From TimelyPortfolio

R code:

require(latticeExtra)
require(quantmod)

getSymbols("DEXJPUS",src="FRED")
getSymbols("SP500", src="FRED")

asTheEconomist(xyplot(DEXJPUS,main="US Dollars for Japanese Yen Since 1970\nSource: Federal Reserve Bank of St. Louis"))

#merge the weekly returns of Yen and SP500
ret <- na.omit(merge(weeklyReturn(DEXJPUS),weeklyReturn(SP500)))
#use the rolling correlation method from PerformanceAnalytics chart.RollingCorrelation
rollcor <- as.xts(rollapply(ret, width = 208, FUN = function(x) cor(x[,
                     1, drop = FALSE], x[, 2, drop = FALSE]), by = 1,
                     by.column = FALSE, na.pad = FALSE, align = "right"))
xyplot(na.omit(merge(SP500,rollcor,DEXJPUS)),col=brewer.pal("RdBu",n=9)[c(9,2,8)],
              lattice.options=theEconomist.opts(),
              par.settings=theEconomist.theme(box="transparent"),
              scale=list(y=list(rot=0)),
              xlab=NULL,
              strip=strip.custom(factor.levels=c("S&P 500","Correlation (Rolling 4 Year) S&P 500 and USD/Yen","USD/Japanese Yen")),
              main = "S&P 500 and USD/Yen Since 1970\nSource: Federal Reserve Bank of St. Louis")

Tuesday, March 13, 2012

Japan Trade More Specifically with Korea

Macro analysis of Japanese trade in posts Japanese Trade and the Yen and Japan Trade by Geographic Region revealed some very interesting changes.  Since the Korean Won is so undervalued versus the Japanese Yen on a Purchasing Power Parity (PPP) basis, I was very interested in how this undervaluation might have affected Japanese and Korean trade between themselves and with the United States.  The 2008-2009 financial crisis ended the growing Japanese surplus with Korea, and currently the Japanese surplus with Korea is at its lowest level since January 2003.

From TimelyPortfolio

When we look at the Japanese and Korean deficits with the United States, we can see Korea has maintained the level of surplus achieved prior to the 2008-2009 financial crisis, while the Japanese surplus has eroded rapidly over that same time frame.

From TimelyPortfolio

If the Korean Won appreciates versus the Yen, will Korean exporters maintain their recent market share gains?  If the Korean Won appreciates versus the Yen, will there be any impact on the US $?  If there is unexpected inflation, will this exacerbate the Korean Won appreciation?

R Code from GIST:

Monday, March 12, 2012

Japan Trade by Geographic Region

To further the analysis presented in Japanese Trade and the Yen, I thought I would take the more granular data provided by the Japanese Ministry of Finance on trade by geographic region.  Of course, I will use R to read, analyze, and plot the .csv data.  Below you will see there are only two remaining regions where Japan has a trade surplus (North and South America), and those surpluses are declining very rapidly.

From TimelyPortfolio

R code from GIST:

Wednesday, March 7, 2012

Japanese Trade and the Yen

I have had the pleasure over the last couple of weeks to help plan the CFA Society of Alabama 2012 Dinner featuring Jim Rogers and Barron’s Senior Editor Jack Willoughby.  The event was fantastic, and I would like to publicly thank Jim Rogers and Jack Willoughby for investing so much time and effort into the State of Alabama.  Both are incredible men, and I was delighted to meet them.

Jack Willoughby challenged Jim Rogers’ statement “you must understand currencies” with the point that  leveraged forex trading that has grown popular is not suitable for investors.  Jim responded by saying currencies seem unsafe just like all investments seem unsafe before a bull run, and that with proper education and management, currencies represent outstanding opportunities.  I think both are right.

Over a year ago in Japan Intentional or Accidental Pursuit of Deflation, I contended that the persistently appreciating Yen was starting to pose an extreme competitive disadvantage to the Japanese exporters.  Korean electronic, auto, and appliance manufacturers (LG, Samsung, Hyundai, Kia, etc.) have exploded their market share in the US due to their huge pricing advantage over their Japanese neighbors discussed recently in Hyundai Motor Europe confident on 2012 goal

“…Japanese rival Toyota, which has been overshadowed by the success of South Koreans in Europe in recent years, said good products backed by a currency which is 'extremely competitive' make Hyundai and Kia outperform the market.

'It is probably the mirror of the yen,' Mr Alain Uyttenhoven, vice-president at Toyota Europe, told reporters, referring to the strong yen that hurt Japanese carmakers. “

Japan seems very slow to change, but the Yen seems to have finally found a limit as the Japanese now suffer a significant trade deficit with the world.  The Japanese no longer can pursue the harmful Yen policy of the past.  Instead of Yen to US$ and Euro, they should focus on the Yen versus their competing Asian currencies.

From TimelyPortfolio

The question then becomes does this represents an opportunity for investors, and if it does, how do you go from US stocks and bonds to a short Yen long emerging currency position?

R code from GIST:

Friday, January 13, 2012

Are We Japanese?

Most of the discussion trying to determine if the U.S. is Japan 20 years later focuses on the economy and the stock market.  However, one of the biggest and most persistent correlations between Japan and the U.S. are the Japanese Yen and the U.S. 10 Year Treasury Yield.  I think it is essential to really try to explore this relationship to help determine “How Japanese are we?”  With the US $ in decline, it is hard to imagine the continued persistence of this dynamic. (Thanks reader teramonagi for catching an error.)

From TimelyPortfolio

For additional thoughts on Japan, please see my post Japan Intentional or Accidental Pursuit of Deflation.

R code in GIST:

Thursday, February 3, 2011

Japan Intentional or Accidental Pursuit of Deflation

Japan’s intentional or accidental pursuit of deflation has caused an imbalance far greater than Bernanke’s pursuit of inflation.  Japanese policymakers have allowed Yen appreciation versus all other currencies.  It appears that they recognize a couple of things:

1) Higher interest rates and inflation represent a much bigger risk to their credit risk, deficit funding, and aging population than deflation.

2) Developed markets are saturated by Japanese goods, and further Yen appreciation does not cripple those exports.

However, by recognizing these two items, they are allowing their competition and potential growth engine in the emerging markets to completely take advantage of them.  Hyundai and Samsung in Korea have a 30-50% price advantage over their Japanese competition.

Japan’s desperate attempt to avoid their inevitable collapse from higher rates and inflation is speeding their collapse caused by emerging market competition.  The markets eventually will impose the adjustment to the Japanese situation.  At least Bernanke recognizes the imbalance caused by undervalued Asian currencies and knows that inflation is the only mechanism to force Asian emerging nations to allow their currencies to appreciate to normal valuation even if it means hard decisions for the US eventually.

Lower interest rates encourage imbalances, while higher interest rates force the changes necessary to correct these imbalances.

Since the absolute worst of the Asian collapse in 1997, is Japan better off than the emerging Asian nations?

image

Since 2007, is Japan better off than the emerging Asian nations?

image

As a point of reference, here is OECD’s calculation of Purchasing Power Parity for the Korea versus Japan 184, which means the Korean Won is undervalued versus the Japanese Yen by 84%.  The Economist’s Big Mac Index shows undervaluation of Asian currencies versus the Yen to be 40-50%.

The Japanese decision has been treated unkindly in the equity markets

via StockCharts.com

 

For the r geeks here is the code:

require(quantmod)
require(PerformanceAnalytics)

#get asian currency data from the FED FRED data series
getSymbols("DEXKOUS",src="FRED") #load Korea
getSymbols("DEXMAUS",src="FRED") #load Malaysia
getSymbols("DEXSIUS",src="FRED") #load Singapore
getSymbols("DEXTAUS",src="FRED") #load Taiwan
getSymbols("DEXCHUS",src="FRED") #load China
getSymbols("DEXJPUS",src="FRED") #load Japan

asian<-merge(DEXKOUS,DEXMAUS,DEXSIUS,DEXTAUS,DEXCHUS,DEXJPUS)

#do dailyReturn so that I can use pretty PerformanceAnalytics charts
#division puts currencies in Japanese yen from US dollar
asianreturn<-merge(dailyReturn(asian[,6]/asian[,1],subset="1996::"),dailyReturn(asian[,6]/asian[,2],subset="1996::"),dailyReturn(asian[,6]/asian[,3],subset="1996::"),dailyReturn(asian[,6]/asian[,4],subset="1996::"),dailyReturn(asian[,6]/asian[,5],subset="1996::"))

#label columns for graph legends
colnames(asianreturn)<-c("Korea","Malaysia","Singapore","Taiwan","China")

chart.CumReturns(asianreturn,ylim=c(-0.4,0.4),legend.loc="topright",main="Asian Currencies in Japanese Yen",ylab="",period.areas=list(c("Sep 97","Dec 97"),c("Jun 04","Nov 06"),c("Dec 07","Mar 09")),period.color="gray",event.lines=c("Dec 97","Nov 06","Mar 09"),event.labels=c("Asian Tiger Collapse","Carry Trade","Financial Crisis"),event.color="black")
mtext("Source: Federal Reserve FRED",side=1,adj=0)

chart.Drawdown(asianreturn['2006-11-30::',],legend.loc="right",main="Asian Currencies in Japanese Yen",ylab="Drawdown Since Financial Crisis")
mtext("Source: Federal Reserve FRED",side=1,adj=0)

 

 

3.5 hours