Showing posts with label pipeR. Show all posts
Showing posts with label pipeR. Show all posts

Tuesday, February 3, 2015

Financial Charts | Pan and Zoom

The htmlwidget for Week 2 over at Building Widgets claims to add pan and zoom interactivity to almost all R charts.  Since their were no tests on financial charts, I thought I would try it out on a couple.  It really does work. 

Here is an example on an efficient frontier plotted from fPortfolio.

When we combine pipeR and htmlwidgets, we get a solid result from what I think is fairly elegant and understandable code.

svgPanZoom(
svgPlot({
returns %>>%
(cumprod( 1 + . )) %>>%
(.[endpoints(.,"months")]) %>>%
( ./lag(.,k=1) - 1 ) %>>%
chart.SnailTrail(
colorset = RColorBrewer::brewer.pal(9,"Set1")[-6]
,add.names="none"
,width = 36
,step = 36
,legend.loc = "topright"
)
},height= 10, width = 16)
)

An even more challenging test was chartSeries, and svgPanZoom still passed the test beautifully. See if it works on your machine.


getSymbols("SPY")
svgPanZoom(svgPlot({chartSeries(SPY)},width = 12, height = 8))

If you would like to reproduce the plots, all the code is in this Gist.

Monday, November 24, 2014

Pipeline to Plot Annual % Change

image

(thanks tradeblotter for pointing out error in code in first release)

Pipes in R make my life incredibly easy, and I think my code easier to read.   Note, there are a couple different flavors of pipes (see magrittr and pipeR).  For now, I choose pipeR.

library(quantmod)
library(pipeR)
library(ggplot2)

getSymbols("^GSPC",from="1900-01-01",auto.assign=F) %>>% #get S&P 500 from Yahoo!Finance
( .[endpoints(.,"years"),4] ) %>>% #get end of year
ROC( type="discrete", n=1 ) %>>% #get one year rate of change
na.fill(0) %>>% #fill first year with 0
( #make data.frame
data.frame(
date = as.Date(format(index(.),"%Y-01-01"))
,.
)
) %>>%
structure( #hard way to do colnames()
names = c("date","change")
) %>>%
ggplot( #start our plot pipe
aes( y= change, x= date)
) %>>%
+ geom_bar( stat="identity" ) %>>% #choose bar
+ labs( title = "Annual Change of the S&P 500" ) #give plot a title

Or if we wanted to use the new pipeline syntax for the plot portion.

library(quantmod)
library(pipeR)
library(ggplot2)

getSymbols("^GSPC",from="1900-01-01",auto.assign=F) %>>% #get S&P 500 from Yahoo!Finance
( .[endpoints(.,"years"),4] ) %>>% #get end of year
ROC( type="discrete", n=1 ) %>>% #get one year rate of change
na.fill(0) %>>% #fill first year with 0
( #make data.frame
data.frame(
date = as.Date(format(index(.),"%Y-01-01"))
,.
)
) %>>%
structure( #hard way to do colnames()
names = c("date","change")
) %>>%
(
pipeline({
ggplot(., aes( y= change, x= date) )
+ geom_bar( stat="identity" )
+ labs( title = "Annual Change of the S&P 500 (source: Yahoo! Finance)" )
})
)

Monday, October 6, 2014

Popular Mutual Funds Decomposed With Ekholm (2014)

While we have a foundation and momentum from the last post “SelectionShare & TimingShare | Masterfully Written by Delightfully Responsive Author” , we can run the Ekholm calculations on some popular funds to see how they have evolved since the early 1980s.  Remember these are my opinions and not investment advice.  I chose these four funds for

  1. popularity in terms of Assets Under Management (AUM)
  2. style (active)
  3. tenure (old)
  4. evolution ( 2 evolved in a bad way and 2 have stayed consistent in a good way ).

This will continue what I envision to be a whole series of posts experimenting with the Ekholm (2014) decomposition into SelectionShare and TimingShare and determining how to use it in a mutual fund selection process.  Just as a reminder, below is the link to the very well-done paper by Anders Ekholm.

Ekholm, Anders G.

Components of Portfolio Variance: Systematic, Selection and Timing

August 8, 2014

http://ssrn.com/abstract=2463649

See if you can make any conclusions after reading the paper and looking at the chart below on the 2 year rolling Ekholm decomposition of FPA Crescent ®  Fund (FPACX), Sequoia ® Fund (SEQUX), Fidelity ® Contrafund ® (FCNTX), and The Growth Fund of America ®   (AGTHX).

image

As always, I really would like for you to reproduce and extend.  Please let me know if you do.  Below is the code.

# perform Ekholm (2012,2014) analysis on some popular mutual funds

# Ekholm, A.G., 2012
# Portfolio returns and manager activity:
# How to decompose tracking error into security selection and market timing
# Journal of Empirical Finance, Volume 19, pp 349-€“358

# Ekholm, Anders G., July 21, 2014
# Components of Portfolio Variance:
# R2, SelectionShare and TimingShare
# Available at SSRN: http://ssrn.com/abstract=2463649


library(Quandl) # use to get Fama/French factors
library(pipeR) # pipes are the future or R
library(rlist) # rlist - like underscore/lodash for R lists
library(dplyr) # super fast and really powerful
library(tidyr) # next gen wide/long formatter package
library(latticeExtra) # old but still awesome
library(directlabels) # fantastic and works with ggplot & lattice
library(quantmod) # also will load xts

# use Quandl Kenneth French Fama/French factors
# http://www.quandl.com/KFRENCH/FACTORS_D
f <- Quandl("KFRENCH/FACTORS_D",type = "xts") / 100

# grab our function from post
# http://timelyportfolio.blogspot.com/2014/10/selectionshare-timingshare-masterfully.html
devtools::source_gist("e5728c8c7fb45dbdb6e0")

tickers <- c( "FCNTX", "AGTHX", "SEQUX", "FPACX" )
ekFunds <- lapply(
tickers
,function(ticker) {
ticker %>>%
getSymbols( from = "1896-01-01", auto.assign = F ) %>>%
(fund ~
structure(
fund[,6] / stats::lag( fund[,6], 1 ) - 1
,dimnames = list(NULL,gsub(x = colnames(fund)[6], pattern = "[\\.]Adjusted", replacement = ""))
)
) %>>%
merge( f ) %>>% # Quandl("KFRENCH/FACTORS_D",type = "xts") / 100
na.omit %>>%
rollapply (
FUN= function(x){
x %>>%
jensen_ekholm %>>%
( data.frame( summary(.[["linmod"]])$"r.squared" , .$ekholm ) ) %>>%
xts(order.by=tail(index(x),1)) -> return_df
colnames(return_df)[1] <- "R_sq"
return(return_df)
}
, width = 500
#, by = 100
, by.column=F
, fill = NULL
) %>>%
na.fill(0)
}
)
names(ekFunds) <- tickers

ekFunds %>>%
list.map(
{
structure(
data.frame(
date = index(.)
, fund = names(ekFunds)[.i]
, .
)
) %>>%
gather(measure,value,-date,-fund)
}
) %>>%
(
do.call( rbind , . )
) -> ekT

ekT %>>%
# just plot at R^2, SelectionShare, and TimingShare
filter( measure %in% c("R_sq","SelectionShare","TimingShare") ) %>>%
(
xyplot(
value ~ date | measure
, groups = fund
, data = .
, type = "l"
# using direct.label so not necessary
, auto.key = list( space = "right" )
# title our plot
, main = paste(
"Comparison of Ekholm Decomposition for Various Mutual Funds"
,paste0("2 Year Rolling since ",format(.$date[1],format="%b %d, %Y"))
,sep="\n"
)
# layout one on top of the other
, layout = c(1,length(unique(.$measure)))
)
) %>>%
# I like labels on plot rather than legend
directlabels::direct.label( method = "last.qp" ) %>>%
# pretty it up with the latticeExtra Economist theme
asTheEconomist

Wednesday, July 30, 2014

Refresh Old rCharts+flickr post with httr and pipeR

The R world keeps moving, and I noticed this old post didn’t work anymore, so I have rewritten it to use Hadley Wickham's httr instead of Rflickr for two reasons:

  1. Rflickr is not working for me anymore
  2. httr is a very helpful package for navigating the "what was scary to me" world of http and oauth

In addition to the changes above, I will also demonstrate use of the pipeR package from Kun Ren who has been quite prolific lately. I feel pretty strongly I will be rewriting this post one more time in the near future (already done) employing his rlist package.

image