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:

require(quantmod)
require(xtsExtra)
require(reshape2)
library(rCharts)
#turn off rstudio viewer which is default now
options(viewer=NULL)
currencies <- c(
"DEXBZUS", #Brazil
"DEXINUS", #India
"DEXSFUS", #South Africa
"DEXMXUS" #Mexico
)
getSymbols(currencies, src="FRED")
currencies.xts <- na.omit(do.call(merge,lapply(currencies,get)))
#get inverse for emerging currency/US$
currencies.xts <- 1/currencies.xts
#do check for reasonableness
xtsExtra::plot.xts(currencies.xts["2007::",])
#get pct change from 2013
currencies.pct <-
currencies.xts["2013::",]/
matrix(
rep(
as.vector(head(currencies.xts["2013",],1)), #first day of the year
NROW(currencies.xts["2013::",]) #repeat for each row
),
ncol=length(currencies),
byrow=T
) - 1
#another reasonableness check
xtsExtra::plot.xts(currencies.pct)
xtsExtra::plot.xts(currencies.pct,screens=1)
currencies.df <- data.frame(
format(index(currencies.pct),"%Y-%m-%d"),
currencies.pct,
stringsAsFactors = FALSE
)
colnames(currencies.df) <- c("Date","Brazil","India","South Africa","Mexico")
currencies.df <- melt(currencies.df, id.vars=1)
colnames(currencies.df) <- c("Date","Country","ExchangeRate")
#dimple plot
d1 <- dPlot(
ExchangeRate ~ Date,
groups = "Country",
data = currencies.df,
type = "line"
)
d1$xAxis(
type = "addTimeAxis",
inputFormat = "%Y-%m-%d",
outputFormat = "%b %Y"
)
d1$yAxis(
outputFormat = "0.2%"
)
d1
#nvd3 plot
#convert date
currencies.df$Date = as.Date(currencies.df$Date)
n1 <- nPlot(
ExchangeRate ~ Date,
group = "Country",
data = currencies.df,
type = "lineWithFocusChart"
)
n1$xAxis(
tickFormat =
"#! function(d) {
return d3.time.format('%b %Y')(new Date(d * 86400000));
} !#"
)
n1$yAxis(tickFormat = "#!d3.format('0.2%')!#")
n1
view raw code.R hosted with ❤ by GitHub

Tuesday, January 21, 2014

What Do the Odds Say? Buy Stocks Begin of Year?

At some point in 2013, I read (can’t remember where) that 2012 was a rare year for the S&P 500  where no day’s closing  price was lower than the closing price  for the first day.  So if you bought on the first day of 2012, you never had a loss for the entire year.  Well, the same thing happened 2013, so I just had to do some analysis.  Below is a dimple.js chart built using rCharts with the minimum close price for the year divided by the close price for the first day of that year.

data source: Yahoo! Finance, Standard & Poors

Thursday, January 16, 2014

Retail Relative Strength

So back before Thanksgiving I did a post Something to Think About Before Black Friday | rChart + dygraphs.  Well since then I have noticed that Retail relative strength has deteriorated considerably.  I thought it would be a good time to use good old bfast (see posts) to look for a structural breakpoint.  Below is the output.  And yes, I do plan to make interactive eventually with rCharts.

image

The remainder is what I think is very interesting.

image

Code:

#analyze breakpoints with the R package bfast
#please read the paper
#Verbesselt J, Hyndman R, Newnham G, Culvenor D (2010)
#Detecting Trend and Seasonal Changes in Satellite Image Time Series.
#Remote Sensing of Environment, 114(1), 106–115.
#http://dx.doi.org/10.1016/j.rse.2009.08.014
require(bfast)
require(quantmod)
getSymbols("XRT",from="2000-01-01")
getSymbols("SPY",from="2000-01-01")
#get relative strenght as weekly log price
xrt_rs <- log(to.weekly(XRT[,6] / SPY[,6])[,4])
#need ts representation so do some brute force conversion
xrt_rs.ts <- ts(
as.vector(xrt_rs),
start=c(
as.numeric(format(index(xrt_rs[1,]),"%Y")), #year
as.numeric(format(index(xrt_rs[1,]),"%m")) #month
),
frequency=52
)
#look at the stl Seasonal-Trend decomposition procedure already in R
xrt_rs.stl <- stl(xrt_rs.ts,s.window="periodic")
plot(xrt_rs.stl,main="STL Decomposition of S&P 500")
#get the results from bfast
#adjusting h lower will result in more breakpoints
xrt_rs.bfast <- bfast(xrt_rs.ts,h=0.15,max.iter=1,season="none")
plot(
xrt_rs.bfast,
type="components",
ylim=c(3,max(xrt_rs)+1),
main="Retail Rel Strength with bfast Breakpoints and Components"
)
plot(
xrt_rs.bfast,
type="trend",
ylim=c(3,max(xrt_rs)+1),
main="Retail Rel Strength with bfast Trend Breakpoints"
)
#do some additional plotting
#[[1]] is used since for speed I only did one iteration
#could plot each iteration if I did multiple
plot(xrt_rs.bfast$Yt/xrt_rs.bfast$output[[1]]$Tt-1,
main="bfast Remainder as % of Retail Rel Strength",
xlab=NA, ylab="remainder (% of rel strength)",bty="l")
#add vertical line for the breakpoints
abline(v=breakdates(xrt_rs.bfast$output[[1]]$bp.Vt),col="gray70")
#add horizontal line at 0
abline(h=0,col="black",lty=2)
text(x=breakdates(xrt_rs.bfast$output[[1]]$bp.Vt),y=par("usr")[3]+.01,
labels=breakdates(xrt_rs.bfast$output[[1]]$bp.Vt,format.times=TRUE),
srt=90,pos=4,cex=0.75)
view raw code.R hosted with ❤ by GitHub

Wednesday, January 15, 2014

Popularity Contest

Although I am sure most of the bloggers that discuss R on R-bloggers are not all that concerned with popularity, I thought it would be interesting to analyze (with R and rCharts, of course) the popularity of these bloggers using Feedly’s API.

 

After building the chart, I got to thinking about these two excellent posts about the nature of blog popularity.

How many more R-bloggers posts can I expect? by Markus Gesmann

Blog posts' half life - why bother? by Bruce McPherson

Clearly not posting for a month (me) is not the way to fame and glory as Google search becomes the most common referrer.

image

Also, is Bruce McPherson onto something when he points out that the nature of a blog does not lend to permanence?  Should every blog, especially educational ones, also have a different view of the same content that lends itself better to permanence?

For those that missed me, I’m back.

R code to get Feedly API data and build dimplejs chart: Github repo