TimeDateClass {fCalendar}R Documentation

timeDate Class, Functions and Methods

Description

A collection and description of functions and methods for managing date and time around the globe for any financial center. The concept allows for dealing with time zones, day light saving time and holiday calendars independent of the date and time specifications of the operating system implemented on your computer. This is an important issue especially for R running under Microsoft's Windows operating system.

The functions for Financial Centers are:

rulesFinCenter Returns DST rules for a financial center,
listFinCenter Lists all supported financial centers.

The functions for the Generation of 'timeDate' Objects are:

timeDate S4: Creates 'timeDate' object from a character vector,
timeCalendar S4: Creates 'timeDate' object from calendar atoms,
timeSequence S4: Creates regularly spaced object of class 'timeDate',
Sys.timeDate Returns system time as an object of class 'timeDate'.

The functions for Special Monthly 'timeDate' Sequences are:

timeLastDayInMonth Computes the last day in a given month and year,
timeNdayOnOrAfter Computes date that is a "on-or-after" n-day,
timeNdayOnOrBefore Computes date that is a "on-or-before" n-day,
timeNthNdayInMonth Computes n-th ocurrance of a n-day in year/month,
timeLastNdayInMonth Computes the last n-day in year/month.

The functions for the Representation of 'timedate' Objects are:

is.timeDate Checks if the object is of class 'timeDate',
print.timeDate S3: Prints 'timeDate', 'FinCenter' and 'Data' Slot,
summary.timeDate S3: Summarizes details of a 'timeDate' object,
format.timeDate Formats 'timeDate' as ISO conform character string.

Additional Calendar Date Functions:

isWeekday Tests if a date is a weekday or not,
isWeekend Tests if a date falls on a weekend or not,
isBizday Tests if a date is a business day or not,
weekDay Returns the day of the week.

Methods for Math Operations with 'timeDate' Objects are:

[.timeDate Extracts, replaces subsets from 'timeDate' objects,
+.timeDate Performs arithmetic + ops on 'timeDate' objects,
-.timeDate Performs arithmetic - ops on 'timeDate' objects,
Ops.timeDate 'Ops' generic functions for 'timeDate' objects,
diff.timeDate Returns suitably lagged and iterated differences,
difftimeDate Returns a difference of two 'timeDate' objects,
c.timeDate Concatenates objects of class 'timeDate',
rep.timeDate Replicates objects of class 'timeDate',
start.timeDate Extracts the first object of a 'timeDate' vector,
end.timeDate Extracts the last object of a 'timeDate' vector,
modify.timeDate Sorts, rounds or truncates a 'timeDate' object,
rev.timeDate Reverts a 'timeDate' vector object.

Mthods for Transformations of 'timeDate' Objects are:

as.character.timeDate Returns a 'timeDate' object as character string,
as.data.frame.timeDate Returns a 'timeDate' object as data frame,
as.POSIXct.timeDate Returns a 'timeDate' object as POSIXct object,
as.POSIXlt As POSIXlt, Use Method (Overwrite),
as.POSIXlt.default Default method for POSIXlt,
julian.timeDate Returns Julian day counts since 1970-01-01,
julian.POSIXt A Julian Patch,
atoms.timeDate Returns date/time atoms from a 'timeDate' object,
atoms Extract atoms, Use Method,
atoms.default Default method for atoms,
months.timeDate Extract months atom from a 'timeDate' object.

Usage

rulesFinCenter(FinCenter = myFinCenter)
listFinCenter(pattern = "*")

timeDate(charvec, format = NULL, zone = "GMT", FinCenter = myFinCenter) 
timeCalendar(y = currentYear, m = 1:12, d = NULL, h = NULL, min = NULL, 
    s = NULL, FinCenter = myFinCenter)
timeSequence(from = "2004-01-01", to = format(Sys.time(), "%Y-%m-%d"), 
        by = "day", length.out = NULL, format = "", FinCenter = myFinCenter)
Sys.timeDate(FinCenter = myFinCenter) 

timeLastDayInMonth(charvec, format = "%Y-%m-%d", 
        FinCenter = "GMT")
timeNdayOnOrAfter(charvec, nday = 1, format = "%Y-%m-%d", 
        FinCenter = "GMT")
timeNdayOnOrBefore(charvec, nday = 1, format = "%Y-%m-%d",   
        FinCenter = "GMT")
timeNthNdayInMonth(charvec, nday = 1, nth = 1, format = "%Y-%m-%d", 
    FinCenter = "GMT")
timeLastNdayInMonth(charvec, nday = 1, format = "%Y-%m-%d", 
        FinCenter = "GMT")

is.timeDate(object) 
## S3 method for class 'timeDate':
print(x, ...)
## S3 method for class 'timeDate':
summary(object, ...)
## S3 method for class 'timeDate':
format(x, ...)

isWeekday(x)
isWeekend(x)
isBizday(x, holidays = holiday.NYSE())
weekDay(x)

## S3 method for class 'timeDate':
x[..., drop = TRUE]
## S3 method for class 'timeDate':
e1 + e2
## S3 method for class 'timeDate':
e1 - e2
## S3 method for class 'timeDate':
Ops(e1, e2)
## S3 method for class 'timeDate':
diff(x, lag = 1, differences = 1, ...)
difftimeDate(time1, time2, 
        units = c("auto", "secs", "mins", "hours", "days", "weeks"))

## S3 method for class 'timeDate':
c(..., recursive = FALSE)
## S3 method for class 'timeDate':
rep(x, times, ...)
## S3 method for class 'timeDate':
start(x, ...)
## S3 method for class 'timeDate':
end(x, ...)
## S3 method for class 'timeDate':
modify(x, method = c("sort", "round", "trunc"),
        units = c("secs", "mins", "hours", "days"))
## S3 method for class 'timeDate':
rev(x)

## S3 method for class 'timeDate':
as.character(x, ...)
## S3 method for class 'timeDate':
as.data.frame(x, ...)
## S3 method for class 'timeDate':
as.POSIXct(x, tz = "")
## S3 method for class 'timeDate':
julian(x, ...)
## S3 method for class 'timeDate':
atoms(x, ...)
## S3 method for class 'timeDate':
months(x, abbreviate = NULL)

Arguments

abbreviate [months] -
currently not used.
by a character string, containing one of "sec", "min", "hour", "day", "week", "month" or "year". This can optionally be preceded by an integer and a space, or followed by "s".
charvec a character vector of dates and times.
differences [lag] -
an integer indicating the order of the difference.
drop ["["] -
a logical flag, by default TRUE.
e1, e2 ["+"][["-"]["Ops"] -
usually objects of class timeDate, in the case of addition and subtraction e2 may be of class numeric.
FinCenter a character with the the location of the financial center named as "continent/city".
format the format specification of the input character vector.
from, to starting date, required, and end date, ptional. If supplied to must be after from.
h, min, s hours of the days (0-23), defaults are 0, minutes of the days (0-59), defaults are 0, and seconds of the days (0-59), defaults are 0.
holidays [isBizday] -
holiday dates from a holiday calendar. An object of class timeDate.
lag [lag] -
an integer indicating which lag to use.
length.out length.out integer, optional. Desired length of the sequence, if specified "to" will be ignored.
nday an integer vector with entries ranging from 0 (Sunday) to 6 (Saturday).
method [modify] -
a character string defining the modification method, one of "sort", "round", or "trunc".
nth an integer vector numbering the n-th occurence.
object [is.timeData][summary] -
an object of class timeDate.
pattern a pattern character string which can be recognized by the grep function. Wild cards are allowed.
recursive [c] -
a logical. If recursive is set to TRUE, the function recursively descends through lists combining all their elements into a vector.
time1, time2 [difftime] -
two objects objects of class timeDate.
times [rep] -
an optional non-negative integer. A vector giving the number of times to repeat each element if of length length(x), or to repeat the whole vector if of length 1.
tz inputs the time zone to POSIX objects, i.e. the time zone, zone, or financial center string, FinCenter, as used by timeDate objects.
units a character string denoting the date/time units in which the results are desired.
x [isWeekday][isWeekend][isBizday][weekDay] -
an object of class timeDate.
[format][print] -
an object of class timeDate.
y, m, d calendar years (e.g. 1997), defaults are 1960, calendar months (1-12), defaults are 1, and calendar days (1-31), defaults are 1.
zone the time zone or financial center where the data were recorded.
... arguments passed to other methods.

Details

For the management of chronological objects under R three concepts are available: The first is the implementation of date and time in R's chron package neglecting locals, time zones and day light saving times. This approach is appropriate for economic time series. The second approach, available in R's base package implements the POSIX standard to date and time objects, named "POSIXt". Unfortunately, the representation of these objects is operating system dependent and especially under MS Windows several problems appear in the management of time zones and day light saving times. Here we present a solution to overcome these difficulties with POSIX objects and introduce a new S4 class of 'timeDate' objects which allow for powerful methods to represent dates and times in different financial centers around the world. Many of the basic functionalities of these objects are in common with S-Plus' timeDate objects and thus many of your privately written functions for FinMetrics may also be used within R's environment.

A major difference is the time zone concept which is replaced by the "Financial Center" concept. The FinCenter character variable specifies where you are living and at which financial center you are working. With the variable myFinCenter you can overwrite the default setting with your personal settings. With the specification of the FinCenter your system knows what rules rules for day light saving times should be applied, what is your holiday calendar, what are your interest rate conventions. (Not all specifications are already implemented.) Many other aspects can be easily accessed when a financial center is named. So we can distinguish between Frankfurt and Zurich, which both belong to the same time zone, but differed in DST changes in the eighties and have different holiday calendars. Futhermore, since the underlying time refers to "GMT" and DST rules and all other information is available in local (ASCII) databases, we are sure, that R delivers with such a date/time concept on every computer independent of the operating system in use, identical results.

Another important feature of the "timeDate" concept used here is the fact that we don't rely on American or European ways to write dates. We use consequently the ISO-8601 standard for date and time notations.

Financial Centers

There are two functions concerned with the financial centers. The first, rulesFinCenter, lists the daylight saving rules for a selected financial center, and the second, listFinCenter, lists all centers available in the database. There is no dependency on the POSIX implementation of your operating system because all time zone and day light saving time information is stored locally in ASCII files. It is important to say, that the TZ environment variable must set to "GMT" in your system environment that there are no conflicts with the POSIX time zone management.

Through the definition of financial centers it becomes possible to introduce in the future a specification structure for financial centers, which includes further information for a center like holiday calendars, currency and interest rate conventions or many others.

Generation of timeDate Objects

We have defined a 'timeDate' class which is in many aspects similar to the S-Plus class with the same name, but has also some important advantageous differeneces. The S4 class has four Slots, the Data slot which holds date and time as 'POSIXlt' objects in the standard ISO-8601 format, the Dim slot which gives the dimension of the data object, the format specification slot and the FinCenter slot which holds the name of the financial center.

Three functions allow to cgenerate date/time objects: timeDate from character vectors, timeCalendar from date and time atoms, and timeSequence from a "from/to" or from a "from/length" sequence specification. Note, time zone transformations are easily handled by by the timeDate functions which can also take timeDate and POSIXt objects as inputs, while transforming them between financial centers and/or time zones specified by the arguments zone and FinCenter. Finally the function Sys.timeDate returns current system time in form of a timeDate object.

Special Monthly timeDate Sequences

We have implemented five functions to generate special monthly sequences. These are functions to compute the last day in a given month and year, to compute the dates in a month that is a n-day on or after a given date, to compute the dates in a month that is a n-day on or before a specified date, to compute the n-th ocurrances of a n-day for a specified year/month vectors, and finally to compute the last n-day for a specified year/month value or vector. n-days are numbered from 0 to 6 where 0 correspond to the Sunday and 6 to the Saturday.

Tests and Representation of timeDate Objects:

We have implemented four methods to test and represent timeDate objects. The method is.timeDate checks if a given object is of class "timeDate". The print method returns the date/time in square "[]" brackets to dsitinguish the output from other date and time objects. On top of the date and time output the name of the FinCenter is printed. The summary method returns a printed report with information about the "timeDate" object. Finally, the format methods allows to transform objects into a ISO conform formatted character strings.

Mathematical Operations:

This is a collection of S3 methods for objects of class timeDate to perform mathematical operations. Included are methods to extracts or replace subsets from timeDate objects, to perform arithmetic "+" and "-" operations, to group 'Ops' generic functions, to return suitably lagged and iterated differences, to return differences of two timeDate objects, to concatenate objects, to replicate objects, to rounds objects, to truncates objects, to extract the first or last entry of a vector, to sort the objects of the elements of a date/time vector, and to revert timeDate vector objects.

Transformation of Objects:

This is a collection of S3 methods for objects of class timeDate to transform those objects between different representations. Included are methods to transform timeDate objects to character strings, to data frames, to POSIXct or POSIXlt objects, to Julian counts, to extract date/time atoms from calendar dates, and to extract the months atom from a timeDate object.

Value

rulesFinCenter
listFinCenter
the first function returns a printed list of DST rules, the second lists time zones available in the database.

timedate
timeCalendar
timeSequence
return a S4 object of class 'timeDate'.

Sys.timeDate
returns the system time as an object of class 'timeDate'.

timeLastDayInMonth
timeNdayOnOrAfter
timeNdayOnOrBefore
timeNthNdayInMonth
timeLastNdayInMonth
return timeDate objects on special dates. For the function timeLastDayInMonth the last day in a given month and year will be returned, for timeNdayOnOrAfter the date in the specified month that is a n-day on or after a given date, for timeNdayOnOrBefore the date that is a n-day on or before a given date, for timeNthNdayInMonth the nth ocurrance of a nday (nth = 1,...,5) in year, month, and for {timeLastNdayInMonth} the last nday in year, month.

is.timeDate
returns TRUE or FALSE depending on whether its argument is of timeDate type or not.

isWeekday
isWeekend
isBizday
weekDay
The first thres functions return logical vectors indicating if a date is a weekday, a weekend day, or a business.day. The function weekDay returns a three letter character string with the names of the day of the week.

Print Method:
prints the financial center and date and time vector for a timeDate object.

Summary Method:
returns a summary report of the details of a timeDate object. This includes the starting and end date, the number of dates the format and financial center in use.

Format Method:
returns an ISO conform formatted character string.

"["
returns a subset from a timeDate object.

"+"
"-"
the plus operator "+" performs arithmetic "+" operation on timeDate objects, and the minus operator "-" returns a difftime object if both arguments e1 and e2 are timeDate objects, or returns a timeDate object e2 seconds earlier than e1.

Ops.timeDate
returns the Ops grouped object.

diff
difftimeDate
For the first function, diff.timeDate, if x is a vector of length n and differences=1, then the computed result is equal to the successive differences x[(1+lag):n] - x[1:(n-lag)]. If difference is larger than one this algorithm is applied recursively to x. Note that the returned value is a vector which is shorter than x. The second function, difftimeDate, takes a difference of two timeDate objects and returns an object of class difftime with an attribute indicating the units.

c
rep
c returns all its arguments to be coerced to a timeDate object which is the type of the returned value, and rep returns a vector of repeated elements belonging to the same class as x.

start
end
return from x the earliest or latest entry as an object of class timeDate, respectively.

modify
rev
modify returns x as a sorted, rounded or truncated object of the same class, depending on the method selection, and rev returns x as a timeDate object in reversed order.

as.character
as.data.frame
return a timeDate object trnasformed into a character or a data frame formatted object.

as.POSIXct
return a timeDate object trnasformed into a POSIX type formatted object.

julian
return a timeDate object as a Julian count.

atoms
months.timeDate
extrac from a timeDate object the calendar atoms, i.e, the year, month, day, and optionally hour, minute and second.

Note

These functions were written for Rmetrics users using R and Rmetrics under Microsoft's Windows XP operating system where time zones, daylight saving times and holiday calendars are not or insuffeciently supported. The functions are untested for other system environments, but may be used.

The usage of the Ical Library and the introduction of the FinCenter concept was originally develloped for R Version 1.5. The timeDate and timeSeries objects were added for R Version 1.8.1. Minor changes were made to adapt the functions for R Version 1.9.1. As a consequence, newer concepts like the Date objects were not yet considered and included in this collection of date and time concepts.

Note, the date/time conversion from an arbitry timezone to GMT cannot be unique, since date/time objects appear twice during the hour when DST changes. A bookkeeping which takes care if DST is effective or not is not yet included. However, in most applications this is not important since the markets are closed on weekends, especially at times when DST usually changes. It is planned for the future to implement the DST change properly.

The ISO-8601 midnight standard has been implemented. Note, that for example "2005-01-01 24:00:00" is a valid date/time string.

IT IS IMPORTANT THAT YOU SET YOUR ENVIRONMENT VARIABLE TZ TO 'GMT', OTHERWISE SOME OF THE 'TIMEDATE' FUNCTIONS WOULD NOT PROPERLY WORK!

Beside the examples given in the manual pages additional demo files are available with much more examples including also those from the book of Zivot and Wang.

Author(s)

Diethelm Wuertz for the Rmetrics R-port.

References

Bateman R., (2000); Time Functionality in the Standard C Library, Novell AppNotes, September 2000 Issue, 73–85.

ISO-8601, (1988); Data Elements and Interchange Formats - Information Interchange, Representation of Dates and Time, International Organization for Standardization, Reference Number ISO 8601, 14 pages.

James D.A., Pregibon D. (1992), Chronological Objects for Data Analysis, Reprint.

Ripley B.D., Hornik K. (2001); Date-Time Classes, R-News, Vol. 1/2 June 2001, 8–12.

Zivot, E., Wang J. (2003); Modeling Financial Time Series with S-Plus, Springer, New-York.

See Also

We recommend to inspect the help pages for the POSIX time and date class, ?Dates, and the help pages from the contributed R packages chron and date.

Examples

## SOURCE("fCalendar.23A-TimeDateClass")

## c -
   xmpCalendar("\nStart: Create Character Vectors > ") 
   dts = c("1989-09-28", "2001-01-15", "2004-08-30", "1990-02-09")
   tms = c(  "23:12:55",   "10:34:02",   "08:30:00",   "11:18:23")
   dts; tms
   
## timeDate -
   xmpCalendar("\nNext: Construct timeDate Object from Character Vector > ") 
   timeDate(dts, format = "%Y-%m-%d", FinCenter = "GMT" )
   timeDate(dts, format = "%Y-%m-%d", FinCenter = "Europe/Zurich") 
   timeDate(paste(dts, tms), format = "%Y-%m-%d %H:%M:%S", 
     zone = "GMT", FinCenter = "GMT")
   timeDate(paste(dts, tms), format = "%Y-%m-%d %H:%M:%S", 
     zone = "Europe/Zurich", FinCenter = "Europe/Zurich")
   timeDate(paste(dts, tms), format = "%Y-%m-%d %H:%M:%S", 
     zone = "GMT", FinCenter = "Europe/Zurich") 
    
## timeCalendar - 
   xmpCalendar("\nNext: Create a timeDate Object From Calendar Atoms > ")
   timeCalendar( m = c(9, 1, 8, 2), d = c(28, 15, 30, 9), 
     y = c(1989, 2001, 2004, 1990), FinCenter = "GMT") 
   timeCalendar(m = c(9, 1, 8, 2), d = c(28, 15, 30, 9), 
     y = c(1989, 2001, 2004, 1990), FinCenter = "Europe/Zurich")
   timeCalendar(h = c(9, 14), min = c(15, 23)) 
  
## timeSequence - 
   xmpCalendar("\nNext: Create a Regularly Spaced timeDate Objects > ")
   timeSequence(from = "2004-03-12", to = "2004-04-11", 
        format = "%Y-%m-%d", FinCenter = "GMT")  
   timeSequence(from = "2004-03-12", to = "2004-04-11", 
        format = "%Y-%m-%d", FinCenter = "Europe/Zurich")
   
## timeDate - 
   xmpCalendar("\nNext: Note, ISO and American Formats are Auto-Detected > ")
   timeDate("2004-12-11", FinCenter = "GMT")    
   timeDate("12/11/2004", FinCenter = "GMT")   
  
## SOURCE("fBasics.A0-SPlusCompatibility")
## SOURCE("fBasics.E1-TimeDateClass")
## SOURCE("fBasics.E2-TimeDatemethods")
## SOURCE("fBasics.Z1-BasicsTools")

## c -
   xmpCalendar("\nStart: Create Character Vectors > ") 
   dts = c("1989-09-28", "2001-01-15", "2004-08-30", "1990-02-09")
   tms = c(  "23:12:55",   "10:34:02",   "08:30:00",   "11:18:23")
   dts; tms
   
## "+/-" - 
   xmpCalendar("\nStart: Add One Day to a Given timeDate Object > ")
   GMT = timeDate(dts, FinCenter = "GMT")
   ZUR = timeDate(dts, FinCenter = "Europe/Zurich")
   GMT + 24*3600
   ZUR[2] - ZUR[1]
  
## "[" - 
   xmpCalendar("\nNext: Subsets from and Lops for timeDate Objects > ")
   GMT[GMT < GMT[2]]
   ZUR[ZUR < ZUR[3]] == ZUR[1:3]

## diff - 
   xmpCalendar("\nNext: Suitably Lagged and Iterated Differences > ")
   diff(GMT)
   diff(GMT, lag = 2)
   diff(GMT, lag = 1, diff = 2)
   difftimeDate(GMT[1:2], GMT[-(1:2)])
   
## c | rep - 
   xmpCalendar("\nNext: Concatenate and Replicate timeDate Objects > ") 
   c(GMT[1:2], ZUR[1:2])
   c(ZUR[1:2], GMT[1:2])
   rep(ZUR[2], times = 3)
   rep(ZUR[2:3], times = 2) 

## round | truncate -
   xmpCalendar("\nNext: Round and Truncate timeDate Objects > ")
   modify(GMT, "round", "days")
   modify(ZUR, "round", "days")
   modify(GMT, "trunc", "days")
   modify(ZUR, "trunc", "days")

## start | end | sort - 
   xmpCalendar("\nNext: Extract First/Last, Sort timeDate Objects > ")
   c(start(ZUR), end(ZUR))
   modify(ZUR, "sort") 

## as -
   xmpCalendar("\nNext: Convert timeDate Objects to Other Objects > ")
   as.character(ZUR)
   as.data.frame(ZUR)
   as.POSIXct(ZUR)
   
## julian - 
   xmpCalendar("\nNext: Julian Time in Days Since 1970-01-01 > ")
   julian(ZUR)  
   as.integer(julian(ZUR))
   julian(ZUR, "days")  
   as.integer(julian(ZUR, "days"))
    
## atoms - 
   xmpCalendar("\nNext: Atoms from a timeDate Object > ")
   atoms(ZUR)
   atoms(ZUR)[,3]
   atoms(ZUR)[, "d"] 

[Package fCalendar version 221.10065 Index]