The packages tframe and xts

Một phần của tài liệu Financial risk modelling and portfolio optimization with r second edition (Trang 412 - 417)

So far, many possibilities for dealing with time series data inRhave been presented and it is up to the user to choose the class that will suit his or her task best. However,

k k matters are different for package developers. They are faced with the problem that

their functions and methods have to interact with these quite numerous ways time series can be created and the different classes for date/time stamps. Providing a solu- tion to this problem is the motivation for the packagesxts(see Ryan and Ulrich 2014) andtframe(see Gilbert 2015a), namely, to provide a unifying class and method in- frastructure such that a developer has only to cope with these time series classes. Of course, employing the facilities ofxtsortframeis not confined to this group of R users.

The packagetframeis hosted on CRAN and R-Forge. As well as providing func- tions for handling time series irrespective of the representation of dates and times, further facilities for plotting and data manipulation have been implemented. The packagetframePlusis an extension oftframe, in particular with respect to the sec- ond group of provided methods (see Gilbert 2015b). A classed time frame attribute tframeis set or extracted to an object by the functiontframe(). Alternatively, a time frame can be superimposed on an object by either of the functionstfSet()or tframed(), or by means of coercion:as.tframe(). The existence of atframe object is assessed by calling eithertframe()ortframed(). The equality of two objects can be determined by the functiontestEqual(), and whether the time frames of two objects are the same with the functiontestEqualframes(). The classedtframeattribute of an objectbarcan also be transferred to another object fooby usingframe()as extractor function on the former object and the same func- tion in the assignment of the latter, that is, tframe(foo) <- tframe(bar).

The start and end periods are returned by either callingstart()ortfstart() for the beginning period, or end()ortfend()for the ending period of a time frame. For multivariate time series objects, the functions latestStart() and latestStartIndex()are available. These functions return either the start date of the series where observations start at the latest time and the latter returns the column index pertinent to the series in question. Similarly, the functionsearlies- tEnd(),earliestEndIndex(), andlatestEnd(),latestEndIndex() are made available, with obvious meanings. The sample size is recovered by the func- tiontfSpan()and sub-setting of a time series is accomplished bytfwindow(), whereby the relevant newstartandendperiods are specified. Atframeobject can be expanded horizontally by means of the function tfExpand()and verti- cally, that is, by right-appending a time series to an existingtframeobject, by the tbind()method. The analogue to this function with respect to the time dimen- sion issplice(). Dropping ofNAentries is accomplished by calling the function trimNA(). The names of the series can either be extracted or assigned to aframe object by the functionseriesNames(). A certain series of a multiple time series object is extracted by the functionselectSeries(). Utility functions aretfL() for lagging a time series,diff()anddifflog()for computing (logarithmic) dif- ferences,tfplot()for producing time series plots, andtfprint()for producing a formatted print of atframeobject. Reading and writing atframeobject from/to a file connection is accomplished by the functionstsScan()andtsWrite, re- spectively. In the complementary packagetframePlus, facilities for the aggregation of time series (as.quarterly(),as.annually(), andas.weekly()) are

k k made available. The aggregation method has to be provided as argumentFUN; the

default is set to compute sums of the data belonging to the lower-frequency periods.

The date/time representation can be replaced by a new date/time class with the func- tionchangeTSrepresentation(). To apply a function to consecutive periods of a coarser time grid, the functionrollAggregate()is made available. Cumu- lated sums of a time series are returned by callingtfI(). As well as producing time series plots with the functiontfplot(), a routine for generating perspective plots of a multivariate time series istfpersp(). Finally,tframeobjects can be written to a spreadsheet file (format eitherxlsorcsv) by the functionsTSwriteXLS() orTSwriteCSV(), respectively.

Objects of S3 classxtsare amended and modified versions ofzooobjects and can be created by either calling its generator functionxts()or by means of coercion (methodsas.xtsandtry.xts()). The modifications implemented are that (i) a time-based index is required forxtsobjects, whereas forzooobjects any ordered index can be used; (ii)xtsobjects are amended by internal attributes which store the class of the original series data (.CLASS) and a row names attribute (.ROWNAMES), which takes care of the date/time information of the series; and (iii) the possibility of adding user-specified attributes. Because thextsclass is derived fromzoo, basi- cally all the methods and functions presented in the previous sub-section can also be applied toxtsobjects. Hence, in the following only the facilities particular toxts objects will be presented.

The first group of functions to described will refer to the date/time handling of xtsobjects. The function endpoints()returns the index entries of a time se- ries that adhere to the last “date/time” of a period. The periodicities supported are:

microseconds, milliseconds, seconds, minutes, hours, days, weeks, months, quarters, and years. Next, to recover the first or lastnobservations of a time series the methods first()andlast()are made available. A feature of these methods is that aside from a numeric value for the count of periods to return, this can also be expressed as the count of a periodicity, for example,first(x, “1 month”)would return the time series data pertinent to the first calendar month. The index values only could then be recovered by either of the methodsindex()ortime. Date/time stamps as POSIXctobjects for the first or last index entry for a specified period are returned by the functionsfirstof()andlastof(). The index class of anxtsobject can be queried with the functionindexClass(), and can also be employed in its assign- ment. Furthermore, the index can be converted to a different class through coercion by means of the functionconvertIndex(). The supported index classes are:Date, POSIXct,chron,yearmon,yearqtr, ortimeDate. Testing whether the in- dex class is supported or not can be accomplished with eitheris.timeBased() ortimeBased(). The time zone of the index can be queried or assigned with the functionindexTZ(). Similarly, the format of an index representation can be re- trieved or modified with the functionindexFormat(). Assessing whether a time series index is ordered can be accomplished with the functionisOrdered(increas- ing/decreasing and with/without duplicate index entries). The index entries of a time series can be made unique with either of the functionsmake.index.unique()or make.time.unique(). This is achieved either by dropping duplicate entries or

k k by adding fractions of a second to a time stamp. The default increment is set to a hun-

dredth of a second, which might be applicable for high-frequency data. For producing a sequence of date/time vectors the functionstimeBasedSeq()ortimeBase- dRange()can be utilized (the latter will only return a two-element vector in which the elapsed seconds since 1 January 1970 for the start and end dates/times are re- turned). The specification of the start, end, and periodicity for these two functions is pretty user friendly. This information is supplied to the function in the form of a character string with format equal to eitherfrom/to/byorfrom::to::by. Inci- dentally, the latter can be omitted and then the date/time increments do depend on the granularity of the provided date/time specifications forfromand/orto. The class of the returned object can be controlled by means of theretclassargument, and the length of the returned object can controlled by the argumentlength.out, which takes precedence if in conflict with the stated range/periodicity. An estimate for the periodicity of anxtsobject is returned by the functionperiodicity(), which is accomplished by computing the median time between observations. The count of a certain periodicity of anxtsobject is returned by the functionnfoo(), wherefoo is a placeholder for eitherseconds,minutes,hours,days,weeks,months, quarters, oryears.

In the second group, functions will be presented for manipulating, aggregating, and sub-settingxtsobjects. Akin to theaggregate()method in the packagezoo, two sets of facilities for applying a function to date/frequency ranges have been imple- mented. The first are theapply.foo()functions, wherefoois a placeholder for daily,weekly,monthly,quarterly, or yearly. Here, the function FUN will be applied to the time series data contained in the non-overlapping periods as defined by foo. The second set of functions consist of period.apply()and wrapper functionsperiod.foo(), wherefoois a shortcut for the functionsmax, min,prod, orsum. These routines return the function value pertinent to the time intervals implied by the argumentindex, and the sub-sequences are defined asIN- DEX[k]toINDEX[k + 1]fork = 1 : (length(INDEX)-1). Finally, the methodsplit.xts()enables the user to split anxtsobject according to a certain periodicity. This method returns alistobject ofxtsobjects in which the elements are the time series data of the requested non-overlapping periods.

References

Armstrong W. 2009its: Irregular Time Series. R package version 1.1.8.

Armstrong W. 2014fts: R interface to tslib (a time series library in C++). R package version 0.9.9.

Chalabi Y., Mọchler M., and Wỹrtz D. 2011 Rmetrics – timeDate Package.The R Journal3(1), 19–24.

Gilbert P. 2015atframe: Time Frame Coding Kernel. R package version 2015.12-1.

Gilbert P. 2015b tframePlus: Time Frame Coding Kernel Extensions. R package version 2015.1-2.

Grothendieck G. and Petzoldt T. 2004 R Help Desk: Date and time classes in R.R News4(1), 29–32.

k k Hallman J. 2015tis: Time Indexes and Time Indexed Series. R package version 1.30.

James D. and Hornik K. 2015chron: Chronological Objects which Can Handle Dates and Times. R package version 2.3-47. S original by David James, R port by Kurt Hornik.

Plummer M., Best N., Cowles K., and Vines K. 2006 CODA: Convergence diagnosis and output analysis for MCMC.R News6(1), 7–11.

Ripley B. and Hornik K. 2001 Date-time classes.R News1(2), 8–11.

Ryan J. and Ulrich J. 2014xts: eXtensible Time Series. R package version 0.9-7.

Therneau T., Lumley T., Halvorsen K., and Hornik K. 2014date: Functions for handling dates.

R package version 1.2-34. S original by Terry Therneau, R port by Thomas Lumley, Kjetil Halvorsen, and Kurt Hornik.

Trapletti A. and Hornik K. 2016tseries: Time Series Analysis and Computational Finance. R package version 0.10-35.

Wüertz D., Chalabi Y., and Ellis A. 2009A Discussion of Time Series Objects for R in Finance Rmetrics Ebook Series. Finance Online GmbH, Zürich.

Würtz D., Chalabi Y., Maechler M., and Byers J. 2015atimeDate: Rmetrics – Chronological and Calendar Objects. R package version 3012.100.

Würtz D., Setz T., and Chalabi Y. 2015btimeSeries: Rmetrics – Financial Time Series Objects.

R package version 3022.101.2.

Zeileis A. and Grothendieck G. 2005 zoo: S3 infrastructure for regular and irregular time series.

Journal of Statistical Software14(6), 1–27.

k k

Appendix C

Back-testing and reporting of portfolio strategies

Một phần của tài liệu Financial risk modelling and portfolio optimization with r second edition (Trang 412 - 417)

Tải bản đầy đủ (PDF)

(436 trang)