A package accompanying this book,FRAPO, is available on CRAN. It can also be downloaded from the author’s website atwww.pfaffikus.de. Within the pack- age,S4classes and methods are employed. The purpose of this package is to provide:
•the examples in this book;
•the data sets that are used in theRcode listings;
•classes, methods, and functions for portfolio optimization techniques and ap- proaches that have not been covered in other contributedRpackages;
•utility functions, such as the computation of returns, trend/momentum-based indicators, and descriptive portfolio statistics.
Listing 2.1 shows first how the package can swiftly be installed, where it is as- sumed that the user has access to the Internet. Additional packages are automatically installed as required. Next, the package is loaded into the workspace. An overview of the package in terms of the help topics covered is returned to the console by executing line 6. The description part of the package is followed by an index of the help top- ics. The first entry is “BookEx”: “Utility functions for handling book examples.” The help page for this entry is then opened by executing the command on line 8, where
k k Rcode 2.1The package FRAPO.
# # I n s t a l l a t i o n o f t h e book ’ s a c c o m p a n y i n g p a c k a g e 1
i n s t a l l . p a c k a g e s ( "FRAPO" ) 2
# # L o a d i n g o f t h e p a c k a g e 3
l i b r a r y ( FRAPO ) 4
# # O v e r v i e w o f t h e h e l p t o p i c s 5
h e l p ( p a c k a g e = FRAPO ) 6
# # D i s p l a y i n g h e l p f o r t h e e x a m p l e s 7
? BookEx 8
# # S h o w i n g t h e l i s t i n g o f R c o d e e x a m p l e s 9
l i s t E x ( ) 10
# # R e t u r n i n g t h e c o n t e n t o f t h i s e x a m p l e 11
showEx ( " C3R1 " ) 12
# # E x e c u t i n g t h i s s c r i p t 13
r u n E x ( " C3R1 " , e c h o = TRUE) 14
the shortcut?for thehelp()function is used. The functions implemented to han- dle theRcode examples covered in this book are listed in the usage section. That is, listEx()will return a character vector of the names of theRcode examples, the functionshowEx()will display anRcode example on the standard output ( i.e., the console), or it can be directly executed by callingrunEx(), a copy of an example can be created in the working directory by means of the functionsaveEx(), and can be edited by callingeditEx(). The latter function comes in handy if the reader wishes to “play around” with the code or to modify it in some way (s/he is encour- aged to do so). To reiterate, a copy of theRcode example shipped with the package is first created in the working directory, and editing this file and saving the changes will not affect the originalRcode as listed in this book, unlessRis started in the package subdirectory “BookEx,” which is not recommended for the above reason. In the remaining code lines, the handling of theRcode examples is elucidated.
Given the scarcity of publicly available financial time series, some data sets are included in the package, as listed below. Some of these data sets can be considered as benchmark data.
•EESCBFX: ESCB FX Reference Rates
•EuroStoxx50: EURO STOXX 50
•FTSE100: FTSE 100
•INDTRACK1: Hang Seng Index and Constituents
•INDTRACK2: DAX 100 Index and Constituents
•INDTRACK3: FTSE 100 Index and Constituents
•INDTRACK4: Standard & Poor’s 100 Index and Constituents
k k
•INDTRACK5: Nikkei 225 Index and Constituents
•INDTRACK6: Standard & Poor’s 500 Index and Constituents
•MIBTEL: Milano Indice Borsa Telematica
•MultiAsset: Multi Asset Index Data
•NASDAQ: NASDAQ
•SP500: Standard & Poor’s 500
•StockIndex: Stock Index Data
•StockIndexAdj andStockIndexAdjD: Stock Index Data, month-end and daily.
The data sets EuroStoxx50, FTSE100, MIBTEL, NASDAQ, and SP500 are used in Cesarone et al. (2011) and can be retrieved from http://host .uniroma3.it/docenti/cesarone/DataSets.htm. These data sets comprise weekly observations of the index constituents starting on 3 March 2003 and ending on 24 March 2008. The authors adjusted the price data for dividends and removed stocks if two or more consecutive missing values were found. In the remaining cases theNAentries were replaced by interpolated values.
The series of data objects INDTRACK* are part of the OR library (see http://people.brunel.ac.uk/∼mastjjb/jeb/info.html) and are used in Beasley et al. (2003) and Canakgoz and Beasley (2008). Similar to the data sets described above, these objects hold weekly observations of the index and its constituents. Stocks with missing values during the sample period have been discarded. The data was downloaded from DATASTREAM and made anonymous.
The first column refers to the index data itself. The data license for these time series is included in the package as file BeasleyLicence and can also be found at http://people.brunel.ac.uk/∼mastjjb/jeb/orlib/legal.html.
The ESCB FX data set consists of daily spot exchange rates for major currencies against the euro. The sample starts on 1 April 1999 and ends on 4 April 2012, giving a total of 3427 observations. The currencies are AUD, CAD, CHF, GBP, HKD, JPY, and USD.
The source of the remaining data sets MultiAsset, StockIndex, Stock IndexAdj, andStockIndexAdjDis Yahoo! Finance (seehttp://finance .yahoo.com). The un/adjusted month-end/daily prices for the major stock and/or bond markets as well as gold are provided. The sample ofMultiAssetstarts in November 2004 and ends in November 2011. The sample period for data sets cover- ing the major stock markets is larger, starting in July 1991 and ending in June 2011.
With respect to portfolio optimization, which is thoroughly covered in Chapter 5 and Part III of this book, the following approaches are available (in alphabetical order):
k k
•PAveDD(): Portfolio optimization with average draw-down constraint;
•PCDaR(): Portfolio optimization with conditional draw-down at risk constraint;
•PERC(): equal risk contributed portfolios;
•PGMV(): global minimum variance portfolio;
•PMD(): most diversified portfolio;
•PMTD(): minimum tail-dependent portfolio;
•PMaxDD(): portfolio optimization with maximum draw-down constraint;
•PMinCDaR(): portfolio optimization for minimum conditional draw-down at risk.
These are constructor functions for objects of theS4classPortSoldefined in FRAPO. In order to foster the reader’s comprehension ofS4classes and methods as introduced in Section 2.4, the handling of these objects is elucidated in the following R code in-line statements. As an example, the solution of a global minimum-variance (GMV) portfolio is determined for the major stock indexes as contained in theStockIndexAdjdata set:
> data(StockIndexAdj)
> R <- returnseries(StockIndexAdj, method = "discrete",
+ trim = TRUE)
> P <- PGMV(R, optctrl = ctrl(trace = FALSE))
After the data set has been loaded into the workspace, the discrete returns of the price series are computed and assigned to the objectR. The result of callingPGMVis then stored in the objectP. The structure of an unknown object can be investigated with the functionstr(), but here we will query the class ofP:
> class(P) [1] "PortSol"
attr(,"package") [1] "FRAPO"
The structure of this class can then be returned:
> showClass("PortSol")
Class "PortSol" [package "FRAPO"]
Slots:
Name: weights opt type call
Class: numeric list character call
k k
Known Subclasses: "PortCdd", "PortAdd", "PortMdd"
In the output it is indicated that this class is defined in the packageFRAPOand contains the slotsweights,opt,type, andcall. In the second line of the slots section, the classes of these entities are listed. Thus, the class of the portfolio weights isnumeric, the outcome of the optimization is alistobject, the type of the port- folio is described ascharacter, and the call to the function by which the object has been created is of classcall. The last line of the output indicates which other classes inherit fromPortSol. The manual page of thePortSolclass is displayed byhelp("PortSol-class"). The methods defined forPortSolobjects are displayed by callingshowMethods()with the class name is passed as argument classes.
> showMethods(classes = "PortSol", inherited = FALSE) Function "complete":
<not an S4 generic function>
Function "coredata":
<not an S4 generic function>
Function "coredata<-":
<not an S4 generic function>
Function ".DollarNames":
<not an S4 generic function>
Function "formals<-":
<not an S4 generic function>
Function "functions":
<not an S4 generic function>
Function "prompt":
<not an S4 generic function>
Function "scale":
<not an S4 generic function>
Function: show (package methods) object="PortSol"
Function: Solution (package FRAPO) object="PortSol"
Function: update (package stats) object="PortSol"
Function: Weights (package FRAPO) object="PortSol"
This says that ashow() method is available, which is executed automatically when the object is returned. The generic function for this method is available in the methodspackage. TheSolution()method for retrieving the outcome of the op- timizer is defined in the packageFRAPOitself, as is the methodWeights()for extracting the optimal weight vector.
k k
> P
Optimal weights for porfolio of type:
Global Minimum Variance
SP500 N225 FTSE100 CAC40 GDAX HSI
36.6719 13.9499 49.3782 0.0000 0.0000 0.0000
> Weights(P)
SP500 N225 FTSE100 CAC40
3.667185e+01 1.394991e+01 4.937824e+01 -5.526138e-07
GDAX HSI
-6.809098e-07 -7.415764e-07
Anupdate()method is available, too. This comes in handy and saves typing if one wishes to update an existing object by altering the values passed to the gen- erating function’s arguments. For instance, portfolio back-testing whereby the fund is rebalanced regularly can be carried out by utilizing theupdate()method and incrementally increasing the underlying data sample.
In order to see the actual source code of a method definition, rather than entering the name of the method one can useselectMethod():
> showMethods("Weights", inherited = FALSE) Function: Weights (package FRAPO)
object="PortSol"
> selectMethod(f = "Weights", signature = "PortSol") Method Definition:
function (object) {
ans <- slot(object, "weights") return(ans)
}
<environment: namespace:FRAPO>
Signatures:
object target "PortSol"
defined "PortSol"
As can be seen from the function’s body, alternative means for retrieving the slot weightsare:
> Weights(P)
SP500 N225 FTSE100 CAC40
3.667185e+01 1.394991e+01 4.937824e+01 -5.526138e-07
GDAX HSI
-6.809098e-07 -7.415764e-07
> slot(P, "weights")
SP500 N225 FTSE100 CAC40
3.667185e+01 1.394991e+01 4.937824e+01 -5.526138e-07
GDAX HSI
-6.809098e-07 -7.415764e-07
> P@weights
SP500 N225 FTSE100 CAC40
k k
3.667185e+01 1.394991e+01 4.937824e+01 -5.526138e-07
GDAX HSI
-6.809098e-07 -7.415764e-07
With these last pointers and examples, the reader should hopefully have some in- sight into working with the formal class and method scheme inR.
References
Beasley J., Meade N., and Chang T. 2003 An evolutionary heuristic for the index tracking problem.European Journal of Operational Research148, 621–643.
Becker R., Chambers J., and Wilks A. 1988The New S Language. Chapman & Hall, London.
Canakgoz N. and Beasley J. 2008 Mixed-integer programming approaches for index tracking and enhanced indexation.European Journal of Operational Research196, 384–399.
Cesarone F., Scozzari A., and Tardella F. 2011 Portfolio selection problems in practice: a comparison between linear and quadratic optimization models. Quantitative Finance Papers 1105.3594, arXiv.org.
Chambers J. 1998Programming with Data. Springer-Verlag, New York.
Chambers J. 2008Software for Data Analysis: Programming with R. Springer-Verlag, New York.
Chambers J. 2014 Object-oriented programming, functional programming in R.Statistical Sci- ence29(2), 167–180.
Chambers J. 2016Extending R.CRC Press, Taylor & Francis Group, Boca Raton.
Chambers J. and Hastie T. 1992Statistical Models in S. Chapman & Hall, London.
Fox J. 2009 Aspects of the social organization and trajectory of the R project.The R Journal 1(2), 5–13.
Gentleman R. and Ihaka R. 1997 The R language InProceedings of the 28th Symposium on the Interface(ed. Billard L. and Fisher N.) The Interface Foundation of North America.
Graves S., Dorai-Raj S., and Francois R. 2013sos: Search contributed R packages, sort by package. R package version 1.3-8.
Ihaka R. and Gentleman R. 1996 R: A language for data analysis and graphics.Journal of Computational and Graphical Statistics5, 299–314.
R Core Team 2016 R:A Language and Environment for Statistical ComputingR Foundation for Statistical Computing Vienna, Austria.
Zeileis A. 2005 CRAN task views.R News5(1), 39–40.
k k
3
Financial market data