Showing posts with label currencies. Show all posts
Showing posts with label currencies. Show all posts

Friday, May 22, 2015

visNetwork, Currencies, and Minimum Spanning Trees

Just because I’m ignorant doesn’t mean I won’t try things.  Feel free to correct any ignorance that follows.  More than anything I would like to feature the new htmlwidget visNetwork.  I thought  the example from Minimum Spanning Trees in R applied to currency data (similar to this research paper Minimum Spanning Tree Application in the Currency Market) would be a good way to demonstrate this fancy new widget.  We’ll grab the currency data from FRED using quantmod code from this old post Eigen-who?.

Code

# get MST using code from this post
# https://mktstk.wordpress.com/2015/01/03/minimum-spanning-trees-in-r/

library(quantmod)
# #get currency data from the FED FRED data series
Korea <- getSymbols("DEXKOUS",src="FRED",auto.assign=FALSE) #load Korea
Malaysia <- getSymbols("DEXMAUS",src="FRED",auto.assign=FALSE) #load Malaysia
Singapore <- getSymbols("DEXSIUS",src="FRED",auto.assign=FALSE) #load Singapore
Taiwan <- getSymbols("DEXTAUS",src="FRED",auto.assign=FALSE) #load Taiwan
China <- getSymbols("DEXCHUS",src="FRED",auto.assign=FALSE) #load China
Japan <- getSymbols("DEXJPUS",src="FRED",auto.assign=FALSE) #load Japan
Thailand <- getSymbols("DEXTHUS",src="FRED",auto.assign=FALSE) #load Thailand
Brazil <- getSymbols("DEXBZUS",src="FRED",auto.assign=FALSE) #load Brazil
Mexico <- getSymbols("DEXMXUS",src="FRED",auto.assign=FALSE) #load Mexico
India <- getSymbols("DEXINUS",src="FRED",auto.assign=FALSE) #load India
USDOther <- getSymbols("DTWEXO",src="FRED",auto.assign=FALSE) #load US Dollar Other Trading Partners
USDBroad <- getSymbols("DTWEXB",src="FRED",auto.assign=FALSE) #load US Dollar Broad
#combine all the currencies into one big currency xts
currencies<-merge(Korea, Malaysia, Singapore, Taiwan,
China, Japan, Thailand, Brazil, Mexico, India,
USDOther, USDBroad)

currencies<-na.omit(currencies)

colnames(currencies)<-c("Korea", "Malaysia", "Singapore", "Taiwan",
"China", "Japan", "Thailand", "Brazil", "Mexico", "India",
"USDOther", "USDBroad")
#get daily percent changes
currencies <- currencies/lag(currencies)-1
currencies[1,] <- 0

cor.distance <- cor(currencies)
corrplot::corrplot(cor.distance)

library(igraph)
g1 <- graph.adjacency(cor.distance, weighted = T, mode = "undirected", add.colnames = "label")
mst <- minimum.spanning.tree(g1)
plot(mst)

library(visNetwork)
mst_df <- get.data.frame( mst, what = "both" )
visNetwork(
data.frame(
id = 1:nrow(mst_df$vertices)
,label = mst_df$vertices
)
, mst_df$edges
) %>%
visOptions( highlightNearest = TRUE, navigation = T )

Thursday, May 15, 2014

PDF Chart–> Inkscape SVG –> d3 Interactive Chart

I just spent the last couple of days updating myself on the newest research on currency management.  For the best real-time (delayed about a year) broad look, BIS puts out an incredibly helpful Triennial Central Bank Survey of foreign exchange... in which you see things like this

image

and this.

image

pdfs suffer from a lack of interactivity, so I thought why not use Inkscape’s PDF to SVG conversion to strip the above chart and make it SVG.  Then, if everything goes well, experiment with some basic interactivity provided by d3.js.  Here is what happened.

If anyone would like a more extensive write up of the process, please let me know.

Monday, January 27, 2014

Emerging Currencies with rCharts + FRED

I liked this chart a lot.

I thought I would show how we can semi-replicate it in R with rCharts.  Here it is with the currencies that are on FRED with dimplejs.

… and here with nvd3.

Code to replicate from Github Gist:

Wednesday, May 15, 2013

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

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:

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

Friday, August 17, 2012

GARCH Panel in plot.xts

I’m clearly out of my realm of competence with most of the rugarch functions, but I thought it might be nice to provide an example combining plot.xts and uGARCHroll.

image

R code from GIST:

Thursday, August 2, 2012

How do you say “We Will Do Whatever It Takes” in Thai?

As the market has already started to poke holes in Draghi’s promise, I thought it would be good to continue the series of posts that I began with the British version “We Will Do Whatever it Takes” with my favorite article written during the Asia Pacific crisis in 1997.

The Economist, “The baht spills over”: May 22, 1997

Too soon to crow

“Even if Thailand's troubles are in a regional class of their own, its neighbours still have reason to fear the knock-on effect of a successful onslaught on the baht. For now, Thailand has been crowing about a victory over the speculators. Mr Amnuay has even promised to bring interest rates, which have been kept high to protect the baht, down by two percentage points this year. It is as if a little guy, having survived one round with the big bullies, was dancing around with his fists up, saying, go on, hit me again.

They almost certainly will. The defence of the baht was achieved by a series of extraordinary measures that will be hard to sustain…”

A little graphical perspective might help us remember when this article was written.

image

For the entire set of Economist articles on Thailand during this period, go to http://www.economist.com/topics/thailand-1?page=33&%2524Version=0&%2524Path=%252F&%2524Domain=.economist.com.  Also, please read the incredibly thorough account of the 1997 crisis at The Nation blog.

If throughout financial market history, the central banks and politicians ever defeated the markets (greedy speculators), please let me know.  I am absolutely amazed at the confidence in central banks and politicians, especially in the United States.

 

R code:

#plot Thai baht
require(lattice)
require(latticeExtra)
require(quantmod)
getSymbols("DEXTHUS",src="FRED")
DEXTHUS <- 1/DEXTHUS["1995-01-01::1999-12-31",]
asTheEconomist(
  xyplot(DEXTHUS,
       panel = function (x,y,...) {
         panel.xyplot(x,y,...)
         panel.abline(v=index(DEXTHUS)[which(index(DEXTHUS)=="1997-05-22")],col="black", lty=3)
         panel.text(x=index(DEXTHUS)[which(index(DEXTHUS)=="1997-05-22")], y = 0.025, labels="Economist article The Baht Spills Over", col="indianred4", srt=90, pos=3)
       },
        main = "Thai Baht Before and After Crisis (1995-1999) \n source : Federal Reserve Bank of St. Louis")
)

Tuesday, July 31, 2012

“We Will Do Whatever it Takes”

When I first heard Draghi’s quote “We Will Do Whatever it Takes,”  I immediately thought that I should dig through some other good quotes from similarly positioned officials in financial history.  Let’s start with Prime Minister John Major in England 1992.

I found this clip reminding us of the 1992 British Pound devaluation.

http://news.bbc.co.uk/onthisday/hi/dates/stories/september/16/newsid_2519000/2519013.stm “The move is a dramatic U-turn in government policy, as only last week Prime Minister John Major reaffirmed the government's commitment to remaining within the mechanism.” (see his strong words below at the 2:34 mark)

Another near real-time view of Black Wednesday, September 16, 1992.

I think the last lines from the Atlantic June 4, 2010 article “Go For the Jugular” sum it up very well

“That evening, Lamont called a press conference in the Treasury's central courtyard. At 7:30 p.m., facing a massive battery of TV cameras from all over the world, he announced Britain's exit from the exchange-rate mechanism.

The markets had won, and the government had at last recognized it.”

Wednesday, July 25, 2012

Inspirational Stack Overflow Dendrogram Applied to Currencies

When I saw the answer to this Stack Overflow question, I immediately remembered working on my old post Clustering with Currencies and Fidelity Funds and just had to try to apply this technique.  As I should have guessed, it worked with only a minimal amount of changes.  Hoping to incrementally improve, I added a couple of slight modifications.

From TimelyPortfolio

R code from GIST (select raw to copy/paste):

Thursday, May 31, 2012

Conditional Drawdown Exploration

After reading Strub, Issam S., Trade Sizing Techniques for Drawdown and Tail Risk Control (May 21, 2012), I thought I should try to tie this with 2 other good R pieces on Conditional Drawdown:

http://systematicinvestor.wordpress.com/2011/11/01/minimizing-downside-risk/
http://www.rinfinance.com/agenda/2010/Carl+Peterson+Boudt_Tutorial.pdf

As always, NONE OF THIS IS INVESTMENT ADVICE.

In Strub’s paper, he uses conditional drawdown (CDaR) and conditional VaR (CVaR) to calculate the position size on directional (breakout determined) long/short currency positions.  The results were interesting enough to attempt to replicate with slight changes.  For this post, I will use CDaR to determine the position size on a long-only Mebane Faber 10-month moving average strategy.  We will start with an efficient frontier comparison and then abandon the frontier for a systematic approach.

(The blue text represents the added explanation in response to a comment)

If we look below at the frontier plots of return versus each measure of risk—the most common standard deviation, CDaR (conditional drawdown), and CVaR (conditional variance at risk)—we see that the frontiers are not noticeably different.  Visually, the most different and in a bad way, is the red CVaR line in the top left frontier plot.  The red CVaR line offers less return for each unit of standard deviation than the other two frontier lines, but the underperformance is not apparent when we use CDaR or CVaR on our x-axis as our measure of risk.

From TimelyPortfolio

Like the frontier plots above, the transition maps show only slightly different efficient allocations for each potential unit of risk.  At the lower end of the risk axis (left on the chart), we can see the biggest differences between allocations.

From TimelyPortfolio

The lack of noticeably different results seems consistent with well-known issues of mean-variance optimization.  These issues are described very well in this Morningstar piece.

“It is well known that mean-variance optimization is very sensitive to the estimates of returns, standard deviations, and correlations (see Michaud [1989] and Best and Grauer [1991]). Of these three inputs, returns are by far the most important and, unfortunately, the least stable. Chopra and Ziemba [1993] estimated that at a moderate risk tolerance level, mean-variance optimization is 11 times more sensitive to estimation error in returns relative to estimation error in risk (variance) and mean-variance optimization is two times more sensitive to estimation error in risk (variance) relative to estimation error in covariances (which also applies to correlations). Richard Michaud coined the phrase “the Markowitz optimization enigma” to describe the problem of input sensitivity and the highly concentrated asset allocations that result (see Michaud [1989]).

Input sensitivity indicates that the model’s output (the asset allocations) changes significantly due to small changes in the input (the capital market assumptions). Estimation error refers to the fact that in a forward-looking context the inputs are forecasts, and as such, are likely to be less than perfect (i.e. they contain errors). Putting these two issues together enables an uninformed practitioner to do more harm than good.”

For one more look at the lack of significant difference, let’s look at the cumulative returns of the 25th allocation from each efficient frontier.

From TimelyPortfolio

Even though the frontiers for the entire period are not significantly different, we can still use these more sophisticated risk measures in a different way to determine position size.  As a simple example similar to the example provided in Strub, let’s say we would like to pursue a Mebane Faber style 10-month moving average style long only position in each of the 3 currencies.  We would also like to limit the CDaR of each position to be 5%, so if we are fully allocated the sum of the 3 CDaR will be 15%. We will try to achieve this by using the 12 month rolling CDaR as our expected CDaR in the next month. Here is the chart of the 12 month rolling CDaR.

From TimelyPortfolio

If we just allocated 100% of the portfolio for each currency that exceeded its 10-month moving average, the results would look like this. Our maximum leverage across the portfolio would be 300%.

From TimelyPortfolio

However, if we would like to allocate more than 100% in quiet times and constrain our CDaR in volatile times, we can adjust our allocation by the 12 month rolling CDaR. As an example, if the New Zealand Dollar has a 15% CDaR for the last 12 months and we want 5% CDaR, we could allocate 33% or 15%historical/5%target to the New Zealand Dollar. This could result in a near infinite position size when CDaR is small, so we could also say that we want our maximum allocation to a single currency to be 200% or 600% at a portfolio level. The cumulative return chart would look like this.

From TimelyPortfolio
From TimelyPortfolio

I think it very unlikely that this would be a final allocation mechanism, and I certainly would not be comfortable with this, but I hope it offers some instructive building blocks upon which you can build an allocation system.

R code from GIST:

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:

Tuesday, January 17, 2012

Foreign Currencies and US 10y Treasury Yields

Since I explored the relationship between the Japanese Yen and the US 10y Treasury Yield on Friday, I thought it might be worthwhile to extend the exploration to a much broader range of currencies. I personally am most interested on how Asian Central Bank manipulation has affected the US 10y yield, and how if that changes what might be the impact to world markets. Please let me know your thoughts.

From TimelyPortfolio
From TimelyPortfolio

R code in 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:

Wednesday, October 12, 2011

Generosity of Asian Central Banks

The only thing that separates the United States from Europe and the notorious PIIGS is the generosity of Asian Central Banks who have been consistently quantitatively easing since 1998 (Join the Reserves).

From TimelyPortfolio

Without this generosity, the United States could very easily have entered a death spiral (see Death Spiral of a Country and Death Spiral Warning Graph) in 2008 and still might fall into this disastrous trap.

Deliberately attacking this very tenuous thread seems foolish, but this foolish action has found support with our fine politicians Washington Post "Senate approves China currency bill".  The US needs to recruit some US $ buyers, but unfortunately there are none to fill the multi-trillion dollar gap.

Even more concerning is the focus on China who has been steadily attacking the problem.  The focus on China does not make sense when you look at the appreciation of the Chinese Yuan.  I see a lot more Korean cars on the road and TVs and appliances in the stores, but I do not hear any mention of the extreme undervaluation of the Korean Won to the US$ but especially the Japanese Yen, so it appears the Koreans Won.

From TimelyPortfolio

I agree that the US$ reserve building needs to stop, but let’s not deliberately induce a positive feedback death spiral.

R code (click to download from Google Docs):

require(quantmod)
require(PerformanceAnalytics)

getSymbols("DEXCHUS",src="FRED")
getSymbols("DEXKOUS",src="FRED")

plot.zoo(merge(1/DEXCHUS,100/DEXKOUS)["1997::",],screens=1,lwd=2,
    col=c("lightblue4","antiquewhite4"),
    xlab="Year",ylab=NA,
    main="Chinese Yuan and Korean Won
    1997 to Sep 2011")
legend("right", c("China","Korea"), lwd = 2, bty="n",
    col=c("lightblue4","antiquewhite4"),y.intersp=2,
    text.col=c("lightblue4","antiquewhite4"))

Friday, September 30, 2011

Difficult Month for One of My Best Ideas

THIS IS NOT INVESTMENT ADVICE.  MY IDEAS PROBABLY WILL LOSE YOU MONEY, AND I WILL NOT LET YOU KNOW WHEN I CHANGE MY MIND.

Bloomberg’s article “Asian Currencies Set for Worst Month Since 1997 Crisis Caused IMF Bailouts” demonstrates why with all my bearishness I did not make much money this month.  Just as a reminder for the not so faithful readers, http://timelyportfolio.blogspot.com/2011/05/russell-napier-asip-in-ft-says-emerging.html shows why I like long emerging market stocks and short Russell 2000.  However, this trade does not work so well when the currencies get clobbered.  I understand the clobbering in 1997 when Soros and others had control of the Asian currencies, but 15 years 10 trillion since that crisis, the Asian central banks clearly have control of their currencies if they choose to exert that influence.  Billions in outflows are meaningless compared to the trillions sitting in foreign currencies (see post Join the Reserves), primarily the US $.

From TimelyPortfolio

R code:

require(quantmod)

#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
getSymbols("DEXTHUS",src="FRED") #load Thailand
getSymbols("DEXBZUS",src="FRED") #load Brazil
getSymbols("DEXMXUS",src="FRED") #load Mexico
getSymbols("DEXINUS",src="FRED") #load India
getSymbols("DTWEXO",src="FRED") #load US Dollar Other Trading Partners
getSymbols("DTWEXB",src="FRED") #load US Dollar Broad

par(mfrow=c(4, 3)) #provides 2 columns and 3 rows for charts
plot(1/coredata(DEXKOUS["1995::2011"]),type="l",ylab="Korea")
plot(1/coredata(DEXMAUS["1995::2011"]),type="l",ylab="Malaysia")
plot(1/coredata(DEXSIUS["1995::2011"]),type="l",ylab="Singapore")
plot(1/coredata(DEXTAUS["1995::2011"]),type="l",ylab="Taiwan")
plot(1/coredata(DEXCHUS["1995::2011"]),type="l",ylab="China")
plot(1/coredata(DEXJPUS["1995::2011"]),type="l",ylab="Japan")
plot(1/coredata(DEXTHUS["1995::2011"]),type="l",ylab="Thailand")
plot(1/coredata(DEXBZUS["1995::2011"]),type="l",ylab="Brazil")
plot(1/coredata(DEXMXUS["1995::2011"]),type="l",ylab="Mexico")
plot(1/coredata(DEXINUS["1995::2011"]),type="l",ylab="India")
plot(coredata(DTWEXO["1995::2011"]),type="l",ylab="US Dollar Other")
plot(coredata(DTWEXB["1995::2011"]),type="l",ylab="US Dollar Broad")

Wednesday, July 27, 2011

Join the Reserves

Most forget that the tremendous macro imbalances caused by the 10 Trillion in foreign reserves are just 14 years old phenomenon but the results have been and will be profound.  The buying started after the Asia Pacific collapse of 1997, and the Asian central banks chose to continuously engage a different form of quantitative easing that far exceeds Bernanke’s QE1 and QE2. Remember Greenspan’s “Conundrum” and the inability of Fed rate increases to push the long end of the curve higher.  Those artificially restrained rates persuaded money managers and institutions to seek higher returns in new products like CDOs and motivated additional housing demand from the US consumer.  These were both significant factors in the 2008 collapse.

Interest rates are a very effective negative feedback mechanism that helps control the cyclicality of the economy.  When nonmarket forces inhibit the normal functioning of interest rates, significant macro imbalances can cause severe consequences.  Unfortunately, it seems we still have not learned our lesson.

It is very odd to me that all the recent media and popular attention on the political debate gives an illusion of control to our inept politicians and causes us to forget that the market, primarily Asian central bank buyers, determines the limits of US fiscal and monetary policy.  I can only hope that somehow the US can maintain the very tenuous confidence we take for granted.

From TimelyPortfolio

R code (click to download):

#get reserve data from IMF
require(ggplot2)   url = "http://www.imf.org/external/np/sta/cofer/eng/cofer.csv"   cofer <- read.csv (url, skip=5)
cofer <- cofer[c(7:17),c(1,3:18)]
rownames(cofer) <- cofer[,1]
cofer <- cofer[,2:NCOL(cofer)]
#erase commas
col2cvt <- 1:NCOL(cofer)
cofer[,col2cvt] <- lapply(cofer[,col2cvt],
function(x){as.numeric(gsub(",", "", x))})
#erase spaces
rownames(cofer) <- gsub(" ", "", rownames(cofer))
#get numeric
col2cvt <- 1:NCOL(cofer)
cofer[,col2cvt] <- lapply(cofer[,col2cvt],
function(x){as.numeric(x)})
#get data frame and invert
cofer <- as.data.frame(t(cofer))
#convert years to dates to use
datestoformat <- rownames(cofer)
datestoformat <- as.Date(paste(substr(datestoformat,2,5),"-12-31",sep=""))
#prepare for ggplot
rownames(cofer) <- 1:NROW(cofer)
cofer <- cbind(datestoformat,cofer)
cofer_melt <- melt(cofer,id.vars=1)
colnames(cofer_melt) <- c("Date","Country","Amount")   #get area chart
jpeg(filename="oecd cofer reserves area chart.jpg",quality=100,
width=6.25, height = 6.25, units="in",res=96)
ggplot(cofer_melt,
aes(x=Date,y=Amount,fill=Country)) + geom_area() +
scale_fill_hue(l=40, c=65) +
opts(title="OECD Cofer Foreign Currency Reserves",
panel.background = theme_rect(colour="gray"))
dev.off()

Created by Pretty R at inside-R.org

Thursday, May 26, 2011

Clustering with Currencies and Fidelity Funds

Great news came yesterday with the release of the R In Finance 2011 Presentations.  I must attend next year after seeing all that I missed.  The Iacus: Statistical Analysis of Financial Time Series and Option Pricing in R (pdf) presentation offered a different method of clustering than that shown in yesterday’s post Eigen-who? How Can I Write About Eigen-anything and Expect You to Read?, so I thought it would be fun to quickly run his Markov Operator Distance example on the currency data from yesterday. As always, please comment liberally and point out any errors.  Mr. Iacus does not use the change but rather price in his analysis.  Knowing far less about these methods, I think using percentage change makes more sense.  I’ll use price first and then show results using percentage change.

From TimelyPortfolio
From TimelyPortfolio

As I said above, price is used, but I thought I should run on price change also.  These results make more sense to me since I know that the Chinese Yuan has been closely pegged to the US Dollar over the analysis period.

From TimelyPortfolio

A very good friend of mine has a 401k with various Fidelity mutual funds, so let’s run the same techniques on his set of Fidelity Fund options.  To avoid repetition, I will only run on price change rather than price.  I only included the equity fund options, so FPURX Fidelity Puritan with only 60% equities makes sense that it is all alone.

From TimelyPortfolio
From TimelyPortfolio
From TimelyPortfolio

R code:

#extends post on principal component analysis with MODist
#using example from http://www.rinfinance.com/agenda/2011/StefanoIacus.pdf
#on currency data and fidelity mutual fund data   require(quantmod)   #get currency data from the FED FRED data series
Korea <- getSymbols("DEXKOUS",src="FRED",auto.assign=FALSE) #load Korea
Malaysia <- getSymbols("DEXMAUS",src="FRED",auto.assign=FALSE) #load Malaysia
Singapore <- getSymbols("DEXSIUS",src="FRED",auto.assign=FALSE) #load Singapore
Taiwan <- getSymbols("DEXTAUS",src="FRED",auto.assign=FALSE) #load Taiwan
China <- getSymbols("DEXCHUS",src="FRED",auto.assign=FALSE) #load China
Japan <- getSymbols("DEXJPUS",src="FRED",auto.assign=FALSE) #load Japan
Thailand <- getSymbols("DEXTHUS",src="FRED",auto.assign=FALSE) #load Thailand
Brazil <- getSymbols("DEXBZUS",src="FRED",auto.assign=FALSE) #load Brazil
Mexico <- getSymbols("DEXMXUS",src="FRED",auto.assign=FALSE) #load Mexico
India <- getSymbols("DEXINUS",src="FRED",auto.assign=FALSE) #load India
USDOther <- getSymbols("DTWEXO",src="FRED",auto.assign=FALSE) #load US Dollar Other Trading Partners
USDBroad <- getSymbols("DTWEXB",src="FRED",auto.assign=FALSE) #load US Dollar Broad       #combine all the currencies into one big currency xts
currencies <- merge(Korea, Malaysia, Singapore, Taiwan,
China, Japan, Thailand, Brazil, Mexico, India,
USDOther, USDBroad)
currencies <- na.omit(currencies)
colnames(currencies) <- c("Korea", "Malaysia", "Singapore", "Taiwan",
"China", "Japan", "Thailand", "Brazil", "Mexico", "India",
"USDOther", "USDBroad")       #use MODist package as described in the fine presentation
#http://www.rinfinance.com/agenda/2011/StefanoIacus.pdf
require(sde)   currencies <- as.zoo(currencies)
d <- MOdist(currencies)
cl <- hclust( d )
groups <- cutree(cl, k=4)
plot(currencies, col=groups, main="Various Asian and American Currencies
1995-Current"
)
cmd <- cmdscale(d)
colnames(cmd) <- c("first coordinate","second coordinate")
plot( cmd, col=groups, main="MODist of Various Asian and American Currencies
1995-Current"
)
text( cmd, labels(d) , col=groups)   #struggling with whether price or percent change works better
#run again with percentage change
currencies <- ROC(currencies,1,type="discrete")
currencies[1,1:NCOL(currencies)] <- 0
currencies <- as.zoo(currencies)
d <- MOdist(currencies)
cl <- hclust( d )
groups <- cutree(cl, k=4)
cmd <- cmdscale(d)
colnames(cmd) <- c("first coordinate","second coordinate")
plot( cmd, col=groups, main="MODist of Various Asian and American Currencies
Percentage Change 1995-Current"
)
text( cmd, labels(d) , col=groups)     #do the same MODist for some Fidelity Funds
#except just use price change rather than price
tckr<-c("FBGRX","FCNTX","FDGFX","FEQIX","FEXPX",
"FFTYX","FFIDX","FDGRX","FDEGX","FLCSX",
"FMCSX","FOCPX","FDVLX","FSLSX","FIVFX",
"FOSFX","FRESX","FSEMX","FSTMX","FPURX")
start<-"1990-01-01"
end<- format(Sys.Date(),"%Y-%m-%d") # yyyy-mm-dd   # Pull tckr index data from Yahoo! Finance
getSymbols(tckr, from=start, to=end, adjust=TRUE)   fidelity<-na.omit(merge(to.weekly(FBGRX)[,4],to.weekly(FCNTX)[,4],
to.weekly(FDGFX)[,4] ,to.weekly(FEQIX)[,4],
to.weekly(FEXPX)[,4] , to.weekly(FFTYX)[,4],
to.weekly(FFIDX)[,4] , to.weekly(FDGRX)[,4],
to.weekly(FDEGX)[,4] , to.weekly(FLCSX)[,4],
to.weekly(FMCSX)[,4] , to.weekly(FOCPX)[,4],
to.weekly(FDVLX)[,4] , to.weekly(FSLSX)[,4],
to.weekly(FIVFX)[,4] , to.weekly(FOSFX)[,4],
to.weekly(FRESX)[,4] , to.weekly(FSEMX)[,4],
to.weekly(FSTMX)[,4] , to.weekly(FPURX)[,4]))   colnames(fidelity) <- substr(colnames(fidelity),1,5)   fidelity <- ROC(fidelity,1,type="discrete")
fidelity[1,1:NCOL(fidelity)] <- 0
fidelity <- as.zoo(fidelity)   d <- MOdist(fidelity)
cl <- hclust( d )
groups <- cutree(cl, k=5)
plot(fidelity, col=groups, main="Various Fidelity Mutual Funds
1998-Current"
)
cmd <- cmdscale(d)
colnames(cmd) <- c("first coordinate","second coordinate")
plot( cmd, col=groups, main="MODist of Various Fidelity Mutual Funds
1995-Current"
)
text( cmd, labels(d) , col=groups)   #get plot of eigenvalues since we have not done in any
#previous posts
#using techniques from corrgram package documentation
#get correlation matrix
(fidelity.cor <- cor(fidelity,use="pair"))
#get two largest eigenvectors
(fidelity.eig <- eigen(fidelity.cor)$vectors[,1:2])
e1 <- fidelity.eig[,1]
e2 <- fidelity.eig[,2]
#make the chart
plot(e1,e2,col='white', xlim=range(e1,e2), ylim=range(e1,e2),
main="Plot of 2 Largest Eigenvectors for Various Fidelity Funds")
arrows(0, 0, e1, e2, cex=0.5, col=groups, length=0.1)
text(e1,e2, rownames(fidelity.cor), cex=0.75, col=groups)

Created by Pretty R at inside-R.org