Title: | Financial Time Series Objects (Rmetrics) |
---|---|
Description: | 'S4' classes and various tools for financial time series: Basic functions such as scaling and sorting, subsetting, mathematical operations and statistical functions. |
Authors: | Diethelm Wuertz [aut] (original code), Tobias Setz [aut], Yohan Chalabi [aut], Martin Maechler [ctb] , Georgi N. Boshnakov [cre, aut] |
Maintainer: | Georgi N. Boshnakov <[email protected]> |
License: | GPL (>= 2) |
Version: | 4041.111 |
Built: | 2024-10-23 06:19:12 UTC |
Source: | CRAN |
Package timeSeries is part of the Rmetrics suit of R packages.
It provides a class, timeSeries
, particularly aimed at analysis
of financial data, along with many methods, functions, and utilities
for statistical and financial computations on time series.
The following sections have not been updated for some time.
timeSeries |
Creates a "timeSeries" from scratch |
series , coredata |
Extracts the data |
getUnits |
Extracts the time serie units |
time |
Extracts the positions of timestamps |
x@format |
Extracts the format of the timestamp |
finCenter |
Extracts the financial center |
x@recordIDs |
Extracts the record IDs |
x@title |
Extracts the title |
x@documentation |
Extracts the documentation |
apply |
Applies a function to blocks of a "timeSeries" |
cbind |
Combines columns of two "timeSeries" objects |
rbind |
Combines rows of two "timeSeries" objects |
diff |
Returns differences of a "timeSeries" object |
dim |
returns dimensions of a "timeSeries" object |
merge |
Merges two "timeSeries" objects |
rank |
Returns sample ranks of a "timeSeries" object |
rev |
Reverts a "timeSeries" object |
sample |
Resamples a "timeSeries" object |
scale |
Scales a "timeSeries" object |
sort |
Sorts a "timeSeries" object |
start |
Returns start date/time of a "timeSeries" |
end |
Returns end date/time of a "timeSeries" |
end |
Returns end date/time of a "timeSeries" |
t |
Returns the transpose of a "timeSeries" object |
attach |
Attaches a "timeSeries" to the search path
|
[ |
Subsets a "timeSeries" object |
[<- |
Assigns values to a subset |
$ |
Subsets a "timeSeries" by column names |
$<- |
Replaces subset by column names |
head |
Returns the head of a "timeSeries" |
tail |
Returns the tail of a time Series |
na.omit |
Handles NAs in a "timeSeries" object |
removeNA |
removes NAs from a matrix object |
substituteNA |
substitutes NAs by zero, column mean or median |
interpNA |
interpolates NAs using R's "approx" function |
Ops |
S4: Arith method for a "timeSeries" object |
Math |
S4: Math method for a "timeSeries" object |
Math2 |
S4: Maths method for a "timeSeries" object |
abs |
Returns absolute values of a "timeSeries" object |
sqrt |
Returns square root of a "timeSeries" object |
exp |
Returns the exponential values of a "timeSeries" object |
log |
Returns the logarithm of a "timeSeries" object |
sign |
Returns the signs of a "timeSeries" object |
diff |
Differences a "timeSeries" object |
scale |
Centers and/or scales a "timeSeries" object |
quantile |
Returns quantiles of an univariate "timeSeries"
|
as.timeSeries |
Defines method for a "timeSeries" |
as.*.default |
Returns the input |
as.*.ts |
Transforma a 'ts' object into a "timeSeries" |
as.*.data.frame |
Transforms a 'data.frame' intp a 'timeSeries |
as.*.character |
Loads and transforms from a demo file |
as.*.zoo |
Transforms a 'zoo' object into a "timeSeries" |
as.vector.* |
Converts univariate "timeSeries" to vector |
as.matrix.* |
Converts "timeSeries" to matrix |
as.numeric.* |
Converts "timeSeries" to numeric |
as.data.frame.* |
Converts "timeSeries" to data.frame |
as.ts.* |
Converts "timeSeries" to ts |
as.logical.* |
Converts "timeSeries" to logical |
is.timeSeries |
Tests for a "timeSeries" object |
plot |
Displays a X-Y "timeSeries" Plot |
lines |
Adds connected line segments to a plot |
points |
Adds Points to a plot |
show |
Prints a 'timeSeries oobject |
align |
Aligns a "timeSeries" to time stamps |
cumulated |
Computes cumulated series from a returns |
alignDailySeries |
Aligns a "timeSeries" to calendarical dates |
rollDailySeries |
Rolls a 'timeSeries daily |
drawdowns |
Computes series of drawdowns from financial returns |
drawdownsStats |
Computes drawdowns statistics |
durations |
Computes durations from a financial time series |
countMonthlyRecords |
Counts monthly records in a "timeSeries" |
rollMonthlyWindows |
Rolls Monthly windows |
rollMonthlySeries |
Rolls a "timeSeries" monthly |
endOfPeriodSeries |
Returns end of periodical series |
endOfPeriodStats |
Returns end of period statistics |
endOfPeriodBenchmarks |
Returns period benchmarks |
returns |
Computes returns from prices or indexes |
returns0 |
Computes untrimmed returns from prices or indexes |
runlengths |
Computes run lenghts of a "timeSeries" |
smoothLowess |
Smoothes a "timeSeries" |
smoothSpline |
Smoothes a "timeSeries" |
smoothSupsmu |
Smoothes a "timeSeries" |
splits |
Detects "timeSeries" splits by outlier detection |
spreads |
Computes spreads from a price/index stream |
turns |
Computes turning points in a "timeSeries" object |
turnsStats |
Computes turning points statistics |
colCumsums |
Computes cumulated column sums of a "timeSeries" |
colCummaxs |
Computes cumulated maximum of a "timeSeries" |
colCummins |
Computes cumulated minimum of a "timeSeries" |
colCumprods |
Computes cumulated pruduct values by column |
colCumreturns |
Computes cumulated returns by column |
colSums |
Computes sums of all values in each column |
colMeans |
Computes means of all values in each column |
colSds |
Computes standard deviations of all values in each column |
colVars |
Computes variances of all values in each column |
colSkewness |
Computes skewness of all values in each column |
colKurtosis |
Computes kurtosis of all values in each column |
colMaxs |
Computes maxima of all values in each column |
colMins |
Computes minima of all values in each column |
colProds |
Computes products of all values in each column |
colStats |
Computes statistics of all values in each column |
orderColnames |
Returns ordered column names of a "timeSeries" |
sortColnames |
Returns alphabetically sorted column names |
sampleColnames |
Returns sampled column names of a "timeSeries" |
pcaColnames |
Returns PCA correlation ordered column names |
hclustColnames |
Returns hierarchically clustered columnames |
statsColnames |
Returns statisticall rearrange columnames |
orderStatistics |
Computes order statistics of a "timeSeries" object |
rollMean |
Computes rolling means of a "timeSeries" object |
rollMin |
Computes rolling minima of a "timeSeries" object |
rollMax |
Computes rolling maxima of a "timeSeries" object |
rollMedian |
Computes rolling medians of a "timeSeries" object |
rollStats |
Computes rolling statistics of a "timeSeries" objectcr |
rowCumsums |
Computes cumulated column sums of a "timeSeries" |
smoothLowess |
Smoothes a series with lowess function |
smoothSupsmu |
Smoothes a series with supsmu function |
smoothSpline |
Smoothes a series with smooth.spline function |
dummyDailySeries |
Creates a dummy daily "timeSeries" object |
isMonthly |
Decides if the series consists of monthly records |
isDaily |
Decides if the series consists of daily records |
isQuarterly |
Decides if the series consists of Quarterly records |
description |
Creates default description string |
Diethelm Wuertz [aut] (original code), Tobias Setz [aut], Yohan Chalabi [aut], Martin Maechler [ctb] (<https://orcid.org/0000-0002-8685-9910>), Georgi N. Boshnakov [cre, aut]
Maintainer: Georgi N. Boshnakov <[email protected]>
Aggregate a "timeSeries"
object over general periods.
## S4 method for signature 'timeSeries' aggregate(x, by, FUN, ...)
## S4 method for signature 'timeSeries' aggregate(x, by, FUN, ...)
x |
an object of class |
by |
a sequence of |
FUN |
the function to be applied. |
... |
arguments passed to other methods. |
aggregate
aggregates x
by applying FUN
on the
values of the time series in each of the aggregation periods,
specified by argument by
.
Argument by
should be of the same class as
time(x)
. by
is sorted and duplicated values are removed
from it. Each pair of consecutive values in by
then determines
a period over which to apply the aggregation function FUN
, see
findInterval
.
an object of class "timeSeries"
## Load Microsoft Data Set - x <- MSFT ## Aggregate by Weeks - by <- timeSequence(from = start(x), to = end(x), by = "week") aggregate(x, by, mean) ## Aggregate to Last Friday of Month - by <- unique(timeLastNdayInMonth(time(x), 5)) X <- aggregate(x, by, mean) X dayOfWeek(time(X)) isMonthly(X) ## Aggregate to Last Day of Quarter - by <- unique(timeLastDayInQuarter(time(x))) X <- aggregate(x, by, mean) X isQuarterly(X)
## Load Microsoft Data Set - x <- MSFT ## Aggregate by Weeks - by <- timeSequence(from = start(x), to = end(x), by = "week") aggregate(x, by, mean) ## Aggregate to Last Friday of Month - by <- unique(timeLastNdayInMonth(time(x), 5)) X <- aggregate(x, by, mean) X dayOfWeek(time(X)) isMonthly(X) ## Aggregate to Last Day of Quarter - by <- unique(timeLastDayInQuarter(time(x))) X <- aggregate(x, by, mean) X isQuarterly(X)
Aligns a "timeSeries"
object to equidistant time stamps. There
are also functions for the common cases of changing daily to weekly
and daily to monthly.
## S4 method for signature 'timeSeries' align(x, by = "1d", offset = "0s", method = c("before", "after", "interp", "fillNA", "fmm", "periodic", "natural", "monoH.FC"), include.weekends = FALSE, ...) alignDailySeries(x, method = c("before", "after", "interp", "fillNA", "fmm", "periodic", "natural", "monoH.FC"), include.weekends = FALSE, units = NULL, zone = "", FinCenter = "", ...) daily2monthly(x, init = FALSE) daily2weekly(x, startOn = "Tue", init = FALSE)
## S4 method for signature 'timeSeries' align(x, by = "1d", offset = "0s", method = c("before", "after", "interp", "fillNA", "fmm", "periodic", "natural", "monoH.FC"), include.weekends = FALSE, ...) alignDailySeries(x, method = c("before", "after", "interp", "fillNA", "fmm", "periodic", "natural", "monoH.FC"), include.weekends = FALSE, units = NULL, zone = "", FinCenter = "", ...) daily2monthly(x, init = FALSE) daily2weekly(x, startOn = "Tue", init = FALSE)
x |
an object of class |
by |
a character string denoting the period. |
offset |
a character string denoting the offset. |
method |
the method to be used for the alignment. A character string, one of
|
include.weekends |
a logical value. Should weekend dates be included or removed from the series? |
units |
an optional character string, which allows to overwrite the current
column names of a |
zone |
the time zone or financial center where the data were recorded. |
FinCenter |
a character with the the location of the financial center named
as |
startOn |
a character string, specifying the day of week as a three letter
abbreviation. Weekly aggregated data records are then fixed to the
weekdays given by the argument |
init |
a logical value, if set to |
... |
further arguments to be passed to the interpolating function. |
TODO: complete.
alignDailySeries
aligns a daily 'timeSeries' to new positions,
Effectively, it is a frontend to the "timeSeries"
method for
align
with by = "1d"
, and offset = "0s"
.
In addition, there are two tailored functions for common cases:
daily2monthly
and daily2weekly
which aggregate
"timeSeries"
objects from daily to monthly or weekly levels,
respectively.
In the case of the function daily2weekly
one can explicitly set
the starting day of the week, the default value is Tuesday,
startOn = "Tue"
.
a "timeSeries"
object,
for alignDailySeries
, a weekly aligned daily "timeSeries"
object
from a daily time series with missing holidays.
## Use Microsofts' OHLCV Price Series - head(MSFT) end(MSFT) ## Use MSFT and Compute Sample Size - dim(MSFT) ## Align the Series - MSFT.AL <- align(MSFT) ## Show the Size of the Aligned Series - dim(MSFT.AL) ## alignDailySeries ## Cut out April Data from 2001 - Close <- MSFT[, "Close"] tsApril01 <- window(Close, start="2001-04-01", end="2001-04-30") tsApril01 ## Align Daily Series with NA - tsRet <- returns(tsApril01, trim = TRUE) GoodFriday(2001) EasterMonday(2001) alignDailySeries(tsRet, method = "fillNA", include.weekends = FALSE) alignDailySeries(tsRet, method = "fillNA", include.weekends = TRUE) ## Align Daily Series by Interpolated Values - alignDailySeries(tsRet, method = "interp", include.weekend = FALSE) alignDailySeries(tsRet, method = "interp", include.weekend = TRUE) ## Load Microsoft Data Set - x <- MSFT ## Aggregate daily records to end of month records - X <- daily2monthly(x) X isMonthly(X) ## Aggregate daily records to end of week records - X <- daily2weekly(x, startOn="Fri") X dayOfWeek(time(X))
## Use Microsofts' OHLCV Price Series - head(MSFT) end(MSFT) ## Use MSFT and Compute Sample Size - dim(MSFT) ## Align the Series - MSFT.AL <- align(MSFT) ## Show the Size of the Aligned Series - dim(MSFT.AL) ## alignDailySeries ## Cut out April Data from 2001 - Close <- MSFT[, "Close"] tsApril01 <- window(Close, start="2001-04-01", end="2001-04-30") tsApril01 ## Align Daily Series with NA - tsRet <- returns(tsApril01, trim = TRUE) GoodFriday(2001) EasterMonday(2001) alignDailySeries(tsRet, method = "fillNA", include.weekends = FALSE) alignDailySeries(tsRet, method = "fillNA", include.weekends = TRUE) ## Align Daily Series by Interpolated Values - alignDailySeries(tsRet, method = "interp", include.weekend = FALSE) alignDailySeries(tsRet, method = "interp", include.weekend = TRUE) ## Load Microsoft Data Set - x <- MSFT ## Aggregate daily records to end of month records - X <- daily2monthly(x) X isMonthly(X) ## Aggregate daily records to end of week records - X <- daily2weekly(x, startOn="Fri") X dayOfWeek(time(X))
Applies a function to a "timeSeries"
object over regular or
irregular time windows, possibly overlapping.
## S4 method for signature 'timeSeries' apply(X, MARGIN, FUN, ..., simplify = TRUE) fapply(x, from, to, FUN, ...) applySeries(x, from = NULL, to = NULL, by = c("monthly", "quarterly"), FUN = colMeans, units = NULL, format = x@format, zone = x@FinCenter, FinCenter = x@FinCenter, recordIDs = data.frame(), title = x@title, documentation = x@documentation, ...) rollDailySeries(x, period = "7d", FUN, ...)
## S4 method for signature 'timeSeries' apply(X, MARGIN, FUN, ..., simplify = TRUE) fapply(x, from, to, FUN, ...) applySeries(x, from = NULL, to = NULL, by = c("monthly", "quarterly"), FUN = colMeans, units = NULL, format = x@format, zone = x@FinCenter, FinCenter = x@FinCenter, recordIDs = data.frame(), title = x@title, documentation = x@documentation, ...) rollDailySeries(x, period = "7d", FUN, ...)
x , X
|
an object of class |
MARGIN |
a vector giving the subscripts which the function will be
applied over, see base R's |
FUN |
the function to be applied. For the function |
simplify |
simplify the result? |
from , to
|
starting date and end date as |
by |
a character value either |
units |
an optional character string, which allows to overwrite the current
column names of a |
format |
the format specification of the input character vector in POSIX notation. |
zone |
the time zone or financial center where the data were recorded. |
FinCenter |
a character value with the the location of the financial center named as "continent/city", or "city". |
recordIDs |
a data frame which can be used for record identification information. Note, this is not yet handled by the apply functions, an empty data.frame will be returned. |
title |
an optional title string, if not specified the input's data name is deparsed. |
documentation |
optional documentation string, or a vector of character strings. |
period |
a character string specifying the rollling period composed by the
length of the period and its unit, e.g. |
... |
arguments passed to other methods. |
The "timeSeries"
method for apply
extracts the core data
(a matrix) from X
and calls apply
, passing on all the
remaining arguments. If the result is suitable, it converts it to
"timeSeries"
, otherwise returns it as is. ‘Suitable’
here means that it is a matrix or a vector (which is converted to a
matrix) and the number of observations is the same as X
.
Like apply
applies a function to the margins of an array, the
function fapply
applies a function to the time stamps or signal
counts of a financial (therefore the “f” in front of the
function name) time series of class "timeSeries"
.
applySeries
takes a "timeSeries"
object as input and
applies FUN
to windows of x
. The windows are specified
by from
and to
, which need to have the same length. Then
from[i], to[i]
specifies the i
-th window. If
time(x)
is a "timeDate"
object, then from
and
to
are converted to "timeDate"
(if they are not already
such objects), otherwise they are converted to integers.
An alternative way to specify the window(s) on which
applySeries
operates is with argument by
. It is used
only if from
and to
are missing or NULL
. by
= "monthly"
or by = "quarterly"
applies FUN
to the data
for each year-month or year-quarter, respectively. By year-month we
mean that there are separate windows for the months in different
years.
The resulting time stamps are the time stamps of the to
vector. The periods can be regular or irregular, and they can even
overlap.
If from = start(x)
and to = end(x)
, then the function
behaves like apply
on the column margin.
fapply
is the same as applySeries
(in fact, the former
calls the latter), except that the defaults for from
and
to
are start(x)
and end(x)
, respectively. (GNB:
in addition, fapply
throws error if x
is a
‘signal series’.)
rollDailySeries
rolls a daily 'timeSeries' on a given period.
for rollDailySeries
, an object of class "timeSeries"
with
rolling values, computed from the function FUN
.
## Percentual Returns of Swiss Bond Index and Performance Index - LPP <- 100 * LPP2005REC[, c("SBI", "SPI")] head(LPP, 20) ## Aggregate Quarterly Returns - applySeries(LPP, by = "quarterly", FUN = colSums) ## Aggregate Quarterly every last Friday in Quarter - oneDay <- 24*3600 from <- unique(timeFirstDayInQuarter(time(LPP))) - oneDay from <- timeLastNdayInMonth(from, nday = 5) to <- unique(timeLastDayInQuarter(time(LPP))) to <- timeLastNdayInMonth(to, nday = 5) data.frame(from = as.character(from), to = as.character(to)) applySeries(LPP, from, to, FUN = colSums) ## Alternative Use - fapply(LPP, from, to, FUN = colSums) ## Count Trading Days per Month - colCounts <- function(x) rep(NROW(x), times = NCOL(x)) applySeries(LPP, FUN = colCounts, by = "monthly") ## TODO: examples for rollDailySeries()
## Percentual Returns of Swiss Bond Index and Performance Index - LPP <- 100 * LPP2005REC[, c("SBI", "SPI")] head(LPP, 20) ## Aggregate Quarterly Returns - applySeries(LPP, by = "quarterly", FUN = colSums) ## Aggregate Quarterly every last Friday in Quarter - oneDay <- 24*3600 from <- unique(timeFirstDayInQuarter(time(LPP))) - oneDay from <- timeLastNdayInMonth(from, nday = 5) to <- unique(timeLastDayInQuarter(time(LPP))) to <- timeLastNdayInMonth(to, nday = 5) data.frame(from = as.character(from), to = as.character(to)) applySeries(LPP, from, to, FUN = colSums) ## Alternative Use - fapply(LPP, from, to, FUN = colSums) ## Count Trading Days per Month - colCounts <- function(x) rep(NROW(x), times = NCOL(x)) applySeries(LPP, FUN = colCounts, by = "monthly") ## TODO: examples for rollDailySeries()
Functions and methods dealing with the coercion between "timeSeries"
and other classes.
## convert to 'timeSeries' as.timeSeries(x, ...) ## convert from 'timeSeries' to other classes ## S3 method for class 'timeSeries' as.ts(x, ...) ## S4 method for signature 'timeSeries' as.matrix(x, ...) ## S4 method for signature 'timeSeries' as.data.frame(x, row.names = NULL, optional = FALSE, ...) ## S4 method for signature 'timeSeries' as.list(x, ...)
## convert to 'timeSeries' as.timeSeries(x, ...) ## convert from 'timeSeries' to other classes ## S3 method for class 'timeSeries' as.ts(x, ...) ## S4 method for signature 'timeSeries' as.matrix(x, ...) ## S4 method for signature 'timeSeries' as.data.frame(x, row.names = NULL, optional = FALSE, ...) ## S4 method for signature 'timeSeries' as.list(x, ...)
x |
the object to be converted, see Section ‘Details’ for the
special case when |
row.names |
|
optional |
a logical value. If |
... |
arguments passed to other methods. |
Functions to create "timeSeries"
objects from other objects and
to convert "timeSeries"
objects to other classes.
as.timeSeries
is a generic function to convert an object to
"timeSeries"
. There are specialised methods for the following
classes: "ts"
, "data.frame"
, "character"
, and
"zoo"
. The default method is equivalent to calling
"timeSeries()"
, so x
can be of any type that
"timeSeries()"
accepts.
The character
method of as.timeSeries
is special, in
that its contents are parsed and evaluated, then as.timeSeries
is called on the returned value (passing also the "..."
arguments. Care is needed to avoid infinite recursion here since
currently the code doesn't guard against it.
for as.timeSeries
, an object of class "timeSeries"
.
for as.numeric
, as.data.frame
, as.matrix
,
as.ts
, as.list
- a numeric vector, a data frame, a
matrix, an object of class ts
, or a "list"
,
respectively.
timeSeries
,
class timeSeries
## Create an Artificial 'timeSeries' Object setRmetricsOptions(myFinCenter = "GMT") charvec <- timeCalendar() data <- matrix(rnorm(12)) TS <- timeSeries(data, charvec, units = "RAND") TS ## Coerce to Vector as.vector(TS) ## Coerce to Matrix as.matrix(TS) ## Coerce to Data Frame as.data.frame(TS)
## Create an Artificial 'timeSeries' Object setRmetricsOptions(myFinCenter = "GMT") charvec <- timeCalendar() data <- matrix(rnorm(12)) TS <- timeSeries(data, charvec, units = "RAND") TS ## Coerce to Vector as.vector(TS) ## Coerce to Matrix as.matrix(TS) ## Coerce to Data Frame as.data.frame(TS)
Attaches a "timeSeries"
object to the search path.
## S4 method for signature 'timeSeries' attach(what, pos = 2, name = deparse(substitute(what)), warn.conflicts = TRUE)
## S4 method for signature 'timeSeries' attach(what, pos = 2, name = deparse(substitute(what)), warn.conflicts = TRUE)
name |
alternative way to specify the database to be attached.
See for details |
pos |
an integer specifying position in |
warn.conflicts |
a logical value. If |
what |
database to be attached. This may currently be a |
the environment, invisibly, with a name
attribute
The function detach
from the base
package can be used to
detach the attached objects.
## Load Microsoft Data Set - x <- MSFT[1:10, ] colnames(x) ## Attach the Series and Compute the Range - attach(x) range <- High - Low range ## Convert Vector to a \code{"timeSeries"} Object - timeSeries(data=range, charvec=time(x), units="Range") ## Detach the series from the search path - detach("x") ans <- try(High, silent=TRUE) cat(ans[1])
## Load Microsoft Data Set - x <- MSFT[1:10, ] colnames(x) ## Attach the Series and Compute the Range - attach(x) range <- High - Low range ## Convert Vector to a \code{"timeSeries"} Object - timeSeries(data=range, charvec=time(x), units="Range") ## Detach the series from the search path - detach("x") ans <- try(High, silent=TRUE) cat(ans[1])
Extracts or assigns optional attributes from or to a
"timeSeries"
object.
getAttributes(obj) setAttributes(obj) <- value
getAttributes(obj) setAttributes(obj) <- value
obj |
a |
value |
an object, the new value of the attribute, or NULL to remove the attribute. |
Each timeSeries
object is documented. By default a time series
object holds in the documentation slot a string with creation time and
the user who has defined it. But this is not all. Optionally the whole
creation process and history can be recorded. For this the
@documentation
slot may have an optional "Attributes"
element. This attribute is tracked over the whole life time of the
object whenever the time series is changed. Whenever you like to be
informed about the optional attributes, or you like to recover them
you can dot it, and evenmore, whenever you like to add information as
an addiitonal attribute you can also do it.
The two functions getAttributes
and setAttributes
provide access to and allow to modify the optional attributes of a
timeSeries
object.
## Create an artificial 'timeSeries' Object - tS <- dummyMonthlySeries() tS ## Get Optional Attributes - getAttributes(tS) tS@documentation ## Set a new Optional Attribute - setAttributes(tS) <- list(what="A dummy Series") tS getAttributes(tS) tS@documentation
## Create an artificial 'timeSeries' Object - tS <- dummyMonthlySeries() tS ## Get Optional Attributes - getAttributes(tS) tS@documentation ## Set a new Optional Attribute - setAttributes(tS) <- list(what="A dummy Series") tS getAttributes(tS) tS@documentation
Binds "timeSeries"
objects either by column or by row.
## S3 method for class 'timeSeries' cbind(..., deparse.level = 1) ## S3 method for class 'timeSeries' rbind(..., deparse.level = 1) ## S4 method for signature 'timeSeries,ANY' cbind2(x, y) ## other methods for 'cbind2' with the same arguments, see Details ## S4 method for signature 'timeSeries,ANY' rbind2(x, y) ## other methods for 'rbind2' with the same arguments, see Details
## S3 method for class 'timeSeries' cbind(..., deparse.level = 1) ## S3 method for class 'timeSeries' rbind(..., deparse.level = 1) ## S4 method for signature 'timeSeries,ANY' cbind2(x, y) ## other methods for 'cbind2' with the same arguments, see Details ## S4 method for signature 'timeSeries,ANY' rbind2(x, y) ## other methods for 'rbind2' with the same arguments, see Details
x , y
|
objects, at least one of whom is of class |
... |
further arguments to bind. |
deparse.level |
see the documentation of |
These functions bind the objects by row rXXX
or column
(cXXX
.
cbind
and rbind
are S3 generics, so the
"timeSeries"
methods describe here are called only when the
first argument is "timeSeries"
.
cbind2
and rbind2
are S4 generics which dispatch on the
first two arguments. The "timeSeries"
methods for these are
invoked whenever at least one of the first two arguments is of class
"timeSeries"
.
All functions can be called with more than two arguments. After the first two are merged, the result is merged with the third, and so on.
an object of class "timeSeries"
merge
for another way to merge "timeSeries"
object column-wise.
rbind2
and cbind2
from
package "methods"
,
## Load Microsoft Data Set - x <- MSFT[1:12, ] x ## Bind Columnwise - X <- cbind(x[, "Open"], returns(x[, "Open"])) colnames(X) <- c("Open", "Return") X ## Bind Rowwise - Y <- rbind(x[1:3, "Open"], x[10:12, "Open"]) Y
## Load Microsoft Data Set - x <- MSFT[1:12, ] x ## Bind Columnwise - X <- cbind(x[, "Open"], returns(x[, "Open"])) colnames(X) <- c("Open", "Return") X ## Bind Rowwise - Y <- rbind(x[1:3, "Open"], x[10:12, "Open"]) Y
Functions to compute cumulative column statistics.
## S4 method for signature 'timeSeries' colCumsums(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCummaxs(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCummins(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCumprods(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCumreturns(x, method = c("geometric", "simple"), na.rm = FALSE, ...)
## S4 method for signature 'timeSeries' colCumsums(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCummaxs(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCummins(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCumprods(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' colCumreturns(x, method = c("geometric", "simple"), na.rm = FALSE, ...)
x |
a time series, may be an object of class |
na.rm |
a logical. Should missing values be removed? |
method |
a character string to indicate if geometric ( |
... |
arguments to be passed. |
These functions compute the requested cumulative quantities columnwise
to obtain a matrix of the same dimension as the data. The
"timeSeries"
methods replace the data part of the original
object with the resulting matrix.
The "timeSeries"
methods for the Math
group functions
cummin
, cummax
, cumsum
, and cumprod
,
work similarly but don't have the na.rm
argument.
"matrix"
for the default methods of all functions,
"timeSeries"
for the "timeSeries"
methods
Math,timeSeries-method
,
rowCumsums
## simulate return data x <- matrix(rnorm(24), ncol = 2) X <- as.timeSeries(x) ## cumulative sums by column - class(colCumsums(x)) # "matrix" class(colCumsums(X)) # "timeSeries" colCumsums(X)
## simulate return data x <- matrix(rnorm(24), ncol = 2) X <- as.timeSeries(x) ## cumulative sums by column - class(colCumsums(x)) # "matrix" class(colCumsums(X)) # "timeSeries" colCumsums(X)
A collection of functions to compute column statistical properties of financial and economic time series data.
colStats(x, FUN, ...) colSds(x, ...) colVars(x, ...) colSkewness(x, ...) colKurtosis(x, ...) colMaxs(x, ...) colMins(x, ...) colProds(x, ...) colQuantiles(x, prob = 0.05, ...)
colStats(x, FUN, ...) colSds(x, ...) colVars(x, ...) colSkewness(x, ...) colKurtosis(x, ...) colMaxs(x, ...) colMins(x, ...) colProds(x, ...) colQuantiles(x, prob = 0.05, ...)
x |
a rectangular object which can be transformed into a matrix
by the function |
FUN |
a function name, the statistical function to be applied. |
prob |
a numeric value in [0,1]. |
... |
arguments to be passed. |
colStats
|
calculates column statistics, |
colSums |
calculates column sums, |
colMeans |
calculates column means, |
colSds |
calculates column standard deviations, |
colVars |
calculates column variances, |
colSkewness |
calculates column skewness, |
colKurtosis |
calculates column kurtosis, |
colMaxs |
calculates maximum values in each column, |
colMins |
calculates minimum values in each column, |
colProds |
computes product of all values in each column, |
colQuantiles |
computes quantiles of each column. |
each function returns a numeric vector of the statistics, one for each column
## Simulated Return Data in Matrix Form - x = matrix(rnorm(252), ncol = 2) ## Mean Columnwise Statistics - colStats(x, FUN = mean) ## Quantiles Column by Column - colQuantiles(x, prob = 0.10, type = 1)
## Simulated Return Data in Matrix Form - x = matrix(rnorm(252), ncol = 2) ## Mean Columnwise Statistics - colStats(x, FUN = mean) ## Quantiles Column by Column - colQuantiles(x, prob = 0.10, type = 1)
Get or assign new comment to a timeSeries
object.
## S4 method for signature 'timeSeries' comment(x) ## S4 replacement method for signature 'timeSeries' comment(x) <- value
## S4 method for signature 'timeSeries' comment(x) ## S4 replacement method for signature 'timeSeries' comment(x) <- value
x |
a |
value |
a character vector, the comment. |
Objects from class "timeSeries"
have a slot for documentation.
These functions get and change its contents.
## Get description from a 'timeSeries' - comment(LPP2005REC) ## Add User to comment - comment(LPP2005REC) <- paste(comment(LPP2005REC), "by User Rmetrics") comment(LPP2005REC)
## Get description from a 'timeSeries' - comment(LPP2005REC) ## Add User to comment - comment(LPP2005REC) <- paste(comment(LPP2005REC), "by User Rmetrics") comment(LPP2005REC)
Computes a cumulated financial "timeSeries"
, e.g. prices or
indexes, from financial returns.
cumulated(x, ...) ## Default S3 method: cumulated(x, method = c("continuous", "discrete", "compound", "simple"), percentage = FALSE, ...)
cumulated(x, ...) ## Default S3 method: cumulated(x, method = c("continuous", "discrete", "compound", "simple"), percentage = FALSE, ...)
x |
an object of class |
method |
a character string, the method for computation of returns. |
percentage |
a logical value. By default |
... |
ignored by the default method. |
Note, the function cumulated
assumes as input discrete returns
from a price or index series. Only then the cumulated series agrees
with the original price or index series. The first values of the
cumulated series cannot be computed, it is assumed that the series is
indexed to 1.
a "timeSeries"
object
returns
,
drawdowns
,
splits
,
midquotes
,
index2wealth
## Use the Microsofts' Close Prices Indexed to 1 - MSFT.CL <- MSFT[, "Close"] MSFT.CL <- MSFT.CL/MSFT[[1, "Close"]] head(MSFT.CL) ## Compute Discrete Return - MSFT.RET <- returns(MSFT.CL, method = "discrete") ## Cumulated Series and Compare - MSFT.CUM <- cumulated(MSFT.RET, method = "discrete") head(cbind(MSFT.CL, MSFT.CUM))
## Use the Microsofts' Close Prices Indexed to 1 - MSFT.CL <- MSFT[, "Close"] MSFT.CL <- MSFT.CL/MSFT[[1, "Close"]] head(MSFT.CL) ## Compute Discrete Return - MSFT.RET <- returns(MSFT.CL, method = "discrete") ## Cumulated Series and Compare - MSFT.CUM <- cumulated(MSFT.RET, method = "discrete") head(cbind(MSFT.CL, MSFT.CUM))
Utilities called to implement [email protected] of timeSeries
objects.
## Load Microsoft Data - X <- MSFT[1:10, 1:4] ## Get Data Part - DATA <- getDataPart(X) class(DATA)
## Load Microsoft Data - X <- MSFT[1:10, 1:4] ## Get Data Part - DATA <- getDataPart(X) class(DATA)
Creates and returns a string containing the user, the current datetime and the user name.
description()
description()
## Show Default Description String - description()
## Show Default Description String - description()
Difference a "timeSeries"
object.
## S3 method for class 'timeSeries' diff(x, lag = 1, diff = 1, trim = FALSE, pad = NA, ...)
## S3 method for class 'timeSeries' diff(x, lag = 1, diff = 1, trim = FALSE, pad = NA, ...)
x |
an object of class |
lag |
an integer indicating which lag to use. |
diff |
an integer indicating the order of the difference. |
trim |
a logical flag. Should |
pad |
a numeric value with which |
... |
currently not used. |
the differenced "timeSeries"
object
## load Microsoft dataset x <- MSFT[1:12, ] x ## compute differences diff(x) ## trimmed differences diff(x, trim = TRUE) ## padded differences diff(x, trim = FALSE, pad = 0)
## load Microsoft dataset x <- MSFT[1:12, ] x ## compute differences diff(x) ## trimmed differences diff(x, trim = TRUE) ## padded differences diff(x, trim = FALSE, pad = 0)
Get and assign names, row names, column names, and dim names of
"timeSeries"
objects.
"timeSeries"
methods are available for base R functions working
on dimension names, including dim
, dimnames
,
colnames
, rownames
, names
and their assignment
variants.
dim
is the dimension of the underlying data matrix.
rownames
gives the datetime stamps as a character
vector. rownames<-
sets them.
colnames
gives the values of x@units
. These are
conceptually the column names of the data matrix. colnames<-
sets slot units
of x
.
dimnames
gives list(rownames(x), colnames(x)
.
dimnames<-
calls rownames
and colnames
on
value[[1]]
and value[[2]]
, respectively.
(GNB; todo) The "dim<-"
, currently converts x
to a
vector if value
is NULL
, otherwise it ignores
value
, does nothing and returns x
unchanged. This
behaviour should not be relied upon and may be changed in the future,
e.g. by issuing warning when value
is not NULL
. Or
throwing error altogether if assignment with "dim<-"
is
attempted.
## Load Swiss Pension Fund Benchmark Data - X <- LPP2005REC[1:10, 1:3] ## Get Dimension - dim(X) ## Get Column and Row Names - dimnames(X) ## Get Column / Row Names - colnames(X) rownames(X) ## Try your own DIM - DIM <- function(x) {c(NROW(x), NCOL(x))} DIM(X) DIM(X[, 1]) ## Try length / LENGTH - length(X) length(X[, 1]) LENGTH <- function(X) NROW(X) LENGTH(X) ## Columns / Rows - ncol(X); NCOL(X) nrow(X); NROW(X) ## See also - isUnivariate(X) isMultivariate(X)
## Load Swiss Pension Fund Benchmark Data - X <- LPP2005REC[1:10, 1:3] ## Get Dimension - dim(X) ## Get Column and Row Names - dimnames(X) ## Get Column / Row Names - colnames(X) rownames(X) ## Try your own DIM - DIM <- function(x) {c(NROW(x), NCOL(x))} DIM(X) DIM(X[, 1]) ## Try length / LENGTH - length(X) length(X[, 1]) LENGTH <- function(X) NROW(X) LENGTH(X) ## Columns / Rows - ncol(X); NCOL(X) nrow(X); NROW(X) ## See also - isUnivariate(X) isMultivariate(X)
Compute series of drawdowns from financial returns and calculate drawdown statisitcs.
drawdowns(x, ...) drawdownsStats(x, ...)
drawdowns(x, ...) drawdownsStats(x, ...)
x |
a |
... |
optional arguments passed to |
The code in the core of the function drawdownsStats
was borrowed from the package PerformanceAnalytics
authored by Peter Carl and Sankalp Upadhyay.
for drawdowns
, an object of class timeSeries
.
for drawdownsStats
an object of
class "data.frame"
with the following components:
drawdown |
the depth of the drawdown, |
from |
the start date, |
trough |
the trough period, |
to |
the end date, |
length |
the length in number of records, |
peaktrough |
the peak trough, and |
recovery |
the recovery length in number of records. |
Peter Carl and Sankalp Upadhyay for code from the contributed R
package PerformanceAnalytics
used in the function
drawdownsStats
.
returns
,
cumulated
,
splits
,
midquotes
,
index2wealth
## Use Swiss Pension Fund Data Set of Returns - head(LPP2005REC) SPI <- LPP2005REC[, "SPI"] head(SPI) ## Plot Drawdowns - dd = drawdowns(LPP2005REC[, "SPI"], main = "Drawdowns") plot(dd) dd = drawdowns(LPP2005REC[, 1:6], main = "Drawdowns") plot(dd) ## Compute Drawdowns Statistics - ddStats <- drawdownsStats(SPI) class(ddStats) ddStats ## Note, Only Univariate Series are allowd - ddStats <- try(drawdownsStats(LPP2005REC)) class(ddStats)
## Use Swiss Pension Fund Data Set of Returns - head(LPP2005REC) SPI <- LPP2005REC[, "SPI"] head(SPI) ## Plot Drawdowns - dd = drawdowns(LPP2005REC[, "SPI"], main = "Drawdowns") plot(dd) dd = drawdowns(LPP2005REC[, 1:6], main = "Drawdowns") plot(dd) ## Compute Drawdowns Statistics - ddStats <- drawdownsStats(SPI) class(ddStats) ddStats ## Note, Only Univariate Series are allowd - ddStats <- try(drawdownsStats(LPP2005REC)) class(ddStats)
Create dummy daily and monthly time series for examples and exploration.
dummyDailySeries(x = rnorm(365), units = NULL, zone = "", FinCenter = "") dummyMonthlySeries(...)
dummyDailySeries(x = rnorm(365), units = NULL, zone = "", FinCenter = "") dummyMonthlySeries(...)
x |
an object of class |
units |
an optional character string, which allows to overwrite the current
column names of a |
FinCenter |
a character with the the location of the financial center named as
|
zone |
the time zone or financial center where the data were recorded. |
... |
optional arguments passed to |
dummyDailySeries
creates a timeSeries
object with
dummy daily dates from a numeric matrix with daily records of
unknown dates.
dummyMonthlySeries
creates a dummy monthly "timeSeries"
object.
a "timeSeries"
object
dd <- dummyDailySeries() head(dd) tail(dd) dummyMonthlySeries(y = 2022)
dd <- dummyDailySeries() head(dd) tail(dd) dummyMonthlySeries(y = 2022)
Computes durations from an object of class "timeSeries"
.
durations(x, trim = FALSE, units = c("secs", "mins", "hours", "days"))
durations(x, trim = FALSE, units = c("secs", "mins", "hours", "days"))
x |
an object of class |
trim |
a logical value. By default |
units |
a character value or vector which allows to set the units in which the durations are measured. By default durations are measured in seconds. |
Durations measure how long it takes until we get the next record in a
timesSeries
object. We return a time series in which for each
time stamp we get the length of the period from when we got the last
record. This period is measured in length specified by the argument
units
, for daily data use units="days"
.
an object of class "timeSeries"
## Compute Durations in days for the MSFT Sereries - head(durations(MSFT, units = "days")) head(durations(MSFT, trim = TRUE, units = "days")) ## The same in hours - head(durations(MSFT, trim = TRUE, units = "hours"))
## Compute Durations in days for the MSFT Sereries - head(durations(MSFT, units = "days")) head(durations(MSFT, trim = TRUE, units = "days")) ## The same in hours - head(durations(MSFT, trim = TRUE, units = "hours"))
Applies linear filtering to a univariate "timeSeries"
.
## S4 method for signature 'timeSeries' filter(x, filter, method = c("convolution", "recursive"), sides = 2, circular = FALSE, init = NULL)
## S4 method for signature 'timeSeries' filter(x, filter, method = c("convolution", "recursive"), sides = 2, circular = FALSE, init = NULL)
x |
an object from class |
filter |
coefficients of the filter. |
method |
|
sides , circular
|
for convolution filters only. Onesided if |
init |
for recursive filters only. Values before the start of the time series. |
filter
is a generic function with default method
stats::filter
. The method for "timeSeries"
is a wrapper
for the latter.
See ?stats::filter
for details about the arguments.
a "timeSeries"
object
base R function filter
## Creata a dummy signal 'timeSeries' - data <- matrix(rnorm(100), ncol = 2) s <- timeSeries(data, units=c("A", "B")) head(s) ## Filter the series - f <- filter(s, rep(1, 3)) head(f) ## Plot and compare the first series - plot(cbind(s[, 1], f[, 1]), plot.type="s")
## Creata a dummy signal 'timeSeries' - data <- matrix(rnorm(100), ncol = 2) s <- timeSeries(data, units=c("A", "B")) head(s) ## Filter the series - f <- filter(s, rep(1, 3)) head(f) ## Plot and compare the first series - plot(cbind(s[, 1], f[, 1]), plot.type="s")
Get or assign a financial center to a "timeSeries"
object.
## S4 method for signature 'timeSeries' finCenter(x) ## S4 replacement method for signature 'timeSeries' finCenter(x) <- value getFinCenter(x) setFinCenter(x) <- value
## S4 method for signature 'timeSeries' finCenter(x) ## S4 replacement method for signature 'timeSeries' finCenter(x) <- value getFinCenter(x) setFinCenter(x) <- value
x |
a |
value |
a character with the the location of the financial center named
as |
listFinCenter
and finCenter
in package "timeDate"
## An artificial 'timeSeries' Object - tS <- dummyMonthlySeries() tS ## Print Financial Center - finCenter(tS) getFinCenter(tS) ## Assign New Financial Center - finCenter(tS) <- "Zurich" tS setFinCenter(tS) <- "New_York" tS
## An artificial 'timeSeries' Object - tS <- dummyMonthlySeries() tS ## Print Financial Center - finCenter(tS) getFinCenter(tS) ## Assign New Financial Center - finCenter(tS) <- "Zurich" tS setFinCenter(tS) <- "New_York" tS
is.timeSeries
tests if its argument is a timeSeries
.
is.signalSeries
tests if series has no timestamps.
is.timeSeries(x) is.signalSeries(x)
is.timeSeries(x) is.signalSeries(x)
x |
an object. |
a logical value, TRUE
or FALSE
.
## Create an artificial 'timeSeries' object - setRmetricsOptions(myFinCenter = "GMT") charvec <- timeCalendar() data <- matrix(rnorm(12)) TS <- timeSeries(data, charvec, units = "RAND") TS ## Test for 'timeSeries' - is.timeSeries(TS)
## Create an artificial 'timeSeries' object - setRmetricsOptions(myFinCenter = "GMT") charvec <- timeCalendar() data <- matrix(rnorm(12)) TS <- timeSeries(data, charvec, units = "RAND") TS ## Test for 'timeSeries' - is.timeSeries(TS)
Checks if a time series is regular.
## S4 method for signature 'timeSeries' isDaily(x) ## S4 method for signature 'timeSeries' isMonthly(x) ## S4 method for signature 'timeSeries' isQuarterly(x) ## S4 method for signature 'timeSeries' isRegular(x) ## S4 method for signature 'timeSeries' frequency(x, ...)
## S4 method for signature 'timeSeries' isDaily(x) ## S4 method for signature 'timeSeries' isMonthly(x) ## S4 method for signature 'timeSeries' isQuarterly(x) ## S4 method for signature 'timeSeries' isRegular(x) ## S4 method for signature 'timeSeries' frequency(x, ...)
x |
an R object of class 'timeSeries'. |
... |
arguments to be passed. |
What is a regular time series? If a time series is daily, monthly, or
weekly, then we speak of a regular series. This can be tested calling
the functions isDaily
, isMonthly
, isQuarterly
, or
in general isRegular
. If the series is regular then its
frequency can be determined by calling frequency
.
Here are the definitions of daily, monthly, and quarterly time series:
if the series has no more than one date/time stamp per day.
if the series has no more than one date/time stamp per month.
if the series has no more than one date/time stamp per quarter.
A regular series is either a monthly or a quarterly series.
Note that with the above definitions a monthly series is also a daily series, a quarterly series is also a monthly series. On the other hand, a daily series is not regular!
NOT yet implemented is the case of weekly series.
The is*
functions return TRUE
or FALSE
depending
on whether the series fulfills the condition or not.
frequency
returns in general 1, for quarterly series 4,
and for monthly series 12.
data(MSFT) isRegular(MSFT) # FALSE frequency(MSFT) # 1 ## a monthly ts ap <- as.timeSeries(AirPassengers) isRegular(ap) # TRUE frequency(ap) # 12 ## a quarterly ts pres <- as.timeSeries(presidents) isRegular(pres) # TRUE frequency(pres) # 4
data(MSFT) isRegular(MSFT) # FALSE frequency(MSFT) # 1 ## a monthly ts ap <- as.timeSeries(AirPassengers) isRegular(ap) # TRUE frequency(ap) # 12 ## a quarterly ts pres <- as.timeSeries(presidents) isRegular(pres) # TRUE frequency(pres) # 4
Checks if a time series object or any other rectangular object is univariate or multivariate.
isUnivariate(x) isMultivariate(x)
isUnivariate(x) isMultivariate(x)
x |
an object of class |
A rectangular object x
is considered to be univariate if the
function NCOL(x)
returns one, and is considered to be
multivariate if NCOL(x)
returns a value bigger than one.
a logical value
## Load Microsoft Data - setRmetricsOptions(myFinCenter = "GMT") data(MSFT) Open = MSFT[, "Open"] ## Is the 'timeSeries' Univariate - isUnivariate(MSFT) isUnivariate(Open) ## Is the 'timeSeries' Multivariate - isMultivariate(MSFT) isMultivariate(Open)
## Load Microsoft Data - setRmetricsOptions(myFinCenter = "GMT") data(MSFT) Open = MSFT[, "Open"] ## Is the 'timeSeries' Univariate - isUnivariate(MSFT) isUnivariate(Open) ## Is the 'timeSeries' Multivariate - isMultivariate(MSFT) isMultivariate(Open)
Compute a lagged version of a "timeSeries"
object.
## S3 method for class 'timeSeries' lag(x, k = 1, trim = FALSE, units = NULL, ...)
## S3 method for class 'timeSeries' lag(x, k = 1, trim = FALSE, units = NULL, ...)
x |
an object of class |
k |
an integer number, the number of lags (in units of observations).
By default 1. Can also be a vector, in which case the result is a
multivariate |
trim |
a logical value. By default |
units |
an optional character string, which allows to overwrite the current
column names of a |
... |
arguments passed to other methods. |
an object of class "timeSeries"
## Load Micsrosoft Data Set x <- MSFT[1:20, "Open"] ## Lag the 'timeSeries' Object lag(x, k = -1:1)
## Load Micsrosoft Data Set x <- MSFT[1:20, "Open"] ## Lag the 'timeSeries' Object lag(x, k = -1:1)
Functions and methods for mathematical operations on "timeSeries"
.
## S4 method for signature 'timeSeries,timeSeries' Ops(e1, e2) ## S4 method for signature 'timeSeries' Math(x) ## S4 method for signature 'timeSeries' Math2(x, digits) ## S3 method for class 'timeSeries' quantile(x, ...) ## S3 method for class 'timeSeries' median(x, na.rm = FALSE, ...)
## S4 method for signature 'timeSeries,timeSeries' Ops(e1, e2) ## S4 method for signature 'timeSeries' Math(x) ## S4 method for signature 'timeSeries' Math2(x, digits) ## S3 method for class 'timeSeries' quantile(x, ...) ## S3 method for class 'timeSeries' median(x, na.rm = FALSE, ...)
x |
an object of class |
digits |
number of digits to be used in 'round' or 'signif'. |
e1 , e2
|
at least one of the two objects is from class |
na.rm |
a logical value: should missing values be removed? |
... |
arguments to be passed. |
The methods for the Math
and Math2
groups of
mathematical functions return 'timeSeries' objects. Most of them work
element-wise on the data part of the time series with the exception of
cummin
, cummax
, cumsum
, and cumprod
which
work columnwise.
The Ops
group includes mathematical operators. For the binary
operators methods are defined for pairs of at least one 'timeSeries'
object. These work as expected on the data parts of the arguments.
If the operation gives a value of the same dimension as the data part
of the 'timeSeries' object, it replaces the original data in the
object.
There are also methods for quantile
and median
.
the value from a mathematical or logical operation operating on
objects of class "timeSeries"
or the value computed by a
mathematical function.
## create an artificial 'timeSeries' object setRmetricsOptions(myFinCenter = "GMT") charvec = timeCalendar() set.seed(4711) data = matrix(exp(cumsum(rnorm(12, sd = 0.1)))) TS = timeSeries(data, charvec, units = "TS") TS ## mathematical operations: | +/- * ^ ... TS^2 TS[2:4] OR = returns(TS) OR OR > 0 ## median, quantile median(TS) quantile(TS) TS[3] <- NA # to demonstrate 'na.rm' median(TS) # NA #quantile(TS) # error median(TS, na.rm = TRUE) quantile(TS, na.rm = TRUE)
## create an artificial 'timeSeries' object setRmetricsOptions(myFinCenter = "GMT") charvec = timeCalendar() set.seed(4711) data = matrix(exp(cumsum(rnorm(12, sd = 0.1)))) TS = timeSeries(data, charvec, units = "TS") TS ## mathematical operations: | +/- * ^ ... TS^2 TS[2:4] OR = returns(TS) OR OR > 0 ## median, quantile median(TS) quantile(TS) TS[3] <- NA # to demonstrate 'na.rm' median(TS) # NA #quantile(TS) # error median(TS, na.rm = TRUE) quantile(TS, na.rm = TRUE)
Merges several object types with "timeSeries"
objects. The
number of rows must match.
merge(x, y, ...)
merge(x, y, ...)
x , y
|
objects to merge, at least one of class |
... |
further objects to merge. |
a "timeSeries"
object
signature(x = "timeSeries", y = "missing")
signature(x = "timeSeries", y = "ANY")
signature(x = "timeSeries", y = "matrix")
signature(x = "timeSeries", y = "numeric")
signature(x = "timeSeries", y = "timeSeries")
signature(x = "ANY", y = "ANY")
signature(x = "ANY", y = "timeSeries")
signature(x = "matrix", y = "timeSeries")
signature(x = "numeric", y = "timeSeries")
## Load Series - x <- MSFT[1:12, ] ## Merge 'timeSeries' with missing Object - merge(x) ## Merge 'timeSeries' with numeric Object - y <- rnorm(12) class(y) merge(x, y) ## Merge 'timeSeries' with matrix Object - y <- matrix(rnorm(24), ncol=2) class(y) merge(x, y) ## Merge 'timeSeries' with matrix Object - y <- timeSeries(data=rnorm(12), charvec=time(x)) class(y) merge(x, y)
## Load Series - x <- MSFT[1:12, ] ## Merge 'timeSeries' with missing Object - merge(x) ## Merge 'timeSeries' with numeric Object - y <- rnorm(12) class(y) merge(x, y) ## Merge 'timeSeries' with matrix Object - y <- matrix(rnorm(24), ncol=2) class(y) merge(x, y) ## Merge 'timeSeries' with matrix Object - y <- timeSeries(data=rnorm(12), charvec=time(x)) class(y) merge(x, y)
Functions and methods dealing with special monthly
"timeSeries"
objects.
rollMonthlyWindows(x, period = "12m", by = "1m") rollMonthlySeries(x, period = "12m", by = "1m", FUN, ...) countMonthlyRecords(x)
rollMonthlyWindows(x, period = "12m", by = "1m") rollMonthlySeries(x, period = "12m", by = "1m", FUN, ...) countMonthlyRecords(x)
x |
a |
period , by
|
character strings specifying the rollling period composed by the
length of the period and its unit. Examples: |
FUN |
the function for the statistic to be applied. For example,
|
... |
arguments passed to the function |
rollMonthlySeries
computes the statistics defined by the
function FUN
over rolling windows, internally computed by the
function rollMonthlyWindows
. Note, the periods may be
overlapping, may be dense, or even may have gaps.
countMonthlyRecords
computes a "timeSeries"
that holds
the number of records for each month, see examples. The dates are set
to the end of the month.
rollMonthlyWindows
computes start and end dates for rolling
time windows. Argument period
specifies the length of the
periods over which FUN
is applied, while by
gives the
amount by which the window is shifted. Non-overlapping windows
correspond to by >= period
.
for countMonthlyRecords
and rollMonthlySeries
,
a "timeSeries"
object.
for rollMonthlyWindows
, a list with attribute "control"
keeping
the start
and end
dates of the series.
The components of the list are:
from |
an object from class |
to |
an object from class |
## load Microsoft daily dataset x <- MSFT ## count monthly records head(x) # 3 obs. for Sep 2000 counts <- countMonthlyRecords(x) counts ## diy computation of the counts diy <- rollMonthlySeries(x[ , 1], period = "1m", by = "1m", FUN = NROW) ## difference is only in some attributes (e.g. column names) all.equal(diy, counts) ## quaterly non-overlapping time periods windows <- rollMonthlyWindows(counts[-1, ], period = "3m", by = "3m") windows ## nicely print results as a data.frame, each row is a time window data.frame(cbind(FROM = format(windows$from), TO = format(windows$to))) ## compute the average number of monthly trading days per quarter rollMonthlySeries(counts[-1, ], period = "3m", by = "3m", FUN = mean)
## load Microsoft daily dataset x <- MSFT ## count monthly records head(x) # 3 obs. for Sep 2000 counts <- countMonthlyRecords(x) counts ## diy computation of the counts diy <- rollMonthlySeries(x[ , 1], period = "1m", by = "1m", FUN = NROW) ## difference is only in some attributes (e.g. column names) all.equal(diy, counts) ## quaterly non-overlapping time periods windows <- rollMonthlyWindows(counts[-1, ], period = "3m", by = "3m") windows ## nicely print results as a data.frame, each row is a time window data.frame(cbind(FROM = format(windows$from), TO = format(windows$to))) ## compute the average number of monthly trading days per quarter rollMonthlySeries(counts[-1, ], period = "3m", by = "3m", FUN = mean)
Functions for handling missing values in "timeSeries"
objects.
## S3 method for class 'timeSeries' na.omit(object, method = c("r", "s", "z", "ir", "iz", "ie"), interp = c("before", "linear", "after"), FUN, ...)
## S3 method for class 'timeSeries' na.omit(object, method = c("r", "s", "z", "ir", "iz", "ie"), interp = c("before", "linear", "after"), FUN, ...)
object |
an object of class |
method |
the method of handling NAs, see section ‘Details’. |
interp |
Three alternative methods are provided to remove NAs from the
data:
|
FUN |
a function or a name of a function, such as |
... |
arguments to be passed to the function |
Functions for handling missing values in "timeSeries"
objects
and in objects which can be transformed into a vector or a two
dimensional matrix.
For na.omit
argument method
specifies how to handle
NA
s. Can be one of the following strings:
na.rm = FALSE
, skip, i.e. do nothing,
remove NAs,
substitute NAs by zeros,
interpolate NAs and remove NAs at the beginning and end of the series,
interpolate NAs and substitute NAs at the beginning and end of the series,
interpolate NAs and extrapolate NAs at the beginning and end of theseries.
When dealing with daily data sets, there exists another function
alignDailySeries
which can handle missing data in un-aligned
calendrical "timeSeries"
objects.
Additional remarks by GNB:
removeNA(x)
is equivalent to na.omit(x)
or
na.omit(x), methods = "r"
.
interpNA
can be replaced by a call to na.omit
with
argument method equal to ir
, iz
, or ie
, and
argument "interp"
equal to the "method"
argument for
interpNA
(note that the defaults are not the same).
substituteNA(x, type = "zeros")
is equivalent to
na.omit(x, method = "z")
. For other values of type
one
can use argument FUN
, as in na.omit(x, FUN = "mean")
.
A final remark: the three deprecated functions are non-generic.
removeNA(x)
is completely redundant as it simply calls
na.omit
. The other two however may be useful for matrix-like
objects. Please inform the maintainer of the package if you use them
on objects other than from class "timeSeries"
and wish them
kept in the future.
Troyanskaya O., Cantor M., Sherlock G., Brown P., Hastie T., Tibshirani R., Botstein D., Altman R.B., (2001); Missing Value Estimation Methods for DNA microarrays Bioinformatics 17, 520–525.
X <- matrix(rnorm(100), ncol = 5) # Create a Matrix X X[3, 5] <- NA # Replace a Single NA Inside X[17, 2:4] <- c(NA, NA, NA) # Replace Three in a Row Inside X[13:15, 4] <- c(NA, NA, NA) # Replace Three in a Column Inside X[11:12, 5] <- c(NA, NA) # Replace Two at the Right Border X[20, 1] <- NA # Replace One in the Lower Left Corner X Xts <- timeSeries(X) # convert X to timeSeries Xts ## remove rows with NAs na.omit(Xts) ## Subsitute NA's with zeros or column means (formerly substituteNA()) na.omit(Xts, method = "z") na.omit(Xts, FUN = "mean") na.omit(Xts, FUN = "median") ## Subsitute NA's with a trimmed mean na.omit(Xts, FUN = function(x, na.rm) mean(x, trim = 0.10, na.rm = na.rm)) ## interpolate NA's linearily (formerly interpNA()) na.omit(X, method = "ir", interp = "linear") na.omit(X, method = "iz", interp = "linear") na.omit(X, method = "ie", interp = "linear") ## take previous values in a column na.omit(X, method = "ir", interp = "before") na.omit(X, method = "iz", interp = "before") na.omit(X, method = "ie", interp = "before") ## examples with X (which is a matrix, not "timeSeries") ## (these examples are not run automatically as these functions are ## deprecated.) if(FALSE){ ## Remove Rows with NAs removeNA(X) ## subsitute NA's by zeros or column means substituteNA(X, type = "zeros") substituteNA(X, type = "mean") ## interpolate NA's linearily interpNA(X, method = "linear") # Note the corner missing value cannot be interpolated! ## take previous values in a column interpNA(X, method = "before") # Also here, the corner value is excluded }
X <- matrix(rnorm(100), ncol = 5) # Create a Matrix X X[3, 5] <- NA # Replace a Single NA Inside X[17, 2:4] <- c(NA, NA, NA) # Replace Three in a Row Inside X[13:15, 4] <- c(NA, NA, NA) # Replace Three in a Column Inside X[11:12, 5] <- c(NA, NA) # Replace Two at the Right Border X[20, 1] <- NA # Replace One in the Lower Left Corner X Xts <- timeSeries(X) # convert X to timeSeries Xts ## remove rows with NAs na.omit(Xts) ## Subsitute NA's with zeros or column means (formerly substituteNA()) na.omit(Xts, method = "z") na.omit(Xts, FUN = "mean") na.omit(Xts, FUN = "median") ## Subsitute NA's with a trimmed mean na.omit(Xts, FUN = function(x, na.rm) mean(x, trim = 0.10, na.rm = na.rm)) ## interpolate NA's linearily (formerly interpNA()) na.omit(X, method = "ir", interp = "linear") na.omit(X, method = "iz", interp = "linear") na.omit(X, method = "ie", interp = "linear") ## take previous values in a column na.omit(X, method = "ir", interp = "before") na.omit(X, method = "iz", interp = "before") na.omit(X, method = "ie", interp = "before") ## examples with X (which is a matrix, not "timeSeries") ## (these examples are not run automatically as these functions are ## deprecated.) if(FALSE){ ## Remove Rows with NAs removeNA(X) ## subsitute NA's by zeros or column means substituteNA(X, type = "zeros") substituteNA(X, type = "mean") ## interpolate NA's linearily interpNA(X, method = "linear") # Note the corner missing value cannot be interpolated! ## take previous values in a column interpNA(X, method = "before") # Also here, the corner value is excluded }
Find the longest consecutive stretch of non-missing values in a
"timeSeries"
object. In the event of a tie, the first such
stretch. Also, "timeSeries"
method for is.na
.
## S3 method for class 'timeSeries' na.contiguous(object, ...) ## S4 method for signature 'timeSeries' is.na(x)
## S3 method for class 'timeSeries' na.contiguous(object, ...) ## S4 method for signature 'timeSeries' is.na(x)
object , x
|
a |
... |
further arguments passed to other methods. |
for the na.contiguous
method, a "timeSeries"
object
without missing values,
for the is.na
method, a "timeSeries"
object whose data
part is a logical matrix of the same dimension as in x
indicating
if the corresponding values are NA
or not.
## Dummy 'timeSeries' containing NAs data <- matrix(sample(c(1:20, rep(NA,4))), ncol = 2) s <- timeSeries(data, timeCalendar(2023)) is.na(s) ## Find the longest consecutive non-missing values na.contiguous(s) ## tied longest stretches: 1:3, 6:9 and 10:12 x <- c(1:3, NA, NA, 6:8, NA, 10:12) ## should return the 1st one na.contiguous(x) # correct for R > 4.3.0 na.contiguous(timeSeries(x)) # correct for timeSeries version > 4030.106
## Dummy 'timeSeries' containing NAs data <- matrix(sample(c(1:20, rep(NA,4))), ncol = 2) s <- timeSeries(data, timeCalendar(2023)) is.na(s) ## Find the longest consecutive non-missing values na.contiguous(s) ## tied longest stretches: 1:3, 6:9 and 10:12 x <- c(1:3, NA, NA, 6:8, NA, 10:12) ## should return the 1st one na.contiguous(x) # correct for R > 4.3.0 na.contiguous(timeSeries(x)) # correct for timeSeries version > 4030.106
Functions and methods dealing with the rearrangement
of column names of 'timeSeries' objects.
orderColnames |
Returns ordered column names of a time Series, |
sortColnames |
Returns sorted column names of a time Series, |
sampleColnames |
Returns sampled column names of a time Series, |
statsColnames |
Returns statistically rearranged column names, |
pcaColnames |
Returns PCA correlation ordered column names, |
hclustColnames |
Returns hierarchical clustered column names. |
orderColnames(x, ...) sortColnames(x, ...) sampleColnames(x, ...) statsColnames(x, FUN = colMeans, ...) pcaColnames(x, robust = FALSE, ...) hclustColnames(x, method = c("euclidean", "complete"), ...)
orderColnames(x, ...) sortColnames(x, ...) sampleColnames(x, ...) statsColnames(x, FUN = colMeans, ...) pcaColnames(x, robust = FALSE, ...) hclustColnames(x, method = c("euclidean", "complete"), ...)
x |
an object of class |
FUN |
a character string indicating which statistical function should be applied. By default statistical ordering operates on the column means of the time series. |
method |
a character string with two elements. The first determines the
choice of the distance measure, see |
robust |
a logical flag which indicates if robust correlations should be used. |
... |
further arguments to be passed to the underlying functions doing the main work, see section ‘Details’. |
These functions reorder the column names of a "timeSeries"
object according to some statistical measure.
Statistically Motivated Rearrangement
The function statsColnames
rearranges the column names
according to a statical measure. These measure must operate on the
columns of the time series and return a vector of values which can
be sorted. Typical functions ar those listed in help page
colStats
but custom functions can be used that compute for
example risk or any other statistical measure. The ...
argument allows to pass additional arguments to the underlying
function FUN
.
PCA Ordering of the Correlation Matrix
The function pcaColnames
rearranges the column names
according to the PCA ordered correlation matrix. The argument
robust
allsows to select between the use of the standard
cor
and computation of robust correlations using
the function covMcd
from contributed R package
robustbase
. The ...
argument allows to pass
additional arguments to the two underlying functions cor
or covMcd
. E.g., adding method="kendall"
to the argument list calculates Kendall's rank correlations
instead the default which calculates Person's correlations.
Ordering by Hierarchical Clustering
The function pcaColnames
uses the hierarchical clustering
approach hclust
to rearrange the column names of the
time series.
for orderColnames
, an integer vector representing the
permutaion that will sort the column names,
for the other functions, a character vector giving the rearranged column names
## Load Swiss Pension Fund Benchmark Data - data <- LPP2005REC[,1:6] ## Abbreviate Column Names - colnames(data) ## Sort Alphabetically - sortColnames(data) ## Sort by Column Names by Hierarchical Clustering - hclustColnames(data) head(data[, hclustColnames(data)])
## Load Swiss Pension Fund Benchmark Data - data <- LPP2005REC[,1:6] ## Abbreviate Column Names - colnames(data) ## Sort Alphabetically - sortColnames(data) ## Sort by Column Names by Hierarchical Clustering - hclustColnames(data) head(data[, hclustColnames(data)])
Computes the order statistics of a "timeSeries"
object.
orderStatistics(x)
orderStatistics(x)
x |
a |
orderStatistics
computes the order statistics for each column of a
"timeSeries"
object. The output is a named list with the order
statistics for each column in a separate component.
a named list, in which each component is an
univariate "timeSeries"
containing the order statistics of the
corresponding column of the input time series.
## Load Swiss Pension Fund Benchmark Data - setRmetricsOptions(myFinCenter = "GMT") X <- LPP2005REC[, "SPI"] colnames(X) ## Compute 1% Order Statistics - N <- round(0.01*nrow(X)) N OS <- orderStatistics(X)[[1]] OS[1:N, ]
## Load Swiss Pension Fund Benchmark Data - setRmetricsOptions(myFinCenter = "GMT") X <- LPP2005REC[, "SPI"] colnames(X) ## Compute 1% Order Statistics - N <- round(0.01*nrow(X)) N OS <- orderStatistics(X)[[1]] OS[1:N, ]
Computes periodical statistics back to a given period.
endOfPeriodSeries(x, nYearsBack = c("1y", "2y", "3y", "5y", "10y", "YTD")) endOfPeriodStats(x, nYearsBack = c("1y", "2y", "3y", "5y", "10y", "YTD")) endOfPeriodBenchmarks(x, benchmark = ncol(x), nYearsBack = c("1y", "2y", "3y", "5y", "10y", "YTD"))
endOfPeriodSeries(x, nYearsBack = c("1y", "2y", "3y", "5y", "10y", "YTD")) endOfPeriodStats(x, nYearsBack = c("1y", "2y", "3y", "5y", "10y", "YTD")) endOfPeriodBenchmarks(x, benchmark = ncol(x), nYearsBack = c("1y", "2y", "3y", "5y", "10y", "YTD"))
x |
an end-of-month recorded multivariate |
nYearsBack |
a period string. How long back should the series be treated? Options include values from 1 year to 10 years, and year-to-date: "1y", "2y", "3y", "5y", "10y", "YTD". |
benchmark |
an integer giving the position of the benchmark series in
|
endOfPeriodSeries
extract the data for the last few years, as
specified by argument nYearsBack
.
endOfPeriodStats
computes basic exploratory statistics for the
last few years in the data.
endOfPeriodBenchmarks
returns benchmarks back to a given
period.
x
must be end of month data. Such series can be created using
functions like align
, alignDailySeries
,
daily2monthly
.
for endOfPeriodSeries
, a "timeSeries"
,
for endOfPeriodStats
, a data frame,
for endOfPeriodBenchmarks
- currently NULL
(invisibly),
the function is unfinished.
## load series: column 1:3 Swiss market, column 8 (4) benchmark x <- 100 * LPP2005REC[, c(1:3, 8)] colnames(x) x <- daily2monthly(x) x ## Get the Monthly Series - endOfPeriodSeries(x, nYearsBack="1y") ## Compute the Monthly Statistics endOfPeriodStats(x, nYearsBack="1y") ## Compute the Benchmark endOfPeriodBenchmarks(x, benchmark=4)
## load series: column 1:3 Swiss market, column 8 (4) benchmark x <- 100 * LPP2005REC[, c(1:3, 8)] colnames(x) x <- daily2monthly(x) x ## Get the Monthly Series - endOfPeriodSeries(x, nYearsBack="1y") ## Compute the Monthly Statistics endOfPeriodStats(x, nYearsBack="1y") ## Compute the Benchmark endOfPeriodBenchmarks(x, benchmark=4)
"timeSeries"
methods for plot
,
lines
and points
.
## S4 method for signature 'timeSeries' plot(x, y, FinCenter = NULL, plot.type = c("multiple", "single"), format = "auto", at = pretty(x), widths = 1, heights = 1, xy.labels, xy.lines, panel = lines, nc, yax.flip = FALSE, mar.multi = c(0, 5.1, 0, if (yax.flip) 5.1 else 2.1), oma.multi = c(6, 0, 5, 0), axes = TRUE, ...) ## S4 method for signature 'timeSeries' lines(x, FinCenter = NULL, ...) ## S4 method for signature 'timeSeries' points(x, FinCenter = NULL, ...) ## S3 method for class 'timeSeries' pretty(x, n=5, min.n=n%/%3, shrink.sml=0.75, high.u.bias=1.5, u5.bias=0.5+1.5*high.u.bias, eps.correct=0, ...)
## S4 method for signature 'timeSeries' plot(x, y, FinCenter = NULL, plot.type = c("multiple", "single"), format = "auto", at = pretty(x), widths = 1, heights = 1, xy.labels, xy.lines, panel = lines, nc, yax.flip = FALSE, mar.multi = c(0, 5.1, 0, if (yax.flip) 5.1 else 2.1), oma.multi = c(6, 0, 5, 0), axes = TRUE, ...) ## S4 method for signature 'timeSeries' lines(x, FinCenter = NULL, ...) ## S4 method for signature 'timeSeries' points(x, FinCenter = NULL, ...) ## S3 method for class 'timeSeries' pretty(x, n=5, min.n=n%/%3, shrink.sml=0.75, high.u.bias=1.5, u5.bias=0.5+1.5*high.u.bias, eps.correct=0, ...)
x , y
|
objects of class |
FinCenter |
a character with the the location of the financial center
named as |
plot.type |
for multivariate time series, should the series by plotted separately (with a common time axis) or on a single plot? |
format |
POSIX label format, e.g. "%Y-%m-%d" or "%F" for ISO-8601 standard date format. |
at |
a |
widths , heights
|
widths and heights for individual graphs, see |
xy.labels |
logical, indicating if |
xy.lines |
logical, indicating if |
panel |
a |
nc |
the number of columns to use when |
yax.flip |
logical indicating if the y-axis (ticks and numbering) should
flip from side 2 (left) to 4 (right) from series to series
when |
mar.multi , oma.multi
|
the (default) |
axes |
logical indicating if x- and y- axes should be drawn. |
n |
an integer giving the desired number of intervals. |
min.n |
a nonnegative integer giving the minimal number of intervals. |
shrink.sml |
a positive numeric by a which a default scale is shrunk in the case when range(x) is very small. |
high.u.bias |
a non-negative numeric, typically > 1. Larger high.u.bias values favor larger units. |
u5.bias |
a non-negative numeric multiplier favoring factor 5 over 2. |
eps.correct |
an integer code, one of 0, 1, or 2. If non-0, a correction is made at the boundaries. |
... |
additional graphical arguments, see |
Our original method plot
was build along R's plotting function
plot.ts
with an additional argument to tailor the position
marks at user defined position specified by the argument at
. We
call this style or theme "ts"
.
With verson R 3.1 we have inroduced two new additional plotting themes
called "pretty"
and "chick"
. They are becoming active
when we set at = "pretty"
or at = "chic"
.
Plot style or theme "pretty"
is an extension of our original
plotting method.
Plot style or theme "chic"
is an implementation along the
contributed packages xts
and PerformanceAnalytics
from
the Chicago finance group members ("chic"
is an abbreviation of
Chicago.
For both themes, "pretty"
and "chic"
, additional
arguments are passed through the ...
arguments. These are:
Argument |
Default | Description |
type |
"l" | types pf plot |
col |
1 | colors for lines and points |
pch |
20 | plot symbol |
cex |
1 | character and symbol scales |
lty |
1 | line types |
lwd |
2 | line widths |
cex.axes |
1 | scale of axes |
cex.lab |
1 | scale of labels |
cex.pch |
1 | scale of plot symbols |
grid |
TRUE | should grid lines plotted? |
frame.plot |
TRUE | should b box around the plot? |
axes |
TRUE | should be axes drawn on the plot? |
ann |
TRUE | should default annotations appear? |
Concerning the plot elements, the length of these vectors has to be the same as the number of columns in the time series to be plotted. If their length is only one, then they are repeated.
There is an almost 70 pages vignette added to the package, with dozens of examples of tailored plots. Have a look in it.
NULL
(invisibly), the functions are called for the side effect
of producing plots
vignette("timeSeriesPlot", package="timeSeries")
, which
provides extensive plot examples.
## load Swiss pension fund benchmark data LPP <- LPP2005REC[1:12, 1:4] colnames(LPP) <- abbreviate(colnames(LPP), 2) finCenter(LPP) <- "GMT" ## Example Plot 1 plot(LPP[, 1], type = "o", col = "steelblue", main = "LPP", xlab = "2005", ylab = "Return") plot(LPP[, 1], at="auto", type = "o", col = "steelblue", main = "LPP", xlab = "2005", ylab = "Return") ## Example Plot 2 plot(LPP[, 1:2], type = "o", col = "steelblue", main = "LPP", xlab = "2005", ylab = "Return") ## Example Plot 3 plot(LPP[, 1], LPP[, 2], type = "p", col = "steelblue", main = "LPP", xlab = "Return 1", ylab = "Return 2") ## Example Plot 4a, the wrong way to do it! LPP <- as.timeSeries(data(LPP2005REC)) ZRH <- as.timeSeries(LPP[,"SPI"], zone = "Zurich", FinCenter = "Zurich") NYC <- as.timeSeries(LPP[,"LMI"], zone = "NewYork", FinCenter = "NewYork") finCenter(ZRH) finCenter(NYC) plot(ZRH, at="auto", type = "p", pch = 19, col = "blue") points(NYC, pch = 19, col = "red") ## Example Plot 4b, convert NYC to Zurich time finCenter(ZRH) <- "Zurich" finCenter(NYC) <- "Zurich" at <- unique(round(time(ZRH))) plot(ZRH, type = "p", pch = 19, col = "blue", format = "%b %d", at = at, xlab = paste(ZRH@FinCenter, "local Time"), main = ZRH@FinCenter) points(NYC, pch = 19, col = "red") ## Example 4c, force everything to GMT using "FinCenter" argument finCenter(ZRH) <- "Zurich" finCenter(NYC) <- "NewYork" at <- unique(round(time(ZRH))) plot(ZRH, type = "p", pch = 19, col = "blue", format = "%b %d", at = at, FinCenter = "GMT", xlab = "GMT", main = "ZRH - GMT") points(NYC, FinCenter = "GMT", pch = 19, col = "red")
## load Swiss pension fund benchmark data LPP <- LPP2005REC[1:12, 1:4] colnames(LPP) <- abbreviate(colnames(LPP), 2) finCenter(LPP) <- "GMT" ## Example Plot 1 plot(LPP[, 1], type = "o", col = "steelblue", main = "LPP", xlab = "2005", ylab = "Return") plot(LPP[, 1], at="auto", type = "o", col = "steelblue", main = "LPP", xlab = "2005", ylab = "Return") ## Example Plot 2 plot(LPP[, 1:2], type = "o", col = "steelblue", main = "LPP", xlab = "2005", ylab = "Return") ## Example Plot 3 plot(LPP[, 1], LPP[, 2], type = "p", col = "steelblue", main = "LPP", xlab = "Return 1", ylab = "Return 2") ## Example Plot 4a, the wrong way to do it! LPP <- as.timeSeries(data(LPP2005REC)) ZRH <- as.timeSeries(LPP[,"SPI"], zone = "Zurich", FinCenter = "Zurich") NYC <- as.timeSeries(LPP[,"LMI"], zone = "NewYork", FinCenter = "NewYork") finCenter(ZRH) finCenter(NYC) plot(ZRH, at="auto", type = "p", pch = 19, col = "blue") points(NYC, pch = 19, col = "red") ## Example Plot 4b, convert NYC to Zurich time finCenter(ZRH) <- "Zurich" finCenter(NYC) <- "Zurich" at <- unique(round(time(ZRH))) plot(ZRH, type = "p", pch = 19, col = "blue", format = "%b %d", at = at, xlab = paste(ZRH@FinCenter, "local Time"), main = ZRH@FinCenter) points(NYC, pch = 19, col = "red") ## Example 4c, force everything to GMT using "FinCenter" argument finCenter(ZRH) <- "Zurich" finCenter(NYC) <- "NewYork" at <- unique(round(time(ZRH))) plot(ZRH, type = "p", pch = 19, col = "blue", format = "%b %d", at = at, FinCenter = "GMT", xlab = "GMT", main = "ZRH - GMT") points(NYC, FinCenter = "GMT", pch = 19, col = "red")
Print "timeSeries"
objects.
## S4 method for signature 'timeSeries' show(object) ## S3 method for class 'timeSeries' print(x, FinCenter = NULL, format = NULL, style = c("tS", "h", "ts"), by = c("month", "quarter"), ...)
## S4 method for signature 'timeSeries' show(object) ## S3 method for class 'timeSeries' print(x, FinCenter = NULL, format = NULL, style = c("tS", "h", "ts"), by = c("month", "quarter"), ...)
object , x
|
an object of class |
FinCenter |
a character with the the location of the financial center named as "continent/city". |
format |
the format specification of the input character vector, a character string with the format in POSIX notation. |
style |
a character string, one of |
by |
a character string, one of |
... |
arguments passed to the print method for the data part, which is a
|
show
does not have additional arguments.
The print
method allows to modify the way the object is shown
by explicitly calling print
.
The default for style
is tS
. For univariate time series
style = "h"
causes the object to be printed as a vector with
the time stamps as labels. Finally, style = "ts"
prints like
objects from base R class "ts"
, which is suitable for quarterly
and monthly time series.
Prints an object of class timeSeries
.
## Load Micsrosoft Data setRmetricsOptions(myFinCenter = "GMT") LPP <- MSFT[1:12, 1:4] ## Abbreviate Column Names colnames(LPP) <- abbreviate(colnames(LPP), 6) ## Print Data Set print(LPP) ## Alternative Use, Show Data Set LPP # equivalently, show(LPP) ## a short subseries to demo 'print' hC <- head(MSFT[ , "Close"]) class(hC) print(hC) print(hC, style = "h")
## Load Micsrosoft Data setRmetricsOptions(myFinCenter = "GMT") LPP <- MSFT[1:12, 1:4] ## Abbreviate Column Names colnames(LPP) <- abbreviate(colnames(LPP), 6) ## Print Data Set print(LPP) ## Alternative Use, Show Data Set LPP # equivalently, show(LPP) ## a short subseries to demo 'print' hC <- head(MSFT[ , "Close"]) class(hC) print(hC) print(hC, style = "h")
Compute the sample ranks of the values of a 'timeSeries' object.
## S4 method for signature 'timeSeries' rank(x, na.last = TRUE, ties.method = )
## S4 method for signature 'timeSeries' rank(x, na.last = TRUE, ties.method = )
x |
an univariate object of class |
na.last |
for controlling the treatment of |
ties.method |
a character string specifying how ties are treated; can be abbreviated. |
If all components are different (and no NA
s), the ranks are
well defined, with values in seq_len(x)
. With some values equal
(called ‘ties’), argument ties.method
determines the
result at the corresponding indices. The "first"
method results
a permutation with increasing values at each index set of ties. The
"random"
method puts these in random order, whereas the
default, "average"
, replaces them by their mean, and
"max"
and "min"
replace them with their maximum and
minimum respectively, the latter being the typical sports ranking.
NA
values are never considered to be equal: for na.last =
TRUE
and na.last = FALSE
they are given distinct ranks in the
order in which they occur in x
.
a "timeSeries"
object
## Load Microsoft Data - X <- 100 * returns(MSFT) ## Compute the Ranks - head(rank(X[, "Open"]), 10) ## Only Interested in the Vector, then use - head(rank(series(X[, "Open"])), 10)
## Load Microsoft Data - X <- 100 * returns(MSFT) ## Compute the Ranks - head(rank(X[, "Open"]), 10) ## Only Interested in the Vector, then use - head(rank(series(X[, "Open"])), 10)
Reads a file in table format and creates a "timeSeries"
object
from it. The first column of the table must hold the timestamps.
readSeries(file, header = TRUE, sep = ";", zone = "", FinCenter = "", format, ...)
readSeries(file, header = TRUE, sep = ";", zone = "", FinCenter = "", format, ...)
file |
the filename of a spreadsheet dataset from which to import the data records. |
header |
a logical value indicating whether the file contains the names of the variables as its first line. If missing, the value is determined from the file format: 'header' is set to 'TRUE' if and only if the first row contains one fewer fields than the number of columns. |
sep |
the field seperator used in the spreadsheet file to separate
columns, by default |
zone |
the time zone or financial center where the data were recorded. By
default |
FinCenter |
a character with the the location of the financial center named as "continent/city". |
format |
a character string with the format in POSIX notation specifying the timestamp format. The format has not to be specified if the first column in the file has the timestamp format specifier, e.g. "%Y-%m-%d" for the short ISO 8601 format. |
... |
Additional arguments passed to |
The file is imported with read.table
. Note the different
default for argument "sep"
.
The first column of the table must hold the timestamps. Format of the
timestamps can be either specified in the header of the first column
or by the format
argument.
an object of class "timeSeries"
as.timeSeries
,
timeSeries
,
dummyMonthlySeries
,
dummyDailySeries
## full path to an example file fn <- system.file("extdata/msft.csv", package = "timeSeries") ## first few lines of the file readLines(fn, n = 5) ## import the file msft <- readSeries(fn) head(msft) ## is msft the same as the data object MSFT? all.equal(msft, MSFT) ## ... almost, except for slot 'documentation' c(msft@documentation, MSFT@documentation) ## actually, all.equal() says 'attribute', not slot. this is ok too: c(attr(MSFT, "documentation"), attr(msft, "documentation")) ## make 'documentation' equal, here "", and compare again: msft@documentation <- "" all.equal(msft, MSFT) # TRUE
## full path to an example file fn <- system.file("extdata/msft.csv", package = "timeSeries") ## first few lines of the file readLines(fn, n = 5) ## import the file msft <- readSeries(fn) head(msft) ## is msft the same as the data object MSFT? all.equal(msft, MSFT) ## ... almost, except for slot 'documentation' c(msft@documentation, MSFT@documentation) ## actually, all.equal() says 'attribute', not slot. this is ok too: c(attr(MSFT, "documentation"), attr(msft, "documentation")) ## make 'documentation' equal, here "", and compare again: msft@documentation <- "" all.equal(msft, MSFT) # TRUE
Compute financial returns from prices or indexes.
returns(x, ...) returns0(x, ...) ## S4 method for signature 'ANY' returns(x, method = c("continuous", "discrete", "compound", "simple"), percentage = FALSE, ...) ## S4 method for signature 'timeSeries' returns(x, method = c("continuous", "discrete", "compound", "simple"), percentage = FALSE, na.rm = TRUE, trim = TRUE, ...)
returns(x, ...) returns0(x, ...) ## S4 method for signature 'ANY' returns(x, method = c("continuous", "discrete", "compound", "simple"), percentage = FALSE, ...) ## S4 method for signature 'timeSeries' returns(x, method = c("continuous", "discrete", "compound", "simple"), percentage = FALSE, na.rm = TRUE, trim = TRUE, ...)
x |
an object of class |
method |
a character string. Which method should be used to compute the returns, one of "continuous", "discrete", or "compound", "simple". The second pair of methods is a synonym for the first two methods. |
percentage |
a logical value. By default |
na.rm |
a logical value. Should NAs be removed? By default |
trim |
a logical value. Should the time series be trimmed? By Default
|
... |
arguments to be passed. |
an object of class timeSeries
.
returns0
returns an untrimmed series with the first
row of returns set to zero(s).
The functions returnSeries
and getReturns
will be
removed in the near future. They are synonyms for the function
returns
and their use was discouraged for many years. Just use
returns
.
The function returnSeries
is no longer
exported. getReturns
is exported only because we are waiting
for a package on CRAN to be updated.
cumulated
,
drawdowns
,
splits
,
spreads
,
midquotes
,
index2wealth
## Load Microsoft Data - setRmetricsOptions(myFinCenter = "GMT") data(MSFT) X = MSFT[1:10, 1:4] X ## Continuous Returns - returns(X) returns0(X) ## Discrete Returns: returns(X, method = "discrete") ## Don't trim: returns(X, trim = FALSE) ## Use Percentage Values: returns(X, percentage = TRUE, trim = FALSE)
## Load Microsoft Data - setRmetricsOptions(myFinCenter = "GMT") data(MSFT) X = MSFT[1:10, 1:4] X ## Continuous Returns - returns(X) returns0(X) ## Discrete Returns: returns(X, method = "discrete") ## Don't trim: returns(X, trim = FALSE) ## Use Percentage Values: returns(X, percentage = TRUE, trim = FALSE)
Reverses an uni- or multivariate "timeSeries"
object.
## S3 method for class 'timeSeries' rev(x)
## S3 method for class 'timeSeries' rev(x)
x |
an uni- or multivariate |
a "timeSeries"
object
## Create Dummy "timeSeries" tS <- dummyMonthlySeries() ## reverse series rev(tS)
## Create Dummy "timeSeries" tS <- dummyMonthlySeries() ## reverse series rev(tS)
Computes rolling mean, min, max and median for a "timeSeries"
object.
rollStats(x, k, FUN = mean, na.pad = FALSE, align=c("center", "left", "right"), ...) rollMean(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...) rollMin(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...) rollMax(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...) rollMedian(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
rollStats(x, k, FUN = mean, na.pad = FALSE, align=c("center", "left", "right"), ...) rollMean(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...) rollMin(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...) rollMax(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...) rollMedian(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
x |
an uni- or multivariate |
k |
an integer width of the rolling window. Must be odd for
|
FUN |
the function to be rolled. |
na.pad |
a logical flag. Should NA padding be added at beginning?
By default |
align |
a character string specifying whether the index of the result should
be left- or right-aligned or centered compared to the rolling window
of observations. The default choice is set to |
... |
optional arguments to be passed. |
The code in the core of the functions rollMean
, rollMin
,
rollMax
, and rollMedian
was borrowed from the package
zoo
authored by Achim Zeileis, Gabor Grothendieck and Felix
Andrews.
an object of class "timeSeries"
Achim Zeileis, Gabor Grothendieck and Felix Andrews for code from the
contributed R package zoo
used in the functions
rollMean
, rollMin
, rollMax
, and rollMedian
.
## Use Swiss Pension Fund Data Set of Returns - head(LPP2005REC) SPI <- LPP2005REC[, "SPI"] head(SPI) ## Plot Drawdowns - rmean <- rollMean(SPI, k = 10) plot(rmean)
## Use Swiss Pension Fund Data Set of Returns - head(LPP2005REC) SPI <- LPP2005REC[, "SPI"] head(SPI) ## Plot Drawdowns - rmean <- rollMean(SPI, k = 10) plot(rmean)
Compute cumulative row statistics.
## S4 method for signature 'ANY' rowCumsums(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' rowCumsums(x, na.rm = FALSE, ...)
## S4 method for signature 'ANY' rowCumsums(x, na.rm = FALSE, ...) ## S4 method for signature 'timeSeries' rowCumsums(x, na.rm = FALSE, ...)
x |
a time series, may be an object of class |
na.rm |
a logical. Should missing values be removed? |
... |
arguments to be passed. |
for the default method, a matrix,
for the "timeSeries"
method, an S4 object of class "timeSeries"
.
## Simulated Monthly Return Data - X = matrix(rnorm(24), ncol = 2) ## Compute cumulated Sums - rowCumsums(X)
## Simulated Monthly Return Data - X = matrix(rnorm(24), ncol = 2) ## Compute cumulated Sums - rowCumsums(X)
Computes runlengths of an univariate "timeSeries"
object.
runlengths(x, ...)
runlengths(x, ...)
x |
an univariate time series of class |
... |
arguments passed to the function |
Runlengths are defined here as contiguous sequences of values having the same sign.
Zeroes are treated as NA
s.
an object of class "timeSeries"
## random time series - set.seed(4711) x <- rnorm(12) tS <- timeSeries(data = x, charvec = timeCalendar(), units = "x") tS ## return runlengths - runlengths(tS) ## replace the middle value of the negative stretch of 3 values tS[5] <- NA ## the two negative values separated by NA are still one run runlengths(tS)
## random time series - set.seed(4711) x <- rnorm(12) tS <- timeSeries(data = x, charvec = timeCalendar(), units = "x") tS ## return runlengths - runlengths(tS) ## replace the middle value of the negative stretch of 3 values tS[5] <- NA ## the two negative values separated by NA are still one run runlengths(tS)
Takes a sample of the specified size from the elements of a
"timeSeries"
.
## S4 method for signature 'timeSeries' sample(x, size, replace = FALSE, prob = NULL)
## S4 method for signature 'timeSeries' sample(x, size, replace = FALSE, prob = NULL)
x |
an object from class |
size |
a non-negative integer giving the number of items to choose. |
replace |
sample with replacement if |
prob |
a vector of probability weights for obtaining the elements of the vector being sampled. |
The function takes a sample of size size
from the elements of
the time series with or without replacement depending on argument
replace
. The result is returned as a "timeSeries"
object.
For details about the arguments see the documentation of
base:sample
.
an object from class "timeSeries"
sample
(sample
in base R),
sample
(the "timeDate"
method)
## Monthly Calendar Series - x <- daily2monthly(LPP2005REC[, 1:2])[3:14, ] ## Resample the Series with respect to the time stamps - resampled <- sample(x) resampled is.unsorted(resampled)
## Monthly Calendar Series - x <- daily2monthly(LPP2005REC[, 1:2])[3:14, ] ## Resample the Series with respect to the time stamps - resampled <- sample(x) resampled is.unsorted(resampled)
Center and scale a "timeSeries"
object.
## S4 method for signature 'timeSeries' scale(x, center = TRUE, scale = TRUE)
## S4 method for signature 'timeSeries' scale(x, center = TRUE, scale = TRUE)
x |
an object from class |
center , scale
|
a numeric vector or a logical value, see ‘Details’. |
scale
centers and/or scales the columns of a
"timeSeries"
object.
The value of center
determines how column centering is
performed. If center
is a numeric vector with length equal to
the number of columns of x
, then each column of x
has
the corresponding value from center
subtracted from it. If
center
is TRUE then centering is done by subtracting the column
means (omitting NAs) of x
from their corresponding columns, and
if center
is FALSE, no centering is done.
The value of scale
determines how column scaling is performed
(after centering). If scale
is a numeric vector with length
equal to the number of columns of x
, then each column of
x
is divided by the corresponding value from scale
. If
scale
is TRUE then scaling is done by dividing the (centered)
columns of x
by their standard deviations if center
is
TRUE, and the root mean square otherwise. If scale
is FALSE, no
scaling is done.
a centered and/or scaled "timeSeries"
object
## Load Series: x <- 100* LPP2005REC[, c("SBI", "SPI")] ## Scale and Center - X <- scale(x) hist(X[, 1], prob=TRUE) s <- seq(-3, 3, length=201) lines(s, dnorm(s), col="red")
## Load Series: x <- 100* LPP2005REC[, c("SBI", "SPI")] ## Scale and Center - X <- scale(x) hist(X[, 1], prob=TRUE) s <- seq(-3, 3, length=201) lines(s, dnorm(s), col="red")
Get and set the data component of a 'timeSeries'.
series(x) series(x) <- value
series(x) series(x) <- value
x |
a |
value |
a |
series
returns the @.Data
slot of a timeSeries
object in matrix
form.
The assignment version of series
replaces the values of the
time series with value
. The row and column names of
value
are used if not NULL
, otherwise they are left as
in x
. The most natural use is when value
has the same
dimensions as as.matrix(x)
, but if that is not the case the
result is almost as if value
was converted to
"timeSeries"
directly.
Methods for zoo::coredata
and its assignment counterpart are
defined, as well. Users who wish to use them should ensure that
zoo::coredata
is visible (e.g., by calling
library('zoo')
or library('xts')
) or employ the
zoo::
prefix in the calls. These methods are equivalent to
series
and `series<-`
, respectively.
## A Dummy 'timeSeries' Object ts <- timeSeries() ts ## Get the Matrix Part - mat <- series(ts) class(mat) mat ## Assign a New Univariate Series - series(ts) <- rnorm(12) ts ## Assign a New Bivariate Series - series(ts) <- matrix(rnorm(12), ncol = 2) ts
## A Dummy 'timeSeries' Object ts <- timeSeries() ts ## Get the Matrix Part - mat <- series(ts) class(mat) mat ## Assign a New Univariate Series - series(ts) <- rnorm(12) ts ## Assign a New Bivariate Series - series(ts) <- matrix(rnorm(12), ncol = 2) ts
Smooths a "timeSeries"
object.
smoothLowess(x, f = 0.5, ...) smoothSpline(x, spar = NULL, ...) smoothSupsmu(x, bass = 5, ...)
smoothLowess(x, f = 0.5, ...) smoothSpline(x, spar = NULL, ...) smoothSupsmu(x, bass = 5, ...)
x |
an univariate |
f |
the lowess smoother span. This gives the proportion of points in the plot which influence the smooth at each value. Larger values give more smoothness. |
spar |
smoothing parameter, typically (but not necessarily) in (0,1]. By
default |
bass |
controls the smoothness of the fitted curve. Values of up to 10 indicate increasing smoothness. |
... |
optional arguments to be passed to the underlying smoothers. |
The functions smoothLowess
, smoothSpline
,
smoothSupsmu
allow to smooth timeSerie
object. The are
interfaces to the function lowess
, supmsu
. and
smooth.spline
in R's stats
package.
The ...
arguments allow to pass optional arguments to the
underlying stats
functions and tailor the smoothing process.
We refer to the manual pages of these functions for a proper setting
of these options.
a bivariate "timeSeries"
object, the first column holds the
original time series data, the second the smoothed series.
The R core team for the underlying smoother functions.
## Use Close from MSFT's Price Series - head(MSFT) MSFT.CLOSE <- MSFT[, "Close"] head(MSFT.CLOSE) ## Plot Original and Smoothed Series by Lowess - MSFT.LOWESS <- smoothLowess(MSFT.CLOSE, f = 0.1) head(MSFT.LOWESS) plot(MSFT.LOWESS) title(main = "Close - Lowess Smoothed") ## Plot Original and Smoothed Series by Splines - MSFT.SPLINE <- smoothSpline(MSFT.CLOSE, spar = 0.4) head(MSFT.SPLINE) plot(MSFT.SPLINE) title(main = "Close - Spline Smoothed") ## Plot Original and Smoothed Series by Supsmu - MSFT.SUPSMU <- smoothSupsmu(MSFT.CLOSE) head(MSFT.SUPSMU) plot(MSFT.SUPSMU) title(main = "Close - Spline Smoothed")
## Use Close from MSFT's Price Series - head(MSFT) MSFT.CLOSE <- MSFT[, "Close"] head(MSFT.CLOSE) ## Plot Original and Smoothed Series by Lowess - MSFT.LOWESS <- smoothLowess(MSFT.CLOSE, f = 0.1) head(MSFT.LOWESS) plot(MSFT.LOWESS) title(main = "Close - Lowess Smoothed") ## Plot Original and Smoothed Series by Splines - MSFT.SPLINE <- smoothSpline(MSFT.CLOSE, spar = 0.4) head(MSFT.SPLINE) plot(MSFT.SPLINE) title(main = "Close - Spline Smoothed") ## Plot Original and Smoothed Series by Supsmu - MSFT.SUPSMU <- smoothSupsmu(MSFT.CLOSE) head(MSFT.SUPSMU) plot(MSFT.SUPSMU) title(main = "Close - Spline Smoothed")
Sort a "timeSeries"
object with respect to its time stamps.
## S3 method for class 'timeSeries' sort(x, decreasing = FALSE, ...) ## S4 method for signature 'timeSeries' is.unsorted(x, na.rm = FALSE, strictly = FALSE)
## S3 method for class 'timeSeries' sort(x, decreasing = FALSE, ...) ## S4 method for signature 'timeSeries' is.unsorted(x, na.rm = FALSE, strictly = FALSE)
x |
a |
decreasing |
a logical flag. Should we sort in increasing or decreasing order?
By default |
na.rm |
a logical value, should missing values be removed? |
strictly |
logical indicating if the check should be for strictly increasing values. |
... |
optional arguments passed to other methods. |
The method for sort
sorts x
either in increasing or
decreasing time stamp order.
The method for is.unsorted
returns TRUE
if the time
stamps of x
are not sorted in increasing order (including the
case when they are sorted in decreasing order) and FALSE
otherwise. is.unsorted
may also return NA
when there are
NA
s among the time stamps of x
.
All this is in line with the documented functionality of
base::is.unsorted
.
for sort
, a "timeSeries"
object,
for the is.unsorted
method, TRUE
, FALSE
, or
NA
, as described in section ‘Details’.
If is.unsorted
returns NA
when there are NA
s in
the data but not in the time stamps use library{timeSeries}
or
call the function as timeSeries::is.unsorted
. If you need more
details, read the rest of this note.
base::is.unsorted
'sees' the method for "timeSeries"
objects when package timeSeries is loaded (whether or not it is
attached). However, due to the way base::is.unsorted
is
implemented, it may give wrong answers when there are NA
's
among the values of the time series. Developers of packages applying
is.unsorted
on timeSeries objects should import if from package
timeSeries.
The above feature is not a shortcoming of base::is.unsorted
but
a consequence of the fact that the timeSeries method is not consistent
with its semantics. For example, it works on the time stamps, while
is.na
works on the data values.
is.unsorted
for further details on the NA
case
## a monthly calendar series x <- daily2monthly(LPP2005REC[, 1:2])[3:14, ] ## resample the series with respect to the time stamps, resampled <- sample(x) ## the time stamps are unordered resampled is.unsorted(resampled) # TRUE (i.e., not sorted) ## Now sort the series in decreasing time order backward_in_time <- sort(resampled, , decreasing = TRUE) ## time stamps ordered in decreasing order ## but is.unordered requires increasing order: backward_in_time is.unsorted(backward_in_time) # still TRUE ## Is the reverted series ordered? forward_in_time <- rev(backward_in_time) forward_in_time is.unsorted(forward_in_time) # FALSE (i.e., sorted)
## a monthly calendar series x <- daily2monthly(LPP2005REC[, 1:2])[3:14, ] ## resample the series with respect to the time stamps, resampled <- sample(x) ## the time stamps are unordered resampled is.unsorted(resampled) # TRUE (i.e., not sorted) ## Now sort the series in decreasing time order backward_in_time <- sort(resampled, , decreasing = TRUE) ## time stamps ordered in decreasing order ## but is.unordered requires increasing order: backward_in_time is.unsorted(backward_in_time) # still TRUE ## Is the reverted series ordered? forward_in_time <- rev(backward_in_time) forward_in_time is.unsorted(forward_in_time) # FALSE (i.e., sorted)
Searches for outlier splits in a "timeSeries"
object.
splits(x, sd = 3, complement = TRUE, ...)
splits(x, sd = 3, complement = TRUE, ...)
x |
a |
sd |
|
complement |
a logical flag, should the outlier series or its complements be returned? |
... |
arguments to be passed. |
This function finds splits in financial price or index series. If a price or index is splitted we observe a big jump of several standard deviations in the returns, which is identified usually as an outlier.
a "timeSeries"
object
returns
,
cumulated
,
drawdowns
,
spreads
,
midquotes
,
index2wealth
## Create a Return Series with a Split - data <- runif(12, -1, 1) data[6] <- 20 x <- timeSeries(data, timeCalendar(), units="RUNIF") x ## Search for the Split: splits(x, sd=3, complement=TRUE) splits(x, sd=3, complement=FALSE)
## Create a Return Series with a Split - data <- runif(12, -1, 1) data[6] <- 20 x <- timeSeries(data, timeCalendar(), units="RUNIF") x ## Search for the Split: splits(x, sd=3, complement=TRUE) splits(x, sd=3, complement=FALSE)
Compute spreads and midquotes from price streams.
spreads(x, which = c("Bid", "Ask"), tickSize = NULL) midquotes(x, which = c("Bid", "Ask"))
spreads(x, which = c("Bid", "Ask"), tickSize = NULL) midquotes(x, which = c("Bid", "Ask"))
x |
an object of class |
which |
a vector with two character strings naming the column names of the
time series from which to compute the mid quotes and spreads. By
default these are the bid and ask prices with column names
|
tickSize |
the default is |
all functions return an object of class timeSeries
returns
,
cumulated
,
drawdowns
,
splits
,
midquotes
,
index2wealth
## Load the Microsoft Data - setRmetricsOptions(myFinCenter = "GMT") data(MSFT) X = MSFT[1:10, ] head(X) ## Compute Open/Close Midquotes - X.MID <- midquotes(X, which = c("Close", "Open")) colnames(X.MID) <- "X.MID" X.MID ## Compute Open/Close Spreads - X.SPREAD <- spreads(X, which = c("Close", "Open")) colnames(X.SPREAD) <- "X.SPREAD" X.SPREAD
## Load the Microsoft Data - setRmetricsOptions(myFinCenter = "GMT") data(MSFT) X = MSFT[1:10, ] head(X) ## Compute Open/Close Midquotes - X.MID <- midquotes(X, which = c("Close", "Open")) colnames(X.MID) <- "X.MID" X.MID ## Compute Open/Close Spreads - X.SPREAD <- spreads(X, which = c("Close", "Open")) colnames(X.SPREAD) <- "X.SPREAD" X.SPREAD
Returns start or end time stamp of a "timeSeries"
object.
## S3 method for class 'timeSeries' start(x, ...) ## S3 method for class 'timeSeries' end(x, ...)
## S3 method for class 'timeSeries' start(x, ...) ## S3 method for class 'timeSeries' end(x, ...)
x |
an uni- or multivariate |
... |
optional arguments passed to other methods. |
a "timeSeries"
object
## Create a dummy \code{"timeSeries"} tS <- dummyMonthlySeries()[, 1] tS ## Return start and end time stamp c(start(tS), end(tS)) range(time(tS))
## Create a dummy \code{"timeSeries"} tS <- dummyMonthlySeries()[, 1] tS ## Return start and end time stamp c(start(tS), end(tS)) range(time(tS))
Compactly display the structure of a "timeSeries"
object.
## S3 method for class 'timeSeries' str(object, ...)
## S3 method for class 'timeSeries' str(object, ...)
object |
an object of class |
... |
arguments passed to other methods. |
NULL
, invisibly. The function is called for its side effect of
printing a compact representation of the structure of the
"timeSeries"
object.
## Load Microsoft Data Set data(MSFT) X <- MSFT[1:12, 1:4] colnames(X) <- abbreviate(colnames(X), 4) ## Display Structure str(X)
## Load Microsoft Data Set data(MSFT) X <- MSFT[1:12, 1:4] colnames(X) <- abbreviate(colnames(X), 4) ## Display Structure str(X)
Returns the transpose of a "timeSeries"
object.
## S4 method for signature 'timeSeries' t(x)
## S4 method for signature 'timeSeries' t(x)
x |
a 'timeSeries' object. |
a matrix
## Dummy 'timeSeries' with NAs entries data <- matrix(1:24, ncol = 2) s <- timeSeries(data, timeCalendar()) s ## Transpose 'timeSeries' - t(s)
## Dummy 'timeSeries' with NAs entries data <- matrix(1:24, ncol = 2) s <- timeSeries(data, timeCalendar()) s ## Transpose 'timeSeries' - t(s)
Functions and methods extracting and modifying positions of 'timeSeries' objects.
## S4 method for signature 'timeSeries' time(x, ...) ## S3 replacement method for class 'timeSeries' time(x) <- value getTime(x) setTime(x) <- value
## S4 method for signature 'timeSeries' time(x, ...) ## S3 replacement method for class 'timeSeries' time(x) <- value getTime(x) setTime(x) <- value
value |
a valid value for the time component of |
x |
an object of class |
... |
optional arguments passed to other methods. |
time
and time<-
are generic functions with methods for
class "timeSeries"
. They get and set the time component of the
object.
getTime
and setTime
are non-generic alternatives are
non-generic wrappers of time
and time<-
, respectively.
There is another generic function time<-
defined in package
zoo. When that package is loaded its time<-
gets the
"timeSeries"
method. Also, if "time<-"
is called with an
object from class other than "timeSeries"
, the call is
dispatched to "zoo:time<-"
to apply a suitable method.
for time
and getTime
, a "timeDate"
object,
for time<-
and and setTime
, the modified
"timeSeries"
object.
## Create Dummy 'timeSeries' - X <- timeSeries(matrix(rnorm(24), 12), timeCalendar()) ## Return Series Positions - getTime(X) time(X) ## Add / Subtract one Day from X setTime(X) <- time(X) - 24*3600 # sec X time(X) <- time(X) + 24*3600 # sec X
## Create Dummy 'timeSeries' - X <- timeSeries(matrix(rnorm(24), 12), timeCalendar()) ## Return Series Positions - getTime(X) time(X) ## Add / Subtract one Day from X setTime(X) <- time(X) - 24*3600 # sec X time(X) <- time(X) + 24*3600 # sec X
Class "timeSeries"
in package timeSeries.
The main functions for creating objects from class "timeSeries"
timeSeries
and as.timeSeries
.
Objects can also be created by calls of the form
new("timeSeries", .Data, units, positions, format, FinCenter,
recordIDs, title, documentation)
but this is not recommended for
routine work.
The structure of the "timeSeries"
objects should, in general,
be considered internal. The accessor functions to get and set
the components should be used to get and set values of the slots.
.Data
:Object of class "matrix"
containing the data, one column
for each variable.
units
:Object of class "character"
, the unit (or variable, or
column) names of the time series object.
positions
:Object of class "numeric"
, the datetime stamps. If the time
series doesn't have datetime stamps, then positions
is of
length zero.
format
:Object of class "character"
, a datetime format (such as
"%Y-%m-%d"
). if there are no time stamps "format"
is
equal to "counts"
.
FinCenter
:Object of class "character"
, the financial center.
recordIDs
:Object of class "data.frame"
~~
title
:Object of class "character"
, a title for printing.
documentation
:Object of class "character"
, by default it is set to the
current date.
Class "structure"
, from data part.
Class "vector"
, by class "structure", distance 2, with explicit coerce.
Below is a list of the methods that have "timeSeries"
in their
signature. It can be useful for technical purposes, for example in
reporting bugs but most methods that need explanation are documented
with the corresponding functions and looking at their help pages is recommended.
There are short explanations for methods for functions that are not supposed to be called directly.
signature(x = "timeSeries", i = "ANY", j = "index_timeSeries")
: ...
signature(x = "timeSeries", i = "character", j = "character")
: ...
signature(x = "timeSeries", i = "character", j = "index_timeSeries")
: ...
signature(x = "timeSeries", i = "character", j = "missing")
: ...
signature(x = "timeSeries", i = "index_timeSeries", j = "character")
: ...
signature(x = "timeSeries", i = "index_timeSeries", j = "index_timeSeries")
: ...
signature(x = "timeSeries", i = "index_timeSeries", j = "missing")
: ...
signature(x = "timeSeries", i = "matrix", j = "missing")
: ...
signature(x = "timeSeries", i = "missing", j = "character")
: ...
signature(x = "timeSeries", i = "missing", j = "index_timeSeries")
: ...
signature(x = "timeSeries", i = "missing", j = "missing")
: ...
signature(x = "timeSeries", i = "time_timeSeries", j = "ANY")
: ...
signature(x = "timeSeries", i = "time_timeSeries", j = "character")
: ...
signature(x = "timeSeries", i = "time_timeSeries", j = "index_timeSeries")
: ...
signature(x = "timeSeries", i = "time_timeSeries", j = "missing")
: ...
signature(x = "timeSeries", i = "timeDate", j = "character")
: ...
signature(x = "timeSeries", i = "timeDate", j = "index_timeSeries")
: ...
signature(x = "timeSeries", i = "timeDate", j = "missing")
: ...
signature(x = "timeSeries", i = "timeSeries", j = "index_timeSeries")
: ...
signature(x = "timeSeries", i = "timeSeries", j = "missing")
: ...
signature(x = "timeSeries", i = "character", j = "ANY")
: ...
signature(x = "timeSeries", i = "character", j = "missing")
: ...
signature(x = "timeSeries", i = "timeDate", j = "ANY")
: ...
signature(x = "timeSeries", i = "timeDate", j = "missing")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries", value = "ANY")
: ...
signature(x = "timeSeries", value = "factor")
: ...
signature(x = "timeSeries", value = "numeric")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(X = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(what = "timeSeries")
: ...
signature(x = "ANY", y = "timeSeries")
: ...
signature(x = "timeSeries", y = "ANY")
: ...
signature(x = "timeSeries", y = "missing")
: ...
signature(x = "timeSeries", y = "timeSeries")
: ...
signature(from = "ANY", to = "timeSeries")
signature(from = "character", to = "timeSeries")
signature(from = "data.frame", to = "timeSeries")
signature(from = "timeSeries", to = "data.frame")
signature(from = "timeSeries", to = "list")
:
signature(from = "timeSeries", to = "matrix")
signature(from = "timeSeries", to = "ts")
:
signature(from = "ts", to = "timeSeries")
:
coerce
should not be called directly.
Use as(object, "target_class")
instead.
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries", value = "ANY")
: ...
signature(x = "timeSeries", value = "matrix")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries", value = "list")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(object = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(.Object = "timeSeries")
:
don't call "initialize"
, call new("timeSeries", ...)
instead. Even better, call timeSeries
.
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "ANY", y = "timeSeries")
: ...
signature(x = "matrix", y = "timeSeries")
: ...
signature(x = "numeric", y = "timeSeries")
: ...
signature(x = "timeSeries", y = "ANY")
: ...
signature(x = "timeSeries", y = "matrix")
: ...
signature(x = "timeSeries", y = "missing")
: ...
signature(x = "timeSeries", y = "numeric")
: ...
signature(x = "timeSeries", y = "timeSeries")
: ...
signature(object = "timeSeries")
: ...
signature(object = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(e1 = "array", e2 = "timeSeries")
: ...
signature(e1 = "timeSeries", e2 = "array")
: ...
signature(e1 = "timeSeries", e2 = "timeSeries")
: ...
signature(e1 = "timeSeries", e2 = "ts")
: ...
signature(e1 = "timeSeries", e2 = "vector")
: ...
signature(e1 = "ts", e2 = "timeSeries")
: ...
signature(e1 = "vector", e2 = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "ANY", y = "timeSeries")
: ...
signature(x = "timeSeries", y = "ANY")
: ...
signature(x = "timeSeries", y = "missing")
: ...
signature(x = "timeSeries", y = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries", value = "ANY")
: ...
signature(x = "timeSeries", value = "timeDate")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries", value = "ANY")
: ...
signature(x = "timeSeries", value = "matrix")
: ...
signature(object = "timeSeries")
: ...
signature(object = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(object = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
signature(x = "timeSeries")
: ...
timeSeries
and
as.timeSeries
for creating and converting to
"timeSeries"
,
readSeries
for importing from a text file,
dummyDailySeries
for creation of dummy daily and monthly time series,
as.matrix
, time
, finCenter
,
getUnits
, dim
, start
,
etc., for accessing properties of the time series.
## see the help page for timeSeries() showClass("timeSeries")
## see the help page for timeSeries() showClass("timeSeries")
Many base R statistical functions work on (the data part of)
timeSeries
objects without the need for special methods, e.g.,
var
, sd
, cov
, cor
, probability densities,
and others. This page gives some examples with such functions.
colStats
,
colVars
, and other colXXX
functions
## Load Microsoft Data Set - data(MSFT) X = MSFT[, 1:4] X = 100 * returns(X) ## Compute Covariance Matrix - cov(X[, "Open"], X[, "Close"]) cov(X) cor(X)
## Load Microsoft Data Set - data(MSFT) X = MSFT[, 1:4] X = 100 * returns(X) ## Compute Covariance Matrix - cov(X[, "Open"], X[, "Close"]) cov(X) cor(X)
timeSeries
creates a "timeSeries"
object from scratch.
timeSeries(data, charvec, units = NULL, format = NULL, zone = "", FinCenter = "", recordIDs = data.frame(), title = NULL, documentation = NULL, ...)
timeSeries(data, charvec, units = NULL, format = NULL, zone = "", FinCenter = "", recordIDs = data.frame(), title = NULL, documentation = NULL, ...)
data |
a |
charvec |
a character vector of dates and times or any objects which can
be coerced to a |
units |
an optional character string, which allows to overwrite the
current column names of a |
format |
the format specification of the input character vector, a character string with the format in POSIX notation. |
zone |
the time zone or financial center where the data were recorded. |
FinCenter |
a character with the the location of the financial center named as "continent/city". |
recordIDs |
for |
title |
an optional title string, if not specified the input's data name is deparsed. |
documentation |
optional documentation string, or a vector of character strings. |
... |
arguments passed to other methods. |
Generation of Time Series Objects:
We have defined a "timeSeries"
class which is in many aspects
similar to the S-Plus class with the same name, but has also some
important differences. The class has seven Slots, the 'Data' slot
which holds the time series data in matrix form, the 'position' slot
which holds the time/date as a character vector, the 'format' and
'FinCenter' slots which are the same as for the 'timeDate' object, the
'units' slot which holds the column names of the data matrix, and a
'title' and a 'documentation' slot which hold descriptive character
strings. Date and time is managed in the same way as for
timeDate
objects.
as.timeSeries
also creates "timeSeries"
objects.
as.timeSeries(x)
is mostly equivalent to timeSeries(x)
but the two functions have different methods. Beside that, the main
difference between the two functions is that as.timeSeries
doesn't accept additional arguments. The one argument call is
naturally interpreted as ‘convert to’, so
as.timeSeries
is more expressive and is recommended in
that case.
"timeSeries"
methods are provided for many base R functions,
including arithmetic operations, mathematical functions, print
,
summary
, and time series functions. Not all are explicitly
documented, since they can just be used.
an S4 object of class "timeSeries"
as.timeSeries
,
class timeSeries
,
## Load Microsoft data - # Microsoft Data: setRmetricsOptions(myFinCenter = "GMT") data(MSFT) head(MSFT) ## Create a 'timeSeries' object, the direct Way ... Close <- MSFT[, 5] head(Close) ## Create a 'timeSeries' object from scratch - data <- as.matrix(MSFT[, 4]) charvec <- rownames(MSFT) Close <- timeSeries(data, charvec, units = "Close") head(Close) c(start(Close), end(Close)) ## Cut out April data from 2001 - tsApril01 <- window(Close, "2001-04-01", "2001-04-30") tsApril01 ## Compute Continuous Returns - returns(tsApril01) ## Compute Discrete Returns - returns(tsApril01, type = "discrete") ## Compute Discrete Returns, Don't trim - returns(tsApril01, trim = FALSE) ## Compute Discrete Returns, Use Percentage Values - tsRet <- returns(tsApril01, percentage = TRUE, trim = FALSE) tsRet ## Aggregate Weekly - GoodFriday(2001) to <- timeSequence(from = "2001-04-11", length.out = 3, by = "week") from <- to - 6*24*3600 from to applySeries(tsRet, from, to, FUN = sum) ## Create large 'timeSeries' objects with different 'charvec' object classes - # charvec is a 'timeDate' object head(timeSeries(1:1e6L, timeSequence(length.out = 1e6L, by = "sec"))) head(timeSeries(1:1e6L, seq(Sys.timeDate(), length.out = 1e6L, by = "sec"))) # 'charvec' is a 'POSIXt' object head(timeSeries(1:1e6L, seq(Sys.time(), length.out = 1e6L, by = "sec"))) # 'charvec' is a 'numeric' object head(timeSeries(1:1e6L, 1:1e6L))
## Load Microsoft data - # Microsoft Data: setRmetricsOptions(myFinCenter = "GMT") data(MSFT) head(MSFT) ## Create a 'timeSeries' object, the direct Way ... Close <- MSFT[, 5] head(Close) ## Create a 'timeSeries' object from scratch - data <- as.matrix(MSFT[, 4]) charvec <- rownames(MSFT) Close <- timeSeries(data, charvec, units = "Close") head(Close) c(start(Close), end(Close)) ## Cut out April data from 2001 - tsApril01 <- window(Close, "2001-04-01", "2001-04-30") tsApril01 ## Compute Continuous Returns - returns(tsApril01) ## Compute Discrete Returns - returns(tsApril01, type = "discrete") ## Compute Discrete Returns, Don't trim - returns(tsApril01, trim = FALSE) ## Compute Discrete Returns, Use Percentage Values - tsRet <- returns(tsApril01, percentage = TRUE, trim = FALSE) tsRet ## Aggregate Weekly - GoodFriday(2001) to <- timeSequence(from = "2001-04-11", length.out = 3, by = "week") from <- to - 6*24*3600 from to applySeries(tsRet, from, to, FUN = sum) ## Create large 'timeSeries' objects with different 'charvec' object classes - # charvec is a 'timeDate' object head(timeSeries(1:1e6L, timeSequence(length.out = 1e6L, by = "sec"))) head(timeSeries(1:1e6L, seq(Sys.timeDate(), length.out = 1e6L, by = "sec"))) # 'charvec' is a 'POSIXt' object head(timeSeries(1:1e6L, seq(Sys.time(), length.out = 1e6L, by = "sec"))) # 'charvec' is a 'numeric' object head(timeSeries(1:1e6L, 1:1e6L))
Three data sets used in example files.
The following datasets are available:
Daily Microsoft OHLC (Open-high-low-close) prices and volume from 2000-09-27 to 2001-09-27.
USD/CHF intraday foreign exchange rates.
Swiss pension fund assets returns benchmark from 2005-11-01 to 2007-04-11.
The datasets are objects from class "timeSeries"
.
No further information about the LPP2005REC
is available. The
meaning of the columns?
## LPP2005 example data set data(LPP2005REC) plot(LPP2005REC, type = "l") class(LPP2005REC) dim(LPP2005REC) head(LPP2005REC) LPP2005REC[1:5, 2:4] range(time(LPP2005REC)) summary(LPP2005REC) ## MSFT example data set data(MSFT) plot(MSFT[, 1:4], type = "l") plot(MSFT[, 5], type = "h") class(MSFT) range(time(MSFT)) head(MSFT) ## Plot USDCHF example data set data(USDCHF) plot(USDCHF) range(time(USDCHF)) head(USDCHF)
## LPP2005 example data set data(LPP2005REC) plot(LPP2005REC, type = "l") class(LPP2005REC) dim(LPP2005REC) head(LPP2005REC) LPP2005REC[1:5, 2:4] range(time(LPP2005REC)) summary(LPP2005REC) ## MSFT example data set data(MSFT) plot(MSFT[, 1:4], type = "l") plot(MSFT[, 5], type = "h") class(MSFT) range(time(MSFT)) head(MSFT) ## Plot USDCHF example data set data(USDCHF) plot(USDCHF) range(time(USDCHF)) head(USDCHF)
Objects from class "timeSeries"
can be subsetted in different
ways. Methods are defined for the subsetting operators "$"
,
"["
and their assignment versions, as well as for some related
functions from base R. A function to drop or extract outliers is also
described here.
## S3 method for class 'timeSeries' head(x, n = 6, recordIDs = FALSE, ...) ## S3 method for class 'timeSeries' tail(x, n = 6, recordIDs = FALSE, ...) outlier(x, sd = 5, complement = TRUE, ...)
## S3 method for class 'timeSeries' head(x, n = 6, recordIDs = FALSE, ...) ## S3 method for class 'timeSeries' tail(x, n = 6, recordIDs = FALSE, ...) outlier(x, sd = 5, complement = TRUE, ...)
x |
an object of class |
n |
an integer specifying the number of lines to be returned.
By default |
recordIDs |
a logical value. Should the |
sd |
a numeric value of standard deviations, e.g. 10 means that values larger or smaller than ten times the standard deviation will be removed from the series. |
complement |
a logical flag. If |
... |
arguments passed to other methods. |
The "timeSeries"
methods for the subsetting operators "$"
,
"["
and their assignment versions, as well as for the functions
head
and tail
are meant to do what the user expects.
TODO: Further details are needed here, despite the above paragraph.
outlier
drops the outliers if complement = TRUE
and
returns only them if complement = FALSE
.
All functions described here return "timeSeries"
objects.
See also window
which extracts the sub-series between
two datetimes.
All functions return an object of class "timeSeries"
.
## Create an Artificial 'timeSeries' Object setRmetricsOptions(myFinCenter = "GMT") charvec <- timeCalendar() set.seed(4711) data <- matrix(exp(cumsum(rnorm(12, sd = 0.1)))) tS <- timeSeries(data, charvec, units = "tS") tS ## Subset Series by Counts "[" tS[1:3, ] ## Subset the Head of the Series head(tS, 6)
## Create an Artificial 'timeSeries' Object setRmetricsOptions(myFinCenter = "GMT") charvec <- timeCalendar() set.seed(4711) data <- matrix(exp(cumsum(rnorm(12, sd = 0.1)))) tS <- timeSeries(data, charvec, units = "tS") tS ## Subset Series by Counts "[" tS[1:3, ] ## Subset the Head of the Series head(tS, 6)
Extracts and analyzes turning points of an univariate
"timeSeries"
object.
turns(x, ...) turnsStats(x, doplot = TRUE)
turns(x, ...) turnsStats(x, doplot = TRUE)
x |
an univariate |
... |
optional arguments passed to the function |
doplot |
a logical flag, should the results be plotted? By default TRUE. |
The function turns
determines the number and the positions of
extrema (turning points, either peaks or pits) in a regular time
series.
The function turnsStats
calculates the quantity of information
associated with the observations in this series, according to
Kendall's information theory.
The functions are borrowed from the contributed R package
pastecs
and made ready for working together with univariate
timeSeries
objects. You need not to load the R package
pastecs
, the code parts we need here are builtin in the
timeSeries
package.
We have renamed the function turnpoints
to turns
to
distinguish between the original function in the contributed R package
pastecs
and our Rmetrics function wrapper.
For further details please consult the help page from the contributed
R package pastecs
.
for turns
, an object of class timeSeries
.
for turnsStats
, an object of class turnpoints
with the
following entries:
data |
The dataset to which the calculation is done. |
n |
The number of observations. |
points |
The value of the points in the series, after elimination of ex-aequos. |
pos |
The position of the points on the time scale in the series (including ex-aequos). |
exaequos |
Location of exaequos (1), or not (0). |
nturns |
Total number of turning points in the whole time series. |
firstispeak |
Is the first turning point a peak (TRUE), or not (FALSE). |
peaks |
Logical vector. Location of the peaks in the time series without ex-aequos. |
pits |
Logical vector. Location of the pits in the time series without ex-aequos. |
tppos |
Position of the turning points in the initial series (with ex-aequos). |
proba |
Probability to find a turning point at this location. |
info |
Quantity of information associated with this point. |
Frederic Ibanez and Philippe Grosjean for code from the contributed R
package pastecs
and Rmetrics for the function wrapper.
Ibanez, F., 1982, Sur une nouvelle application de la theorie de l'information a la description des series chronologiques planctoniques. J. Exp. Mar. Biol. Ecol., 4, 619–632
Kendall, M.G., 1976, Time Series, 2nd ed. Charles Griffin and Co, London.
## Load Swiss Equities Series - SPI.RET <- LPP2005REC[, "SPI"] head(SPI.RET) ## Cumulate and Smooth the Series - SPI <- smoothLowess(cumulated(SPI.RET), f=0.05) plot(SPI) ## Plot Turn Points Series - SPI.SMOOTH <- SPI[, 2] tP <- turns(SPI.SMOOTH) plot(tP) ## Compute Statistics - turnsStats(SPI.SMOOTH)
## Load Swiss Equities Series - SPI.RET <- LPP2005REC[, "SPI"] head(SPI.RET) ## Cumulate and Smooth the Series - SPI <- smoothLowess(cumulated(SPI.RET), f=0.05) plot(SPI) ## Plot Turn Points Series - SPI.SMOOTH <- SPI[, 2] tP <- turns(SPI.SMOOTH) plot(tP) ## Compute Statistics - turnsStats(SPI.SMOOTH)
Gets and sets the column names of a "timeSeries"
object. The
column names are also called units or unit names.
getUnits(x) setUnits(x) <- value
getUnits(x) setUnits(x) <- value
x |
a |
value |
a character vector of unit names. |
## A Dummy 'timeSeries' Object tS <- dummyMonthlySeries() tS ## Get the Units - getUnits(tS) ## Assign New Units to the Series - setUnits(tS) <- c("A", "B") head(tS)
## A Dummy 'timeSeries' Object tS <- dummyMonthlySeries() tS ## Get the Units - getUnits(tS) ## Assign New Units to the Series - setUnits(tS) <- c("A", "B") head(tS)
Converts an index series to a wealth series normalizing the starting value to one.
index2wealth(x)
index2wealth(x)
x |
an object of class 'timeSeries'. |
returns a time series object of the same class as the input
argument x
normalizing the starting value to one.
returns
,
cumulated
,
drawdowns
,
splits
,
spreads
,
midquotes
,
## Load MSFT Open Prices - INDEX <- MSFT[1:20, 1] INDEX ## Compute Wealth Normalized to 100 - 100 * index2wealth(INDEX)
## Load MSFT Open Prices - INDEX <- MSFT[1:20, 1] INDEX ## Compute Wealth Normalized to 100 - 100 * index2wealth(INDEX)
Extract a part from a "timeSeries"
object.
## S3 method for class 'timeSeries' window(x, start, end, ...)
## S3 method for class 'timeSeries' window(x, start, end, ...)
x |
an object of class |
start , end
|
starting date and end date, |
... |
arguments passed to other methods. |
window
extracts the subset of the "timeSeries"
object
x
observed between the times start
and end
.
## load LPP benchmark returns x <- LPP2005REC[, 7:9] range(time(x)) ## extract data for January 2006 window(x, "2006-01-01", "2006-01-31")
## load LPP benchmark returns x <- LPP2005REC[, 7:9] range(time(x)) ## extract data for January 2006 window(x, "2006-01-01", "2006-01-31")