You are on page 1of 50

Performance Analysis in R

R/ inance !or"shop
Peter Carl Brian Peterson
April 24, 2009 Chicago, IL

Authors of PerformanceAnalytics

#utline
Intro$uction

A%out PerformanceAnalytics

Performance Analysis

&ypes of Analysis

'easures an$ Calculations


'easuring Return Assessing Ris" ()aluating Relati)e Performance (*amining +tyle (*posures

Appen$i*, Buil$ing Bloc"s


-ata .raphics &a%les


R/Finance 2009 2

24 Apr 2009

A%out PerformanceAnalytics
Li%rary of econometric functions for performance an$ ris" analysis of financial portfolios/ Aims to %e useful to %oth practitioners an$ researchers ali"e/ Analysis of return streams, 0hether $istri%ute$ normally or not/ In $e)elopment since early 2001, pac"age$ an$ first release$ to CRA2 in 2003/ 2o0 contains more than 450 functions an$ more than 44,000 lines of co$e an$ 3,600 lines of $ocumentation/ Colla%oration, patches an$ suggestions from users in in$ustry an$ aca$emia 0orl$0i$e

24 Apr 2009

R/Finance 2009

PerformanceAnalytics
CRAN Version 0.9.7.1
+harpe7s +tyle Analysis +nailtrail chart 8aR +ensiti)ity chart 'o$ifie$ (*pecte$ +hortfall 'ulti)ariate moments an$ ris" metrics 9igher co:moments Ro%ust $ata cleaning 'any fe0er $epen$encies #ther ne0 functions, %ug fi*es

Release 1.0
Component 8aR an$ Component (*pecte$ +hortfall !rappers of 8aR an$ (+ functions for consistency A$option of *ts for time series Impro)e$ *:a*is han$ling in charts ormatte$ ta%les in $e)ices Capture ratios an$ other metrics Bug fi*es, ne0 functions

24 Apr 2009

R/Finance 2009

Analy;ing Performance in inance

!hat

24 Apr 2009

R/Finance 2009

Performance Analysis in inance !hat are 0e trying to accomplish< Accrue e)i$ence to help as" %etter =uestions

Is this something I 0ant in my portfolio< !hat is the ris" of in)esting< 9o0 $o I ma*imi;e my e*pecte$ gain an$ minimi;e my chances of going %ro"e< Is this manager 0orth the fees he charges< Is there a %etter su%stitution< !hat 0as happening 0hen///<

'easurement, not pre$iction Consi$er return an$ ris" together 9an$le small, %iase$ samples of e*pensi)e $ata Comparisons can %e tenuous, %e careful of framing #nly one of a set of tas"s ta"en to un$erstan$ a current or potential in)estment
24 Apr 2009 R/Finance 2009 6

&his Analysis
+ho0s a set of he$ge fun$s 0ithin a particular strategy Is typical of situations face$ %y in)estors

+mall, %iase$ sample of li)e, open fun$s Peer group ha)e return series of $iffering lengths an$ =uality &oo small to ma"e confi$ent statistical o%ser)ations a%out &oo large to present easily Returns are clearly non:normal, non:stationary ocus is on a single manager 0ith the conte*t pro)i$e$ %y peers an$ a fe0 in$e*es

.i)en that the assumptions are straine$, 0hat can 0e o%ser)e a%out performance an$ ris"< Ca)eats, %ac"0ar$s loo"ing, no sil)er %ullet, many >hi$$en? ris"s, your mileage may )ary, more than one 0ay to s"in a cat, etc/
24 Apr 2009 R/Finance 2009 7

Performance +ummary

9o0 has the fun$/ strategy/ portfolio performe$ in the past< Cumulati)e performance $oes not sho0 relati)e performance 0ell, %ut gi)es a sense for the o)erall shape/ +ee chart.CumReturns Ran"ing an$ relati)e performance along the 0ay is impossi%le to assess/ -ra0$o0ns sho0 e*tent of losses relati)e to pea" @e=uity@/ +ee chart.Drawdown 8aR through time sho0s ho0 estimation change$/ +ee chart.BarVaR Relati)e performance sho0s perio$s of out:performance, un$er:performance/ +ee chart.RelativePerformance
R/ inance 2009 5

24 Apr 2009

+catter Plots

9o0 $o return an$ ris" compare< &ra$itional )ie0 normali;es return an$ )olatility %y annuali;ing the measures/ +ee chart.Ris Return!catter +hort histories are a pro%lem, an$ >from inception? )ie0 mas"s $iffering time perio$s &railing perio$ performance pro)i$es some smoothing -otte$ lines sho0 +harpe ratio +nail trail sho0s time series o)erlai$ on return an$ ris"/ +ee chart.!nail"rail 9o0 has the fun$@s relati)e performance an$ ris" position change$ through time<
R/ inance 2009 9

24 Apr 2009

Rolling Performance

9o0 consistent has performance %een through time< 9as the manager ta"en more ris" to get higher returns through time< Rolling 0in$o0s pro)i$e another )ie0 of performance an$ ris" through time, one that is easier to associate 0ith e)ents Reasona%le for longer:term assessment +moothing can help re$uce noise, %ut may also hi$e short:term issues Ase multiple time:frames, consi$er your in)estment hori;on +ee chart.Rollin#Performance$ chart.Rollin#Correlation
R/ inance 2009 40

24 Apr 2009

Benchmar"ing an$ Regression

!hat %enchmar" pro)i$es a goo$ comparison< 9o0 has the strategy $one against the %enchmar"< !oul$ 0e prefer to hol$ the %enchmar"< 9o0 has e*posure to the factor change$ through time< +imple linear regression o)er rolling perio$s pro)i$es a )ie0 of parameter sta%ility, 0ith ca)eats from prior sli$e Loess fit sho0s $e)iations from linear fit +ee chart.Re#ression$ chart.Rollin#Re#ression

24 Apr 2009

R/ inance 2009

44

Correlation

A high correlation )alue may %e the result of chance an$ not significant A lo0 correlation )alue may %e significant, a small %ut still meaningful relationship Is $i)ersification a)aila%le< Co)ariance an$ correlation are critical concepts in portfolio construction 9o0 stationary is correlation through time< +ee chart.Correlation$ ta%le.Correlation$ chart.Rollin#Correlation

24 Apr 2009

R/ inance 2009

42

Autocorrelation

!hat is the li=ui$ity of the portfolio< !hat influence $oes the manager ha)e 0hen mar"ing the %oo"< .etmans"y, Lo, et/ al/ C2004D offer that autocorrelation may %e o%ser)e$ 0here li=ui$ity is lo0 .eltner C4994D, also li"ely 0ith real estate, )enture capital, pri)ate e=uity, art, an$ other $ifficult to )alue assets (conomic interpretation is that portfolio prices are slo0 to reflect mar"et )alues +ee chart.AC&'lus$ ta%le.Autocorrelation +houl$ 0e @a$Eust@ for auto: correlation< !hat a%out negati)e )alues<
R/ inance 2009 4B

24 Apr 2009

-o0nsi$e Ris"
!hat ha)e >normal? losses %een in a $o0n perio$< At 0hat le)el shoul$ 0e set alarms for re:e)aluation of an asset in a portfolio< -o losses %eha)e $ifferently than gains< 'ar"o0it; offers semi)ariance +ortino suggests that ris" may inclu$e shortfall from a goal

24 Apr 2009

R/Finance 2009

14

8alue at Ris" C8aRD


!hat le)el of loss is @normal@< A special case of $o0nsi$e ris", the limitations of mean 8alue:at:Ris" are 0ell co)ere$ #ther single:instrument 8aR metho$s, inclu$ing Cornish isher, +"e0:t, 'onte Carlo (*tensions such as (*pecte$ +hortfall Comparison helps gain some insight into the performance of the $ifferent 8aR measures/ +ee chart.VaR!ensitivit( or e*ample, mo$ifie$ CCornish isherD 8aR can %e lo0er than tra$itional 8aR if the asset e*hi%its positi)e s"e0ness an$ lo0 "urtosi 8aR measures gain e*tra importance in a portfolio CcomponentD setting
R/ inance 2009 46

24 Apr 2009

-istri%utions

Can 0e assume that returns are $istri%ute$ 2ormally< 'ost asset returns e*hi%it strong $e)iations from normality 9istogram )isuali;ation $epen$s hea)ily on %in 0i$th, impro)e$ %y using a "ernel $ensity estimator/ +ee chart.)isto#ram Fuantile:Fuantile CFFD plot compares the $ata to the theoretical $istri%ution/ +ee chart.**Plot 'ost $istri%utions lac" parameters 0ith economic meaning Can %e useful for e*pressing 0hat@s @out of %oun$s@ gi)en past performance, !hen $o 0e "no0 that things may ha)e gone off the rails<
R/ inance 2009 41

24 Apr 2009

9igher 'oments

9asn@t %een an easily a)aila%le, stan$ar$ 0ay for measuring thir$ an$ fourth or$er $i)ersification !ill an asset pro)i$e $i)ersification potential in terms of )olatility, s"e0ness an$ "urtosis< 'artellini C2006D, co:moments $o not allo0 the marginal impact of an asset on a portfolio to %e $irectly measure$/ 9igher moment %etas useful to estimate ho0 much ris" 0ill %e impacte$ %y a$$ing an asset to a portfolio, in terms of higher moments/ +ee ta%le.)i#her+oments +u%Eect to the =uality of assessments of s"e0ness, "urtosis
R/ inance 2009 43

24 Apr 2009

+tyle Analysis

!hat ris"s has the fun$ ta"en< Can 0e characteri;e the source of past returns< +harpe C4992D, styles i$entifie$ may %e interprete$ as an a)erage of potentially changing e*posures o)er the perio$ Rolling:0in$o0s may %e useful for e*amining the %eha)ior of a manager@s a)erage e*posures to asset classes o)er time 8ery similar to other forms of factor analysis +ee chart.Rollin#!t(le an$ un$erlying functions -ifficult to interpret, easy to mis: use
R/ inance 2009 45

24 Apr 2009

Calculations

'etho$s

24 Apr 2009

R/Finance 2009

19

it a -istri%ution Asing 'L(


&he function chart.)isto#ram $oes this for only a fe0 $istri%utions, so it@s goo$ to "no0 ho0 to $o it for others/ 'a*imum li"elihoo$ estimation C'L(D is the most important, 0i$esprea$, an$ ecient metho$ use$ for estimating parameters/
G * H chec"-ataCmanagersI, 2, $rop H AL+(J, na/rm H &RA(, metho$ H K)ectorKD G li%raryCsnD G fit H st/mleCy H *DL s H se=CrangeC*DI4J, rangeC*DI2J, length H 600D G fitte$/sst H $stCs, location H fitM$pII4JJ, scale H fitM$pII2JJ, shape H fitM$pIIBJJ, $fHfitM$pII4JJ, log H AL+(D G chart/9istogramC*, pro%a%ilityH&RA(, main H >9istogram?D N hist G linesCs, fitte$/sst, col H >%lue?, l0$H2D G chart/FFPlotC*, main H KFF PlotK, en)elope H 0/96, $istri%ution H KstK, location H fitM$pII4JJ, scale H fitM$pII2JJ, shape H fitM$pIIBJJ, $f H fitM$pII4JJ, log H AL+(D
24 Apr 2009 R/Finance 2009 20

it a -istri%ution Asing 'L(


&here are t0o 0ays to sol)e for fit parameters/ or a "no0n p$f, an e*plicit formula for the 'L( can usually %e foun$/ &he function fitdistr in the pac"age 'A++ uses the close$: form 'L(s for the 2ormal, log:2ormal, e*ponential an$ Poisson $istri%utions C8ena%les an$ Ripley, 2002D/ !hen a formula is not a)aila%le, an iterati)e optimi;ation routine is use$ to fin$ a solution/ In R, the mle function uses the o'tim optimi;er to On$ the minimum of the negati)e log:li"elihoo$/ &he user speciOes the negati)e log:li"elihoo$ analytical e*pression as argument an$ some starting parameters estimates/ A =uic" help/searchC7mle7D 0ill sho0 a num%er of functions in R that use the 'L( approach to Ot particular $istri%utions, such as the st/mle function in the pac"age sn/

24 Apr 2009

R/Finance 2009

21

'o$ern Portfolio &heory C'P& P CAP'D


+odern Portfolio "heor( C'P&D collection of tools an$ techni=ues %y 0hich a ris":a)erse in)estor may construct an optimal portfolio pioneere$ %y 'ar"o0it;@s 4962 paper Portfolio Selection also encompasses CAP', the efficient mar"et hypothesis, Can inclu$e %asically all forms of =uantitati)e portfolio construction an$ optimi;ation/ Ca'ital Asset Pricin# +odel CCAP'D initially $e)elope$ %y !illiam +harpe in 4914 pro)i$es a Eustification for passi)e or in$e* in)esting %y positing that assets that are not on the efficient frontier 0ill either rise or lo0er in price until they are on the efficient frontier of the mar"et portfolio (*ten$e$ an$ e)aluate$ %y +ortino, &reynor, 'erton, an$ others
24 Apr 2009 R/Finance 2009 22

Relati)e Performance per CAP'/'P&


G CAP'ta%leQ: ta%le/CAP'CRaHmanagersI,4,1,$ropH AL+(J,R%HmanagersI,cCK+ P600/&RK,K(-9(C/L+/(FKD,$ropH AL+(J,scaleH42, rfHmanagersI,KA+/Bm/&RK,$ropH AL+(JD

&his illustrates 0hy the choice of %enchmar" is so important, All these managers ha)e )ery lo0 correlations CBetaD to the +PP, %ut high correlation to the (-9(C L+ (=uity in$e*/ ta%le.CAP+CD collects most of the interesting CAP' stats in one place, an$ ma"es it easy to test multiple %enchmar"s

24 Apr 2009

R/Finance 2009

23

Calculations/ unctions un$erlying ta%le/CAP'


CAP+.al'ha, the $egree to 0hich the asset@s returns are not e*plaine$ %y the return that coul$ %e capture$ from the mar"et/ Con)ersely, CAP+.%eta, $escri%es the portions of the returns of the asset that coul$ %e $irectly attri%ute$ to the returns of a passi)e in)estment in the %enchmar" asset C)ia linear mo$el regressionD "re(norRatio, ratio of asset@s (*cess Return to Beta R of the %enchmar" ActivePremium, in)estment@s annuali;e$ return minus the %enchmar"@s annuali;e$ return "rac in#,rror, a measure of the une*plaine$ portion of performance relati)e to a %enchmar" -nformationRatio, Acti)ePremium/&rac"ing(rror/ Information Ratio may %e use$ to ran" in)estments in a relati)e fashion
24 Apr 2009 R/Finance 2009 24

-o0nsi$e Ris"
'ost in)estors are properly concerne$ 0ith %oth re0ar$ an$ ris"/ +ee ta%le.DownsideRis +tan$ar$ -e)iation or 8olatility is often use$ as the primary/ first measure of ris", %ut it is symmetrical 'ar"o0it; propose$ using !emiDeviation to measure only $o0nsi$e )olatility As alrea$y co)ere$, most in)estments incorporate significant )ariations from normality in either s ewness or urtosis +ortino an$ Price C2004D propose incorporating a minimum accepta%le return C'ARD into the measure 0hich results in DownsideDeviation an$ is use$ in .'sidePotentialRatio &he other )ery 0i$ely use$ metho$ of e)aluating $o0nsi$e ris" is through analysis of $ra0$o0ns, pro)i$e$ in findDrawdowns, sortDrawdowns, chart.Drawdown, ma/Drawdown, an$ .'DownRatios
24 Apr 2009 R/Finance 2009 25

Ris"/Re0ar$ Ratios
+harpe first suggeste$ a ratio of return to ris" Cmeasure$ %y annuali;e$ Ie*cessJ return o)er annuali;e$ stan$ar$ $e)iationD 0hich is implemente$ as !har'eRatio !illiam +harpe no0 recommen$s -nformationRatio preferentially to the original +harpe Ratio 'any other authors ha)e mo$ifie$ the ris" measure in use to create similar ratios !ortinoRatio return o)er $o0nsi$e $e)iation .'sidePotentialRatio impro)ement of the +ortino ratio that measures upsi$e return in goo$ runs o)er losses in $ra0$o0n perio$s +e)eral other mo$ifie$ +harpe ratios ha)e %een propose$, an$ are implemente$ in PerformanceAnalytics, inclu$ing using any of .aussian an$ Cornish isher mo$ifie$ 8aR an$ (+ measures as the ris" measure in parameters to !har'eRatio.modified
24 Apr 2009 R/Finance 2009 26

8alue at Ris" C8aRD


8alue at Ris" C8aRD has %ecome a re=uire$ stan$ar$ ris" measure recogni;e$ %y Basel II an$ 'i I PerformanceAnalytics 4/0 has a VaR function 0ith stan$ar$i;e$ parameters for historical, .aussian, "ernel, an$ Cornish isher 8aR/

!rapper 0ill pro%a%ly %e e*ten$e$ to inclu$e 'onteCarlo, +"e0 +tu$ent:t, an$ generali;e$ Pareto 8aR estimators soon Sey parameters are RTthe seriesU, pTpro%a%ilityU, an$ the metho$ $esire$/ Also allo0s moments to %e passe$ in to allo0 for $ifferent estimators or optimi;ation Also allo0s for 'arginal an$ Component 8aR calculations
R/Finance 2009 27

24 Apr 2009

'arginal an$ Component 8aR


Marginal VaR is the change in the portfolio 8aR attri%uta%le to a change in position at the margin/
: Implemente$ in the VaR 0rapper or as VaR.+ar#inal : 2ot particularly useful, e*cept in special cases for re%alancing similar instruments

Component VaR is the ris" contri%ution of each instrument to the ris" of the 0hole portfolio

24 Apr 2009

R/Finance 2009

28

(*pecte$ +hortfall C(+D


Conditional Value at Risk (CvaR) also "no0n as Expected S ortfall (ES) is the mean e*pecte$ loss 0hen the loss e*cee$s the 8aR !e ha)e 0rappe$ ,! in a manner similar to VaR an$ pro)i$e %oth single:instrument an$ component )ersions for .aussian, 9istorical, Sernel, an$ Cornish isher (*pecte$ +hortfall Beyon$ 8aR CVaR.Be(ondD is a relate$ measure of mean e*pecte$ tail loss that a$$s 8aR an$ (+

24 Apr 2009

R/Finance 2009

29

!hat +ensiti)ity/Confi$ence 'a"es +ense for Ris"<


+ome in)estors, ris" managers, or regulators 0ill as" for confi$ence of 99/99V or e)en higher/ &his means,

#nce in 56 years for monthly $ata #nce in 20 years for 0ee"ly $ata #nce in 4 years for $aily $ata

&hese "in$s of ris" confi$ence pro%a%ilities only ma"e sense if you ha)e a L#& of $ata, or for high:fre=uency $ata o)er short hori;ons Cminutes to may%e an hourD 9igh confi$ence le)els also assume a sta%le series, pro%a%ly a %a$ assumption o)er the timeframes a%o)e/ -e)eloping these confi$ence le)els %y e*ten$ing/e*pan$ing your time series through simulation may 0or" Be0are of hi$$en $istri%utional assumptions
24 Apr 2009 R/Finance 2009 30

Be0are the Brea"$o0nW

In a$$ition to >false confi$ence?, you also nee$ to %e a0are of 0hen the ris" measure you@re using $oesn@t fit the $ata 0ell/

GlayoutCmatri*CcC4,2,B,4D,nro0H2,ncolH 2,%yro0H&RA(DD GapplyCmanagersI,4,4,$ropH AL+(J,2, chart/8aR+ensiti)ityD

2ote that Cornish isher 8aR generally more closely mirrors historical reali;ations 2ote 0here 9A'2 %rea"s $o0n completely at high pro%a%ilities

24 Apr 2009

R/ inance 2009

B4

-ata Cleaning an$ +moothing


#ut:of:sample pre$ictions of return or ris" may %e a$)ersely affecte$ %y autocorrelation or outliers in the $ata .eltner an$ .etmans"y ha)e propose$ $ifferent metho$s of $ealing 0ith autocorrelation implemente$ as Return.0eltner an$ !moothin#-nde/ !e propose an$ test a metho$ in our 2005 XoR paper for a ro%ust metho$ of cleaning returns to impro)e out of sample ris" pre$ictions/

i$entify the returns that are outsi$e the confi$ence threshol$ $esire$ for the ris" measure Ce/g/ 96V or 99VD re$uce the magnitu$e of those outlying returns if they are outsi$e the range of the other returns as i$entifie$ %y the 'ahalano%is $istance re$uction in magnitu$e "eeps ran"e$ magnitu$e intact Cthe largest loss/gain 0ill remain the largest loss/gain, e)en after smoothingD see Bou$t,Peterson,Crou* C2005D for $etails or Return/clean

24 Apr 2009

R/Finance 2009

32

-ata Cleaning

2ote the smoothing of outlying returns aroun$ the Russian financial crisis/ Ro%ust smoothing impro)es out of sample ris" pre$ictions @e$hec@ $ata series cleane$ %y Return.clean )ia the function chart.%arVaR
24 Apr 2009 R/Finance 2009 33

+harpe@s +tyle Analysis


+tyle analysis is a returns:%ase$ analysis use$ to $etermine a fun$@s e*posures to the changes in returns of maEor asset classes/ chart.Rollin#!t(le calculates an$ $isplays effecti)e 0eights in rolling 0in$o0s through time/ st(le.fit manages the calculation of the 0eights %y metho$/ st(le.*Pfit calculates the specific constraint case that re=uires =ua$ratic programming/ &he Kunconstraine$K metho$ implements a multiple regression/ >2ormali;e$? is the same, %ut the coefficients sum to 4/ &he Kconstraine$K a$$s that the coefficients must %e %et0een 0 an$ 4/ &hat re=uires a =ua$ratic programming algorithm, using solve.*P from the @=ua$prog@ pac"age/ Ases R2 for )aria%le selection/ Alternati)ely, 0e ha)e an implementation that uses AIC as a criterion:%ase$ metho$ for selecting style 0eights/ (mail us if you@re intereste$/
24 Apr 2009 R/Finance 2009 34

+harpe@s +tyle Analysis


G$ataCe$hecD Gchart/Rolling+tyleCmanagersI,2,$ropH AL+(J,e$hecI,4,44J, metho$HKconstraine$K, le)erageH AL+(, 0i$thHB1, ce*/legen$ H /3, colorsetHrain%o042e=ual, lasH4D

Apologies in a$)ance for the stac"e$ %ar chart/ A much %etter alternati)e is to graph each factor 0eight separately so that the )alues can %e rea$ easily an$ are easier to compare

24 Apr 2009

R/Finance 2009

35

&hings Left &o -o


&urther Research Performance attri%ution an$ Portfolio Analytics Ris" Bu$geting

Applications of Component Ris" to large portfolios &ransactions an$ positions 0ith profit an$ loss Instrument properties an$ mo$el Interfaces to $ata pro)i$er pac"ages

9istorical portfolio frame0or" in R


Practical Bayesian applications Anything Y#A 0ant to 0or" 0ith us on ! ank "ou for your attention

24 Apr 2009

R/Finance 2009

36

Appen$i*, &he Buil$ing Bloc"s

9o0

24 Apr 2009

R/Finance 2009

37

Install an$ Ase PerformanceAnalytics


&here are se)eral 0ays to install pac"ages, %ut the prefera%le 0ay to install them is through the CRA2 repository/ !ithin an R session, you can type,
G install/pac"agesC@PerformanceAnalytics@, $epH&RA(D

#nce the pac"age is installe$, you nee$ to loa$ it into the current 0or"space to use it/ Ase
G li%raryCPerformanceAnalyticsD

to loa$ the pac"age/ Alternati)ely, un$er !in$o0s, use the @Pac"age@ menu an$ select @Li%rary/@

24 Apr 2009

R/Finance 2009

38

Rea$ing -ata
9o0 $o I rea$ $ata from an (*cel sprea$sheet<

(*port the $ata you 0ant from (*cel into a comma:$elimite$ Ole Cusually sa)e$ 0ith a /cs) suffi*D an$ use rea$/cs) +eparate $ata using commas an$ 0ith a hea$er a%o)e each column/ or time series $ata, the $ate is usually foun$ in the first column in YYYY:'':-- format Loo" at $ocumentation for Return.read an$ read.csv

9o0 $o I rea$ $ata from Internet sources<

&here are a )ariety of 0ays, %ut 0e recommen$ the =uantmo$ pac"age, see 1#et!(m%ols 9an$les a )ariety of Internet sources inclu$ing YahooW inance, R(-, .oogle inance, an$ #an$a/ Pro)i$es price aggregation from higher to lo0er timescales, see 1 to.'eriod Also spectacular price charts
R/Finance 2009 39

24 Apr 2009

A%out the -ata


(*ample $ata for this presentation is inclu$e$ in the PerformanceAnalytics pac"age/ &o loa$ the $ata, type,
G $ataCmanagersD

@managers@ is a $ata frame that contains columns of C$isguise$D monthly returns for si* e=uity long:short he$ge fun$s, plus

the (-9(C Long:+hort (=uity he$ge fun$ in$e*, the +PP 600 total returns, a total return series for the A+ &reasury 40:year %on$ an$ a total return series for the A+ &reasury B:month %ill/

'onthly returns for all series en$ in -ecem%er 2001 an$ %egin at $ifferent perio$s starting from Xanuary 4991/

24 Apr 2009

R/Finance 2009

40

!or"ing !ith &ime +eries


Al0ays choose the least comple* $ate/time class that 0ill accomplish the tas"/

P#+IZ classes support times an$ $ates inclu$ing time ;ones an$ $aylight sa)ings time/ &hey are mostly useful for intra$ay an$ tic" $ata, such as currency $ata 0here $ata alignment is an issue/ -ate is a class in %ase that supports $ates 0ithout times/

&he -ate class pro)i$es a se=/-ate function,


G se=Cas/-ateCK4999:42:04KD,length/outH42, %yHK4 monthKD G se=CI+#$ateC2000,4,B4D, %y H KmonthK, length H 4D G se=Cas/-ateCK2000:04:04KD,length/outH420, %yHK4 monthKD:4

&he ;oo pac"age pro)i$es general support for or$ere$ o%ser)ations, in$epen$ent of a particular in$e* class/

Any in$e* 0ill 0or", inclu$ing the in$e*es pro)i$e$ %y ts, its, irts an$ time+eries/ Pro)i$es careful %ac"0ar$s compati%ility 0ith ro%ust as/[ metho$s an$ proper use of reclass/
R/Finance 2009 41

24 Apr 2009

!or"ing !ith &ime +eries


&he *ts pac"age e*ten$s ;oo %y enforcing a time:%ase$ in$e* %ut allo0ing for multiple timescales/ *ts is )ery fast As an e*tension to ;oo, *ts offers relati)ely lossless co)ersion to an$ from the myria$ of time:series classes in R/ Calling reclass turns it %ac" into the o%Eect@s original form 0ith e)erything intact/ Pro)i$es a uni=ue metho$ of $ate su%setting/
G sample/*tsI@2003@J N all of 2003 G sample/*tsI@2003:0B,,@J N 'arch 2003 to the en$ of the $ata set G sample/*tsI@2003:0B,,2003@J N 'arch 2003 to the en$ of 2003 G sample/*tsI@,,2003@J N the %eginning of the $ata through 2003 G sample/*tsI@2003:04:0B@J N Eust the Br$ of Xanuary 2003

&his format e*ten$s all the 0ay $o0n to time : e/g/ @4999:04:06 05,00,,4999:04:06 05,B6,2B@/
R/Finance 2009 42

24 Apr 2009

Calculate Returns
'ost mar"et $ata is prices, %ut almost the entire %o$y of metho$s for performance an$ ris" analysis re=uires returns/ Prices can %e easily con)erte$ to simple or compoun$ ClogarithmicD returns using Return.calculate &he single:perio$ arithmetic return, or simple return, can %e calculate$ Cusing =uantmo$ to get the $ataD,
G get+ym%olsCK+PYKD G Return/calculateC+PYM+PY/Close,metho$HKsimpleKD

+imple returns, cannot %e a$$e$ together/ +imple returns are most often the correct input for performance or ris" analysis/ &he natural logarithm of the simple return of an asset is referre$ to as the continuously compoun$e$ return, or log return, an$ may %e a$$e$ together to get a total return/
G Return/calculateC+PYM+PY/Close,metho$HKcompoun$KD
24 Apr 2009 R/Finance 2009 43

+et Ap -ata for Analysis


&his is an e*ample of ho0 the $ata 0as set up for all of the e*amples sho0n in the first half/ All of the follo0ing co$e snippets reference these )aria%les,
G manager/column H 4L peer/columns H 2,1L in$e*/columns H 3,5L manager/color H Kre$KL peer/color H K$ar"grayKL in$e*/color H KorangeK G colorset H cCrepCmanager/color,lengthCmanager/columnDD, repCin$e*/color, lengthCin$e*/columnsDD, repCpeer/color,lengthCpeer/columnsDDD G linetypes H cCrepC4, lengthCmanager/columnDD, 4,lengthCin$e*/columnsD, repC4, lengthCpeer/columnsDDD G $ottypes H cCrepC41, lengthCmanager/columnDD, close$sym%olsI4,lengthCin$e*/columnsDJ, repC4, lengthCpeer/columnsDDD

24 Apr 2009

R/Finance 2009

44

Charts
Charts in PerformanceAnalytics are $esigne$ to %e compati%le 0ith tra$itional R graphics such as plot/ or e*ample, line 0i$ths can %e change$ %y setting l0$ H 2, or line types can %e change$ using lty H B, etc/

+ee <par an$ <plot for the full list of attri%utes that can %e change$/ or e*ample, a typical time series chart for cumulati)e returns might loo" li"e,
G chart/CumReturnsCmanagersI,cCmanager/column, in$e*/columns, peer/columnsD, $rop H AL+(J, main H >Cumulati)e Returns?, legen$/loc H >topleft?, e)ent/lines H ris"/$ates, e)ent/la%els H ris"/la%els, ylog H &RA(, 0ealth/in$e* H &RA(, colorset H colorset, l0$ H 2D

24 Apr 2009

R/Finance 2009

45

Color an$ +ym%ol +ets


PA inclu$es sets of color palattes $esigne$ to create rea$a%le C%ut appealingD line an$ %ar graphs, in three categories,

ocus, to pro)i$e )isual focus to the $ata graphe$ Orst/ Inclu$es re$focus, %luefocus, an$ greenfocus/ #ne color an$ grays/ (=ual:0eighte$, or 0hen all of the $ata shoul$ %e o%ser)e$ an$ $istinguisha%le on a line graph/ &he $ierent num%ers in the name in$icate the num%er of colors in the set/ +ee rain%o042e=ual, rich42e=ual, tim42e=ual, $ar"1e=ual, set5e=ual/ 'onochrome, same color, $ifferent )alue/ Inclu$es greenmono , %luemono, re$mono, gray5mono an$ gray1mono/ &hese are Eust lists of strings that contain the R.B co$es of each color/ Create your o0n colorsets 0ith RColorBre0er,,,%re0er/pal, rain%o0, gplots,,,rich/colors, fiel$s,,,tim/colors, etc/

+imilarly, there are a fe0 sets of groupe$ sym%ols for scatter charts,

24 Apr 2009

opensym%ols, close$sym%ols, fillsym%ols, linesym%ols, an$ allsym%ols/


R/Finance 2009 46

Legen$s
-efault legen$s are easy to use %y setting,

legen$/loc H any of, ?%ottomright?, ?%ottom?, ?%ottomleft?, ?left?, ?topleft?, ?top?, ?topright?, ?right? an$ ?center?

#r custom legen$s can %e set up after a plot is ma$e/ In this case, 0e@re shortening the list of la%els,
G legen$/colorset H cCrepCmanager/color, lengthCmanager/columnDD, peer/color, repCin$e*/color, lengthCin$e*/columnsDDD G legen$/linetypes H cCrepC4, lengthCmanager/columnDD, 4, 4,lengthCin$e*/columnsDD G legen$/$ottypes H cCrepC41, lengthCmanager/columnDD,4, close$sym%olsI4,lengthCin$e*/columnsDJD G legen$names H cCcolnamesC*I, manager/column, $rop H AL+(JD,KPeer groupK, colnamesC*I, in$e*/columns, $rop H AL+(JDD G legen$C>topleft?, inset H 0/02, te*t/col H legen$/colorset, col H legen$/colorset, ce* H /5, %or$er/col H KgrayK, l0$ H 2, %g H K0hiteK, legen$ H legen$names, ltyHlegen$/linetypes, pch H legen$/$ottypes, pt/%gHK0hiteK, pt/l0$ H K4K, merge H AL+(, pt/ce* H 4/26D
24 Apr 2009 R/Finance 2009 47

&a%les
Create a $ata/frame arrange$ ho0 you 0ant, either %y han$ or using one of the ta%le/[ functions,
G 0 H tCta%le/AutocorrelationC*I, cCmanager/column, peer/columns, in$e*/columnsD, $rop H AL+(JDD

Ase format/$f to format contents of a $ata/frame

oun$ in the @9misc@ pac"age

G li%raryC9miscD G * H format/$fC0, na/%lan"H&, r$ecHcCrepC4,$imC0DI4JDD, col/EustHrepCKncK,$imC0DI2JDD

Ase te*tplot to $isplay te*t output in any graphics $e)ice/

#riginally from @gplots@ pac"age, %ut 0e@)e a$$e$ te*t 0rapping for long la%els an$ a fe0 other features/

G te*tplotC*, ce* H 4, rmar H 0/16, cmar H 4/0, marHcC0,0,0,0D, halign H KcenterK, )align H KcenterK, 0rap/ro0namesH60D

24 Apr 2009

R/Finance 2009

48

Layout an$ 'argins

9o0 to use layout for charts,

G layoutCmatri*CcC4,4,2,2,B,B,4,6D, nro0H4, ncolH2, %yro0H&RA(D, heightHcCB,4/26,4/36,BD, 0i$thH4D G layout/sho0C6D

Anfortunately, you can@t nest layouts/ +ome charts that use layout can not then, in turn, %e use$ 0ith layout/

'argins for plots can %e change$ using par in each frame

mar, a numerical )ector of the form cC%ottom, left, top, rightD 0hich gi)es the num%er of lines of margin to %e specifie$ on the four si$es of the plot/ &he $efault is cC6, 4, 4, 2D \ 0/4

G parCmarHcC4,4,4,2DD

24 Apr 2009

R/ inance 2009

49

-e)ices
!riting to P- files
G p$fCfileH?filename/p$f?, heightH40, 0i$thH3/6, paperHKletterKD ] G $e)/offCD

] or (ncapsulate$ Postscript

!or"s 0ith !or$, Late*

G postscriptCfileHKfilename/epsK, 0i$thH6/26, heightH5, paperHKspecialK, hori;ontalH AL+(, onefileH AL+(D ] G $e)/offCD

Copying from a $e)ice

'ay not copy accurately

G $e)/copy2epsCD

24 Apr 2009

R/Finance 2009

50

You might also like