knitr Performance Report-Attempt 2

[This article was first published on Timely Portfolio, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Over the years I have changed my learning process from reading thoroughly first before proceeding to reading minimally and then applying immediately.  I very quickly see the gaps in my knowledge.  This method is far more painful but seems to quicken progress up the learning curve.  You will definitely see the process in its entirety with this series on latex, knitr, and performance reporting.  For those who are still hesitating, jump right in with me and let me know your result.

As I experimented with Attempt 2, I could see from others sample .Rnw files that LyX can serve as the IDE for Sweave/knitr documents, and I thought this would be a more pleasant route.  However it was not, and I eventually reverted back to old-school manual coding.  This post from R, Ruby, and Finance talks about TeXnic Center as an IDE.  Maybe I will try it for attempt 3. I am still a long way from a useable result (any bets on how many attempts it takes?), but the report is definitely an improvement

In Attempt 2, I used the echo=FALSE option to not output the R code on the final pdf report.  However, the code is still all there for public view within the .Rnw file.

I just remembered that ttrTests offers a Latex output option. Just what I need–another distraction. Look for that in future posts.

R code from GIST:
require(knitr)
knit2pdf("knitr performance 2.rnw")
%% LyX 2.0.2 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english,nohyper,noae]{tufte-handout}
\usepackage{helvet}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{babel}
\usepackage[unicode=true,pdfusetitle,
bookmarks=true,bookmarksnumbered=true,bookmarksopen=true,bookmarksopenlevel=1,
breaklinks=true,pdfborder={0 0 0},backref=false,colorlinks=false]
{hyperref}
\usepackage{breakurl}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
\title{knitr Performance Summary Attempt 2}
\author{Timely Portfolio}
\providecommand{\LyX}{\texorpdfstring%
{L\kern-.1667em\lower.25em\hbox{Y}\kern-.125emX\@}
{LyX}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
<<echo=F>>=
if(exists(".orig.enc")) options(encoding = .orig.enc)
@
\makeatother
\begin{document}
\maketitle
\begin{abstract}
This time we will try to incorporate some \LyX{} brilliance to help
us format the end result. Unfortunately, this process (most likely
due to my ignorance) was not nearly as seamless as the first experiments
with knitr. I eventually went back to old-school manual coding in RStudio.
\end{abstract}
\section{Performance Overview}
We all know that performance reports generally blend both text tables
and graphical charts to communicate. In this example, we will use
two of the most popular Vanguard funds (vbmfx and vfinx) as the subjects
for our performance evaluation.
<<setup,eval=TRUE,echo=FALSE, warning=FALSE,message=FALSE, results='hide'>>=
require(quantmod)
require(PerformanceAnalytics)
getSymbols("VFINX",from="1990-01-01",adjust=TRUE)
getSymbols("VBMFX",from="1990-01-01",adjust=TRUE)
perf <- na.omit(merge(monthlyReturn(VBMFX[,4]),monthlyReturn(VFINX[,4])))
colnames(perf) <- c("VBMFX","VFINX")
@
<<lattice-chart,echo=FALSE,eval=FALSE,tidy=TRUE,warning=FALSE,message=FALSE>>=
require(lattice)
require(latticeExtra)
require(reshape2)
#note: table.CalendarReturns only handles monthly data
perf.annual<-as.data.frame(table.CalendarReturns(perf)[,13:14])
perf.annual<-cbind(rownames(perf.annual),perf.annual)
perf.annual.melt <- melt(perf.annual,id.vars=1)
colnames(perf.annual.melt)<-c("Year","Fund","Return")
p1 <- dotplot(Year~Return,group=Fund,data=perf.annual.melt,
pch=19,
lattice.opts=theEconomist.opts(),
par.settings = theEconomist.theme(box = "transparent"),
main="Annual Returns of VFINX and VBMFX",
auto.key=list(space="right"),
xlim=c(min(perf.annual.melt[,3]),max(perf.annual.melt[,3])))
p2 <- densityplot(~Return, group=Fund, data=perf.annual.melt,
lattice.opts=theEconomist.opts(),
par.settings = theEconomist.theme(box = "transparent"))
print(p1,position=c(0,0,0.6,1),more=TRUE)
print(p2+p1,position=c(0.6,0,1,1))
@
<<ref.label='lattice-chart',echo=FALSE,fig.height=4.75,fig.width=7,warning=FALSE,message=FALSE>>=
@
<<xtable-table,echo=FALSE,eval=TRUE,results='tex',tidy=TRUE,warning=FALSE,message=FALSE>>=
require(xtable)
print(xtable(t(last(table.CalendarReturns(perf)[,13:14],13))), floating=FALSE)
@
\newpage
\section{Risk and Return}
Although the summary and distribution of annual returns is a good first step, any real due diligence will require much more than just return. Let's do a very basic plot of risk and return. Of course, there are much more sophisticated methods, which we will explore in future versions.
\begin{figure}
<<chart-stats,echo=FALSE,eval=TRUE,tidy=TRUE,warning=FALSE,message=FALSE,fig.height=4.75,fig.width=7>>=
perf.stats <- table.Stats(perf)
#eliminate observations,na,skewness,and kurtosis
perf.stats <- perf.stats[3:(NROW(perf.stats)-2),]
perf.stats.melt <- melt(as.data.frame(cbind(rownames(perf.stats),perf.stats),stringsAsFactors=FALSE),id.vars=1)
colnames(perf.stats.melt)<-c("Statistic","Fund","Value")
barchart(Statistic~Value,group=Fund,data=perf.stats.melt,
origin=0,
lattice.opts=theEconomist.opts(),
par.settings=theEconomist.theme(box="transparent"),
main="Risk and Return Statistics")
@
\end{figure}
\section{Diversification}
In today's markets with almost universally high positive correlations, diversification is much more difficult. However, most performance reports should include some analysis of both correlation and diversification.
\begin{figure}
<<chart-correlation,echo=FALSE,eval=TRUE,tidy=TRUE,warning=FALSE,message=FALSE,fig.height=4,fig.width=6>>=
chart.Correlation(perf, main="Correlation Analysis")
@
<<chart-rollingcorrelation,echo=FALSE,eval=TRUE,tidy=TRUE,warning=FALSE,message=FALSE,fig.height=4,fig.width=6>>=
chart.RollingCorrelation(perf[,1],perf[,2],main="VBMFX and VFINX Rolling 12 Month Correlation",xlab="Correlation")
@
\end{figure}
\begin{figure}
<<chart-diversification,echo=FALSE,eval=TRUE,tidy=TRUE,warning=FALSE,message=FALSE,fig.height=5,fig.width=6,fig.keep="last">>=
require(fPortfolio)
frontier <- portfolioFrontier(as.timeSeries(perf))
frontierPlot(frontier,pch=19,title=FALSE)
singleAssetPoints(frontier,col=c("steelblue2","steelblue3"),pch=19,cex=2)
title(main="Efficient Frontier with VBMFX and VFINX",adj=0)
@
\end{figure}
\end{document}

To leave a comment for the author, please follow the link and comment on their blog: Timely Portfolio.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)