Tuesday, February 19, 2013

Onepager Now with knitR

Since at some point I had trouble with a conflict between knitr and the latex package textpos, I used the lesser Sweave in Another Experiment with R and Sweave.  I ran the Sweave2knitr command and discovered that textpos and knitr play well together now.  Here is the result using knitr (go to https://www.box.com/s/4nftk6qpa0cugapmncsn if the embed does not show below):

.rnw source file from Gist

\documentclass[nohyper,justified]{tufte-handout}
%\documentclass{article}
%\usepackage[absolute,showboxes]{textpos}
\usepackage[absolute]{textpos}
\usepackage{sidecap}
%\usepackage{color}
%\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\begin{document}
<<include=FALSE>>=
opts_chunk$set(concordance=TRUE)
@
\begin{wide}
\section{\Huge Performance Summary with knitR and R}
{\Large Here is a little experiment with R and Sweave to produce a performance report. I have done some samples in the past, but I wanted to iterate through a couple more, especially to evaluate other options for what has been started in the PApages package. Of course, this text could be easily replaced with some commentary from a manager about opportunities, thoughts, or current allocation. A dashboard set of charts also might be very helpful here.}
\hrulefill
\end{wide}
<<eval=TRUE,echo=FALSE,results='hide',warning=FALSE,message=FALSE,error=FALSE>>=
#do requires and set up environment for reporting
require(xtable)
require(ggplot2)
require(directlabels)
require(reshape2)
require(latticeExtra)
require(quantmod)
require(PerformanceAnalytics)
data(managers)
#get xts in df form so that we can melt with the reshape package
#will use just manager 1, sp500, and 10y treasury
managers <- managers[,c(1,8,9)]
#add 0 at beginning so cumulative returns start at 1
#also cumulative will match up datewise with returns
managers <- as.xts(rbind(rep(0,NCOL(managers)),coredata(managers)),
order.by=c(as.Date(format(index(managers)[1],"%Y-%m-01"))-1,index(managers)))
managers.df <- as.data.frame(cbind(index(managers),coredata(managers)),stringsAsFactors=FALSE)
#melt data which puts in a form that lattice and ggplot enjoy
managers.melt <- melt(managers.df,id.vars=1)
colnames(managers.melt) <- c("date","account","return")
managers.melt[,1] <- as.Date(managers.melt[,1])
#get cumulative returns starting at 1
managers.cumul <- as.xts(
apply(managers+1,MARGIN=2,FUN=cumprod),
#add end of first month to accommodate the 1 that we add
order.by=index(managers))
managers.cumul.df <- as.data.frame(cbind(index(managers.cumul),
coredata(managers.cumul)),
stringsAsFactors=FALSE)
managers.cumul.melt <- melt(managers.cumul.df,id.vars=1)
colnames(managers.cumul.melt) <- c("date","account","return")
managers.cumul.melt[,1] <- as.Date(managers.cumul.melt[,1])
#get rolling returns for 1y, 3y, 5y, since inception
trailing <- table.TrailingPeriods(managers, periods=c(12,36,60,NROW(managers)),FUNCS=c("mean"),funcs.names=c("return"))
trailing.df <- as.data.frame(cbind(c("1y","3y","5y","SinceIncep"),
c(rep("return",4)),
coredata(trailing)),
stringsAsFactors=FALSE)
trailing.melt <- melt(trailing.df,id.vars=1:2)
colnames(trailing.melt) <- c("period","measure","account","return")
#function to get numbers in percent format
#will use \\ to play well with tikz
percent <- function(x, digits = 2, format = "f", ...)
{
paste(formatC(100 * x, format = format, digits = digits, ...), "%", sep = "")
}
@
\begin{textblock*}{105mm}(15mm,70mm)
\begin{figure}
\vspace{0pt}
<<echo=FALSE,eval=TRUE,fig.width=8,fig.height=12>>=
charts.PerformanceSummary(managers,
colorset=c(brewer.pal(9,"Blues")[6],brewer.pal(8,"Greys")[c(5,4)]),
xlab=NULL)
@
\end{figure}
\end{textblock*}
\begin{textblock*}{75mm}(120mm,100mm)
\small Cumulative returns offer one of the best methods to evaluate the ability of a manager to achieve long term returns. Ultimately, the cumulative return is often one of the primary objectives of our clients.
\normalsize
\newline
\begin{figure}
\vspace{0pt}
<<echo=FALSE,eval=TRUE,results='asis'>>=
trailingtable <- apply(trailing,MARGIN=2,FUN=percent)
rownames(trailingtable) <- c("1y","3y","5y",paste("Since Inception ",format(index(managers)[1],"%b %Y")))
print(xtable(trailingtable), floating=FALSE, scalebox=0.7)
@
\end{figure}
\end{textblock*}
\begin{textblock*}{75mm}(120mm,152mm)
\small However, cumulative returns must also be evaluated with reference to the risks incurred to generate those returns. Below are multiple risk measures. We are most concerned with limiting drawdowns shown in the bottom left chart.
\normalsize
\newline
\begin{figure}
\vspace{0pt}
<<echo=FALSE,eval=TRUE,results='asis'>>=
risktable <- table.DownsideRisk(managers)
print(xtable(risktable), floating=FALSE, scalebox=0.6)
@
\end{figure}
\end{textblock*}
\end{document}

2 comments:

  1. Thanks a lot for sharing!

    got it to work right away with the following:

    ### Delete these 3 lines from onepager+with+knitR.Rnw
    <>=
    opts_chunk$set(concordance=TRUE)
    @

    Execute the following in R:

    ### Load the knitr package
    library(knitr)

    ### Set knitr options
    opts_chunk$set(echo=FALSE, concordance=TRUE)

    ### Create a dated file name for the output file
    onepagereportdated <- paste0("onepager+with+knitR_",format(Sys.time(),"%Y%m%d"),".tex")

    ### Run knitr on the .Rnw file to produce a .tex file
    knit("onepager+with+knitR.Rnw",output=onepagereportdated)

    ### Run texi2pdf on the .tex file within R or process it from your latex system
    tools::texi2pdf(onepagereportdated)

    ReplyDelete
  2. Playing around with this and your previous post on sweave, I discovered that:

    \section*{\Huge etc. --> okay

    \section{\Huge etc. --> not okay

    Omitting the star led to uninformative error messages and failure to compile altogether.

    It's most likely related to the tufte class, which I'm not familiar with.

    ReplyDelete