Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:eXtensible Time Series
Version:0.14.1
Depends:R (≥ 3.6.0), zoo (≥ 1.7-12)
Imports:methods
LinkingTo:zoo
Suggests:timeSeries, timeDate, tseries, chron, tinytest
LazyLoad:yes
Description:Provide for uniform handling of R's different time-based data classes by extending zoo, maximizing native format information preservation and allowing for user level customization and extension, while simplifying cross-class interoperability.
License:GPL-2 |GPL-3 [expanded from: GPL (≥ 2)]
URL:https://joshuaulrich.github.io/xts/,https://github.com/joshuaulrich/xts
BugReports:https://github.com/joshuaulrich/xts/issues
Encoding:UTF-8
NeedsCompilation:yes
Packaged:2024-10-15 15:25:09 UTC; josh
Author:Jeffrey A. Ryan [aut, cph], Joshua M. Ulrich [cre, aut], Ross Bennett [ctb], Corwin Joy [ctb]
Maintainer:Joshua M. Ulrich <josh.m.ulrich@gmail.com>
Repository:CRAN
Date/Publication:2024-10-15 17:30:02 UTC

xts: extensible time-series

Description

Extensible time series class and methods, extending and behaving like zoo.

Details

Easily convert one ofR's many time-series (and non-time-series) classes to atrue time-based object which inherits all of zoo's methods, while allowingfor new time-based tools where appropriate.

Additionally, one may usexts to create new objects which can containarbitrary attributes named during creation as name=value pairs.

Author(s)

Jeffrey A. Ryan and Joshua M. Ulrich

Maintainer: Joshua M. Ulrichjosh.m.ulrich@gmail.com

See Also

xts(),as.xts(),reclass(),zoo()


Internal ISO 8601:2004(e) Time Parser

Description

This function replicates most of the ISO standard for parsing times andtime-based ranges in a universally accepted way. The best documentation isthe official ISO page as well as the Wikipedia entry for ISO 8601:2004.

Usage

.parseISO8601(x, start, end, tz = "")

Arguments

x

A character string conforming to the ISO 8601:2004(e) rules.

start

Lower constraint on range.

end

Upper constraint of range

tz

Timezone (tzone) to use internally.

Details

The basic idea is to create the endpoints of a range, given a stringrepresentation. These endpoints are aligned in POSIXct time to the zerosecond of the day at the beginning, and the 59.9999th second of the 59thminute of the 23rd hour of the final day.

For dates prior to the epoch (1970-01-01) the ending time is aligned to the59.0000 second. This is due to a bug/feature in theR implementation ofas.POSIXct() andmktime0() at the C-source level. This limits theprecision of ranges prior to 1970 to 1 minute granularity with the currentxts workaround.

Recurring times over multiple days may be specified using the "T" notation.See the examples for details.

Value

A two element list with an entry named ‘first.time’ andone named ‘last.time’.

Note

There is no checking done to test for a properly constructed ISOformat string. This must be correctly entered by the user.

When using durations, it is important to note that the time of the durationspecified is not necessarily the same as the realized periods that may bereturned when applied to an irregular time series. This is not a bug, it isa standards and implementation gotcha.

Author(s)

Jeffrey A. Ryan

References

https://en.wikipedia.org/wiki/ISO_8601
https://www.iso.org/iso-8601-date-and-time-format.html

Examples

# the start and end of 2000.parseISO8601('2000')# the start of 2000 and end of 2001.parseISO8601('2000/2001')# May 1, 2000 to Dec 31, 2001.parseISO8601('2000-05/2001')# May 1, 2000 to end of Feb 2001.parseISO8601('2000-05/2001-02')# Jan 1, 2000 to Feb 29, 2000; note the truncated time on the LHS.parseISO8601('2000-01/02')# 8:30 to 15:00 (used in xts subsetting to extract recurring times).parseISO8601('T08:30/T15:00')

Extract and Set .CLASS Attribute

Description

Extraction and replacement functions to access the xts '.CLASS' attribute.The '.CLASS' attribute is used byreclass() to transform an xts objectback to its original class.

Usage

CLASS(x)CLASS(x) <- value

Arguments

x

An xts object.

value

The new value to assign to the '.CLASS' attribute.

Details

This is meant for use in conjunction withtry.xts() andreclass() and isis not intended for daily use. While it's possible to interactively coerceobjects to other classes than originally derived from, it's likely to causeunexpected behavior. It is best to use the usualas.xts() and otherclasses'as methods.

Value

Called for its side-effect of changing the '.CLASS' attribute.

Author(s)

Jeffrey A. Ryan

See Also

as.xts(),reclass()


Extract Subsets of xts Objects

Description

Details on efficient subsetting of xts objects for maximum performanceand compatibility.

Usage

## S3 method for class 'xts'x[i, j, drop = FALSE, which.i = FALSE, ...]

Arguments

x

An xts object.

i

The rows to extract. Can be a numeric vector, time-based vector, oran ISO-8601 style range string (see details).

j

The columns to extract, either a numeric vector of column locationsor a character vector of column names.

drop

Should dimension be dropped, if possible? See notes section.

which.i

Logical value that determines whether a subset xts object isreturned (the default), or the locations of the matching rows (whenwhich.i = TRUE).

...

Additional arguments (currently unused).

Details

One of the primary motivations and key points of differentiation of xts isthe ability to subset rows by specifying ISO-8601 compatible range strings.This allows for natural range-based time queries without requiring priorknowledge of the underlying class used for the time index.

Wheni is a character string, it is processed as an ISO-8601 formatteddatetime or time range using.parseISO8601(). A single datetime isparsed from left to to right, according to the following specification:

CCYYMMDD HH:MM:SS.ss+

A time range can be specified by two datetimes separated by a forward slashor double-colon. For example:

CCYYMMDD HH:MM:SS.ss+/CCYYMMDD HH:MM:SS.ss

The ISO8601 time range subsetting uses a custom binary search algorithm toefficiently find the beginning and end of the time range.i can also be avector of ISO8601 time ranges, which enables subsetting by multiplenon-contiguous time ranges in one subset call.

The above parsing, both for single datetimes and time ranges, will be doneon each element wheni is a charactervector. This is very inefficient,especially for long vectors. In this case, it's recommened to useI(i) sothe xts subset function can process the vector more efficiently. Anotheralternative is to converti to POSIXct before passing it to the subsetfunction. See the examples for an illustration of usingI(i).

The xts index is stored as POSIXct internally, regardless of the value ofitstclass attribute. So the fastest time-based subsetting is always wheni is a POSIXct vector.

Value

An xts object containing the subset ofx. Whenwhich.i = TRUE,the corresponding integer locations of the matching rows is returned.

Note

By design, xts objects always have two dimensions. They cannot bevectors like zoo objects. Thereforedrop = FALSE by default in order topreserve the xts object's dimensions. This is different from both matrix andzoo, which usedrop = TRUE by default. Explicitly settingdrop = TRUEmay be needed when performing certain matrix operations.

Author(s)

Jeffrey A. Ryan

References

ISO 8601: Date elements and interchange formats - Informationinterchange - Representation of dates and timehttps://www.iso.org

See Also

xts(),.parseISO8601(),.index()

Examples

x <- xts(1:3, Sys.Date()+1:3)xx <- cbind(x,x)# drop = FALSE for xts, differs from zoo and matrixz <- as.zoo(xx)z/z[,1]m <- as.matrix(xx)m/m[,1]# this will fail with non-conformable arrays (both retain dim)tryCatch(  xx/x[,1],   error = function(e) print("need to set drop = TRUE"))# correct wayxx/xx[,1,drop = TRUE]# or less efficientlyxx/drop(xx[,1])# likewisexx/coredata(xx)[,1]x <- xts(1:1000, as.Date("2000-01-01")+1:1000)y <- xts(1:1000, as.POSIXct(format(as.Date("2000-01-01")+1:1000)))x.subset <- index(x)[1:20]x[x.subset] # by original index typesystem.time(x[x.subset]) x[as.character(x.subset)] # by character string. Beware!system.time(x[as.character(x.subset)]) # slow!system.time(x[I(as.character(x.subset))]) # wrapped with I(), faster!x['200001'] # January 2000x['1999/2000'] # All of 2000 (note there is no need to use the exact start)x['1999/200001'] # January 2000 x['2000/200005'] # 2000-01 to 2000-05x['2000/2000-04-01'] # through April 01, 2000y['2000/2000-04-01'] # through April 01, 2000 (using POSIXct series)### Time of day subsetting i <- 0:60000focal_date <- as.numeric(as.POSIXct("2018-02-01", tz = "UTC"))x <- .xts(i, c(focal_date + i * 15), tz = "UTC", dimnames = list(NULL, "value"))# Select all observations between 9am and 15:59:59.99999:w1 <- x["T09/T15"] # or x["T9/T15"]head(w1)# timestring is of the form THH:MM:SS.ss/THH:MM:SS.ss# Select all observations between 13:00:00 and 13:59:59.9999 in two ways:y1 <- x["T13/T13"]head(y1)x[.indexhour(x) == 13]# Select all observations between 9:30am and 30 seconds, and 4.10pm:x["T09:30:30/T16:10"]# It is possible to subset time of day overnight.# e.g. This is useful for subsetting FX time series which trade 24 hours on week days# Select all observations between 23:50 and 00:15 the following day, in the xts time zonez <- x["T23:50/T00:14"]z["2018-02-10 12:00/"] # check the last day# Select all observations between 7pm and 8.30am the following day:z2 <- x["T19:00/T08:29:59"]head(z2); tail(z2)

Add vertical lines to an existing xts plot

Description

Add vertical lines and labels to an existing xts plot.

Usage

addEventLines(events, main = "", on = 0, lty = 1, lwd = 1, col = 1, ...)

Arguments

events

An xts object of events and their associated labels. It isensured that the first column ofevents is the event description/label.

main

Main title for a new panel, if drawn.

on

Panel number to draw on. A new panel will be drawn ifon = NA.The default,on = 0, will add to the active panel. The active panel isdefined as the panel on which the most recent action was performed. Notethat only the first element ofon is checked for the default behavior toadd to the last active panel.

lty

Set the line type, same as inpar().

lwd

Set the line width, same as inpar().

col

Color palette to use, set by default to rational choices.

...

Any other passthrough parameters totext() to control howthe event labels are drawn.

Author(s)

Ross Bennett

Examples

## Not run: library(xts)data(sample_matrix)sample.xts <- as.xts(sample_matrix)events <- xts(letters[1:3],               as.Date(c("2007-01-12", "2007-04-22", "2007-06-13")))plot(sample.xts[,4])addEventLines(events, srt = 90, pos = 2)## End(Not run)

Add Legend

Description

Add a legend to an existing panel.

Usage

addLegend(  legend.loc = "topright",  legend.names = NULL,  col = NULL,  ncol = 1,  on = 0,  ...)

Arguments

legend.loc

One of nine locations: bottomright, bottom, bottomleft,left, topleft, top, topright, right, or center.

legend.names

Character vector of names for the legend. WhenNULL,the column names of the current plot object are used.

col

Fill colors for the legend. WhenNULL, the colorset of thecurrent plot object data is used.

ncol

Number of columns for the legend.

on

Panel number to draw on. A new panel will be drawn ifon = NA.The default,on = 0, will add to the active panel. The active panel isdefined as the panel on which the most recent action was performed. Notethat only the first element ofon is checked for the default behavior toadd to the last active panel.

...

Any other passthrough parameters tolegend().

Author(s)

Ross Bennett


Add a panel to an existing xts plot

Description

Apply a function to the data of an existing xts plot object and plot theresult on an existing or new panel.FUN should have argumentsx orRfor the data of the existing xts plot object to be passed to. All otheradditional arguments forFUN are passed through ....

Usage

addPanel(  FUN,  main = "",  on = NA,  type = "l",  col = NULL,  lty = 1,  lwd = 1,  pch = 1,  ...)

Arguments

FUN

An xts object to plot.

main

Main title for a new panel if drawn.

on

Panel number to draw on. A new panel will be drawn ifon = NA.

type

The type of plot to be drawn, same as inplot().

col

Color palette to use, set by default to rational choices.

lty

Set the line type, same as inpar().

lwd

Set the line width, same as inpar().

pch

The type of plot to be drawn, same as inpar().

...

Additional named arguments passed through toFUN and anyother graphical passthrough parameters.

Author(s)

Ross Bennett

See Also

plot.xts(),addSeries()

Examples

library(xts)data(sample_matrix)sample.xts <- as.xts(sample_matrix)calcReturns <- function(price, method = c("discrete", "log")){  px <- try.xts(price)  method <- match.arg(method)[1L]  returns <- switch(method,    simple = ,    discrete = px / lag(px) - 1,    compound = ,    log = diff(log(px)))  reclass(returns, px)}# plot the Closeplot(sample.xts[,"Close"])# calculate returns addPanel(calcReturns, method = "discrete", type = "h")# Add simple moving average to panel 1addPanel(rollmean, k = 20, on = 1)addPanel(rollmean, k = 40, col = "blue", on = 1)

Add a polygon to an existing xts plot

Description

Draw a polygon on an existing xts plot by specifying a time series of ycoordinates. The xts index is used for the x coordinates and the first twocolumns are the upper and lower y coordinates, respectively.

Usage

addPolygon(x, y = NULL, main = "", on = NA, col = NULL, ...)

Arguments

x

An xts object to plot. Must contain 2 columns for the upper andthe lower y coordinates for the polygon. The first column is interpretedas upper y coordinates and the second column as the lower y coordinates.

y

NULL, not used.

main

Main title for a new panel, if drawn.

on

Panel number to draw on. A new panel will be drawn ifon = NA.

col

Color palette to use, set by default to rational choices.

...

Any other passthrough parameters topar().

Author(s)

Ross Bennett

References

Based on code by Dirk Eddelbuettel fromhttp://dirk.eddelbuettel.com/blog/2011/01/16/

Examples

## Not run: library(xts)data(sample_matrix)x <- as.xts(sample_matrix)[,1]ix <- index(x["2007-02"])shade <- xts(matrix(rep(range(x), each = length(ix)), ncol = 2), ix)plot(x)# set on = -1 to draw the shaded region *behind* the main seriesaddPolygon(shade, on = -1, col = "lightgrey")## End(Not run)

Add a time series to an existing xts plot

Description

Add a time series to an existing xts plot

Usage

addSeries(  x,  main = "",  on = NA,  type = "l",  col = NULL,  lty = 1,  lwd = 1,  pch = 1,  ...)

Arguments

x

An xts object to add to the plot.

main

Main title for a new panel if drawn.

on

Panel number to draw on. A new panel will be drawn ifon = NA.

type

The type of plot to be drawn, same as inplot().

col

Color palette to use, set by default to rational choices.

lty

Set the line type, same as inpar().

lwd

Set the line width, same as inpar().

pch

The type of plot to be drawn, same as inpar().

...

Any other passthrough graphical parameters.

Author(s)

Ross Bennett


Align seconds, minutes, and hours to beginning of next period.

Description

Change timestamps to the start of the next period, specified in multiples ofseconds.

Usage

adj.time(x, ...)align.time(x, ...)## S3 method for class 'xts'align.time(x, n = 60, ...)shift.time(x, n = 60, ...)

Arguments

x

Object containing timestamps to align.

...

Additional arguments. See details.

n

Number of seconds to adjust by.

Details

This function is an S3 generic. The result is to round up to the next perioddetermined by 'n modulo x'.

Value

A new object with the same class asx.

Author(s)

Jeffrey A. Ryan with input from Brian Peterson

See Also

to.period()

Examples

x <- Sys.time() + 1:1000# every 10 secondsalign.time(x, 10)# align to next whole minutealign.time(x, 60)# align to next whole 10 min intervalalign.time(x, 10 * 60)

Apply Function over Calendar Periods

Description

Apply a specified function to each distinct period in a given time seriesobject.

Usage

apply.daily(x, FUN, ...)apply.weekly(x, FUN, ...)apply.monthly(x, FUN, ...)apply.quarterly(x, FUN, ...)apply.yearly(x, FUN, ...)

Arguments

x

A time-series object coercible to xts.

FUN

A function to apply to each period.

...

Additional arguments toFUN.

Details

Simple mechanism to apply a function to non-overlapping time periods, e.g.weekly, monthly, etc. Different from rolling functions in that this willsubset the data based on the specified time period (implicit in the call),and return a vector of values for each period in the original data.

Essentially a wrapper to thexts functionsendpoints() andperiod.apply(), mainly as a convenience.

Value

A vector of results produced byFUN, corresponding to theappropriate periods.

Note

WhenFUN = mean the results will contain one column for everycolumn in the input, which is different from other math functions (e.g.median,sum,prod,sd, etc.).

FUN = mean works by column because the default methodstats::meanpreviously worked by column for matrices and data.frames. R Core changed thebehavior ofmean to always return one column in order to be consistentwith the other math functions. This broke somexts dependencies andmean.xts() was created to maintain the original behavior.

UsingFUN = mean will print a message that describes this inconsistency.To avoid the message and confusion, useFUN = colMeans to calculate meansby column and useFUN = function(x) mean to calculate one mean for all thedata. Setoptions(xts.message.period.apply.mean = FALSE) to suppress thismessage.

Author(s)

Jeffrey A. Ryan

See Also

endpoints(),period.apply(),to.monthly()

Examples

xts.ts <- xts(rnorm(231),as.Date(13514:13744,origin="1970-01-01"))start(xts.ts)end(xts.ts)apply.monthly(xts.ts,colMeans)apply.monthly(xts.ts,function(x) var(x))

Coerce an xts Object to an Environment by Column

Description

Method to automatically convert an xts object to an environment containingvectors representing each column of the original xts object. The name ofeach object in the resulting environment corresponds to the name of thecolumn of the xts object.

Usage

## S3 method for class 'xts'as.environment(x)

Arguments

x

An xts object.

Value

An environment containingncol(x) vectors extracted bycolumn fromx.

Note

Environments do not preserve (or have knowledge) of column order andcannot be subset by an integer index.

Author(s)

Jeffrey A. Ryan

Examples

x <- xts(1:10, Sys.Date()+1:10)colnames(x) <- "X"y <- xts(1:10, Sys.Date()+1:10)colnames(x) <- "Y"xy <- cbind(x,y)colnames(xy)e <- as.environment(xy)    # currently using xts-style positive k ls(xy)ls.str(xy)

Convert Objects To and From xts

Description

Conversion S3 methods to coerce data objects of arbitrary classes to xtsand back, without losing any attributes of the original format.

Usage

## S3 method for class 'Date'as.xts(x, ...)## S3 method for class 'POSIXt'as.xts(x, ...)## S3 method for class 'data.frame'as.xts(  x,  order.by,  dateFormat = "POSIXct",  frequency = NULL,  ...,  .RECLASS = FALSE)## S3 method for class 'irts'as.xts(x, order.by, frequency = NULL, ..., .RECLASS = FALSE)## S3 method for class 'matrix'as.xts(  x,  order.by,  dateFormat = "POSIXct",  frequency = NULL,  ...,  .RECLASS = FALSE)## S3 method for class 'timeDate'as.xts(x, ...)## S3 method for class 'timeSeries'as.xts(  x,  dateFormat = "POSIXct",  FinCenter,  recordIDs,  title,  documentation,  ...,  .RECLASS = FALSE)## S3 method for class 'ts'as.xts(x, dateFormat, ..., .RECLASS = FALSE)as.xts(x, ...)xtsible(x)## S3 method for class 'yearmon'as.xts(x, ...)## S3 method for class 'yearqtr'as.xts(x, ...)## S3 method for class 'zoo'as.xts(x, order.by = index(x), frequency = NULL, ..., .RECLASS = FALSE)

Arguments

x

Data object to convert. See details for supported types.

...

Additional parameters or attributes.

order.by,frequency

Seezoo help.

dateFormat

What class should the dates be converted to?

.RECLASS

Should the conversion be reversible viareclass()?

FinCenter,recordIDs,title,documentation

SeetimeSeries help.

Details

A simple and reliable way to convert many different objects into a uniformformat for use withinR.

as.xts() can convert objects of the following classes into an xts object:object:timeSeries,ts,matrix,data.frame,andzoo.xtsible() safely checks whether an object can be converted toan xts object.

Additionalname = value pairs may be passed to the function to be added tothe new object. A specialprint.xts() method ensures the attributes arehidden from view, but will be available viaR's standardattr() function,as well as thextsAttributes() function.

When.RECLASS = TRUE, the returned xts object internally preserves allrelevant attribute/slot data from the inputx. This allows for temporaryconversion to xts in order to use zoo and xts compatible methods. Seereclass() for details.

Value

An S3 object of class xts.

Author(s)

Jeffrey A. Ryan

See Also

xts(),reclass(),zoo()

Examples

## Not run: # timeSerieslibrary(timeSeries)x <- timeSeries(1:10, 1:10)str(as.xts(x))str(reclass(as.xts(x)))str(try.xts(x))str(reclass(try.xts(x)))## End(Not run)

Compute x-Axis Tickmark Locations by Time

Description

Compute x-axis tickmarks likeaxTicks() in base but with respect totime. This function is written for internal use, and documented for thosewishing to use it for customized plots.

Usage

axTicksByTime(  x,  ticks.on = "auto",  k = 1,  labels = TRUE,  format.labels = TRUE,  ends = TRUE,  gt = 2,  lt = 30)

Arguments

x

An object indexed by time or a vector of times/dates.

ticks.on

Time unit for tick locations.

k

Frequency of tick locations.

labels

Should a labeled vector be returned?

format.labels

Either a logical value specifying whether labels shouldbe formatted, or a character string specifying the format to use.

ends

Should the ends be adjusted?

gt

Lower bound on number of tick locations.

lt

Upper bound on number of tick locations.

Details

The defaultticks.on = "auto" uses heuristics to compute sensible ticklocations. Use a combination ofticks.on andk to create tick locationsat specific intervals. For example,ticks.on = "days" andk = 7 willcreate tick marks every 7 days.

Whenformat.labels is a character string the possible values are the sameas those listed in the Details section ofstrptime().

Value

A numeric vector of index element locations where tick marks shouldbe drawn. These arelocations (e.g. 1, 2, 3, ...),not theindex timestamps.

If possible, the result will be named using formatted values from the indextimestamps. The names will be used for the tick mark labels.

Author(s)

Jeffrey A. Ryan

See Also

endpoints()

Examples

data(sample_matrix)axTicksByTime(as.xts(sample_matrix),'auto')axTicksByTime(as.xts(sample_matrix),'weeks')axTicksByTime(as.xts(sample_matrix),'months',7)

Concatenate Two or More xts Objects by Row

Description

Concatenate or bind by row two or more xts objects along a time-based index.All objects must have the same number of columns and be xts objects orcoercible to xts.

Usage

## S3 method for class 'xts'c(...)## S3 method for class 'xts'rbind(..., deparse.level = 1)

Arguments

...

Objects to bind by row.

deparse.level

Not implemented.

Details

Duplicate index values are supported. When one or more input has the sameindex value, the duplicated index values in the result are in the same orderthe objects are passed torbind(). See examples.

c() is an alias forrbind() for xts objects.

Seemerge.xts() for traditional merge operations.

Value

An xts object with one row per row for each object concatenated.

Note

rbind() is a '.Primitive' function inR, which means method dispatchoccurs at the C-level, and may not be consistent with normal S3 methoddispatch (seerbind() for details). Callrbind.xts() directly toavoid potential dispatch ambiguity.

Author(s)

Jeffrey A. Ryan

See Also

merge.xts()rbind()

Examples

x <- xts(1:10, Sys.Date()+1:10)str(x)merge(x,x)rbind(x,x)rbind(x[1:5],x[6:10])c(x,x)# this also works on non-unique index valuesx <- xts(rep(1,5), Sys.Date()+c(1,2,2,2,3))y <- xts(rep(2,3), Sys.Date()+c(1,2,3))# overlapping indexes are appendedrbind(x,y)rbind(y,x)

Extract/Replace Core Data of an xts Object

Description

Mechanism to extract and replace the core data of an xts object.

Usage

## S3 method for class 'xts'coredata(x, fmt = FALSE, ...)xcoredata(x, ...)xcoredata(x) <- value

Arguments

x

An xts object.

fmt

Should the rownames be formated usingtformat()? Alternativelya date/time string to be passed toformat(). See details.

...

Unused.

value

Non-core attributes to assign.

Details

Extract coredata of an xts object - removing all attributes exceptdim anddimnames and returning a matrix object with rownamesconverted from the index of the xts object.

The rownames of the result use the format specified bytformat(x) whenfmt = TRUE. Whenfmt is a character string to be passed toformat().Seestrptime() for valid format strings. Settingfmt = FALSE willreturn the row names by simply coercing the index class to a characterstring in the default manner.

xcoredata() is the complement tocoredata(). It returns all of theattributes normally removed bycoredata(). Its purpose, along with thethe replacement function⁠xcoredata<-⁠ is primarily for developers usingxts'try.xts() andreclass() functionality inside functionsso the functions can take any time series class as an input and return thesame time series class.

Value

Returns either a matrix object for coredata, or a list of namedattributes.

The replacement functions are called for their side-effects.

Author(s)

Jeffrey A. Ryan

See Also

coredata(),xtsAttributes()

Examples

data(sample_matrix)x <- as.xts(sample_matrix, myattr=100)coredata(x)xcoredata(x)

Dimnames of an xts Object

Description

Get or set dimnames of an xts object.

Usage

## S3 method for class 'xts'dimnames(x)## S3 replacement method for class 'xts'dimnames(x) <- value

Arguments

x

An xts object.

value

A two element list. See Details.

Details

For efficienty, xts objects do not have rownames (unlike zoo objects).Attempts to set rownames on an xts object will silently set them toNULL.This is done for internal compatibility reasons, as well as to provideconsistency in performance regardless of object use.

Value

A list or character string containing coerced row names and/oractual column names.

Attempts to set rownames on xts objects via rownames or dimnames willsilently fail.

Note

Unlike zoo, all xts objects have dimensions. xts objects cannot beplain vectors.

Author(s)

Jeffrey A. Ryan

See Also

xts()

Examples

x <- xts(1:10, Sys.Date()+1:10)dimnames(x)rownames(x)rownames(x) <- 1:10rownames(x)str(x)

Locate Endpoints by Time

Description

Extract index locations for an xts object that correspond to thelastobservation in each period specified byon andk.

Usage

endpoints(x, on = "months", k = 1)

Arguments

x

An xts object.

on

A character string specifying the period.

k

The number of periods each endpoint should cover.

Details

endpoints() returns a numeric vector that always begins with zero and endswith the number of observations inx.

Periods are always based on the distance from the UNIX epoch (midnight1970-01-01 UTC),not the first observation inx. See the examples.

Valid values for theon argument are: “us” (microseconds),“microseconds”, “ms” (milliseconds), “milliseconds”,“secs” (seconds), “seconds”, “mins” (minutes),“minutes”, “hours”, “days”, “weeks”,“months”, “quarters”, and “years”.

Value

A numeric vector of beginning with 0 and ending with the number ofof observations inx.

Author(s)

Jeffrey A. Ryan

Examples

data(sample_matrix)endpoints(sample_matrix)endpoints(sample_matrix, "weeks")### example of how periods are based on the UNIX epoch,### *not* the first observation of the data seriesx <- xts(1:38, yearmon(seq(2018 - 1/12, 2021, 1/12)))# endpoints for the end of every other yearep <- endpoints(x, "years", k = 2)# Dec-2017 is the end of the *first* year in the data. But when you start from# Jan-1970 and use every second year end as your endpoints, the endpoints are# always December of every odd year.x[ep, ]

Return First or Last n Elements of A Data Object

Description

Generic functions to return the first or last elements or rows of a vectoror two-dimensional data object.

Usage

first(x, ...)## Default S3 method:first(x, n = 1, keep = FALSE, ...)## S3 method for class 'xts'first(x, n = 1, keep = FALSE, ...)last(x, ...)## Default S3 method:last(x, n = 1, keep = FALSE, ...)## S3 method for class 'xts'last(x, n = 1, keep = FALSE, ...)

Arguments

x

An object.

...

Arguments passed to other methods.

n

Number of observations to return.

keep

Should removed values be kept as an attribute on the result?

Details

A more advanced subsetting is available for zoo objects with indexesinheriting from POSIXt or Date classes.

Quickly and easily extract the first or lastn observations of an object.Whenn is a number, these functions are similar tohead() andtail(), but only return thefirst orlast observation by default.

n can be a character string ifx is an xts object or coerceable to xts.It must be of the form ‘n period’, where 'n' is a numeric value(1 if not provided) describing the number of periods to return. Validperiods are: secs, seconds, mins, minutes, hours, days, weeks, months,quarters, and years.

The 'period' portion can be any frequency greater than or equal to thefrequency of the object's time index. For example,first(x, "2 months")will return the first 2 months of data even ifx is hourly frequency.Attempts to set 'period' to a frequency less than the object's frequencywill throw an error.

n may be positive or negative, whether it's a number or character string.Whenn is positive, the functions return the obvious result. For example,first(x, "1 month") returns the first month's data. Whenn is negative,all dataexcept first month's is returned.

Requesting more data than is inx will throw a warning and simply returnx.

Value

A subset of elements/rows of the original data.

Author(s)

Jeffrey A. Ryan

Examples

first(1:100)last(1:100)data(LakeHuron)first(LakeHuron,10)last(LakeHuron)x <- xts(1:100, Sys.Date()+1:100)first(x, 10)first(x, '1 day')first(x, '4 days')first(x, 'month')last(x, '2 months')last(x, '6 weeks')

Create a POSIXct Object

Description

Easily create of time stamps corresponding to the first or last observationin a specified time period.

Usage

firstof(year = 1970, month = 1, day = 1, hour = 0, min = 0, sec = 0, tz = "")lastof(  year = 1970,  month = 12,  day = 31,  hour = 23,  min = 59,  sec = 59,  subsec = 0.99999,  tz = "")

Arguments

year,month,day

Numeric values to specify a day.

hour,min,sec

Numeric vaues to specify time within a day.

tz

Timezone used for conversion.

subsec

Number of sub-seconds.

Details

This is a wrapper toISOdatetime() with defaults corresponding to thefirst or last possible time in a given period.

Value

An POSIXct object.

Author(s)

Jeffrey A. Ryan

See Also

ISOdatetime()

Examples

firstof(2000)firstof(2005,01,01)lastof(2007)lastof(2007,10)

Get and Replace the Class of an xts Index

Description

Functions to get and replace an xts object's index values and it'scomponents.

Usage

## S3 method for class 'xts'index(x, ...)## S3 replacement method for class 'xts'index(x) <- value## S3 replacement method for class 'xts'time(x) <- value## S3 method for class 'xts'time(x, ...).index(x, ...).index(x) <- value.indexsec(x).indexmin(x).indexhour(x).indexmday(x).indexmon(x).indexyear(x).indexwday(x).indexbday(x).indexyday(x).indexisdst(x).indexDate(x).indexday(x).indexweek(x).indexyweek(x)convertIndex(x, value)

Arguments

x

An xts object.

...

Arguments passed to other methods.

value

A new time index value.

Details

An xts object's index is stored internally as the number of seconds sinceUNIX epoch in the UTC timezone. The.index() and⁠.index<-⁠ functions getand replace the internal numeric value of the index, respectively. Thesefunctions are primarily for internal use, but are exported because they maybe useful for users.

The replacement method also updates thetclass() andtzone() of theindex to match the class and timezone of the new index, respectively. Theindex() method converts the internal numeric index to the class specifiedby the 'tclass' attribute and with the timezone specified by the 'tzone'attribute before returning the index values to the user.

The.indexXXX() functions below extract time components from the internaltime index. They return values like the values ofPOSIXlt components.

.indexsec

0 - 61: seconds of the minute (local time)

.indexmin

0 - 59: minutes of the hour (local time)

.indexhour

0 - 23: hours of the day (local time)

.indexDate

date as seconds since the epoch (UTCnot local time

.indexday

date as seconds since the epoch (UTCnot local time

.indexwday

0 - 6: day of the week (Sunday - Saturday, local time)

.indexmday

1 - 31: day of the month (local time)

.indexweek

weeks since the epoch (UTCnot local time

.indexmon

0 - 11: month of the year (local time)

.indexyear

years since 1900 (local time)

.indexyday

0 - 365: day of the year (local time, 365 only in leap years)

.indexisdst

1, 0, -1: Daylight Saving Time flag. Positive ifDaylight Saving Time is in effect, zero if not, negative if unknown.

Changes in timezone, index class, and index format internal structure, byxts version:

Version 0.12.0:

The.indexTZ,.indexCLASS and.indexFORMATattributes are no longer stored on xts objects, only on the index itself.

TheindexTZ(),indexClass(), andindexFormat() functions (andtheir respective replacement methods) are deprecated in favor of theirrespectivetzone(),tclass(), andtformat() versions. The previousversions throw a warning that they're deprecated, but they will continueto work. They will never be removed or throw an error. Ever.

The new versions are careful to look for the old attributes on the xtsobject, in case they're ever called on an xts object that was created priorto the attributes being added to the index itself.

You can setoptions(xts.warn.index.missing.tzone = TRUE) andoptions(xts.warn.index.missing.tclass = TRUE) to identify xts objectsthat do not have a 'tzone' or 'tclass' attribute on the index, even ifthere is a 'tzone' or 'tclass' attribute on the xts object itself. Thewarnings will be thrown when the object is printed.Usex <- as.xts(x) to update these objects to the new structure.

Version 0.9.8:

The index timezone is now set to "UTC" for time classesthat do not have any intra-day component (e.g. days, months, quarters).Previously the timezone was blank, which meant "local time" as determined byR and the OS.

Version 0.9.2:

There are new get/set methods for the timezone, indexclass, and index format attributes:tzone() and,⁠tzone<-⁠,tclass()and⁠tclass<-⁠, andtformat() and⁠tformat<-⁠. These new functions arealiases to theirindexTZ(),indexClass(), andindexFormat()counterparts.

Version 0.7.5:

The timezone, index class, and index format were addedas attributes to the index itself, as 'tzone', 'tclass', and 'tformat',respectively. This is in order to remove those three attributes from the xtsobject, so they're only on the index itself.

TheindexTZ(),indexClass(), andindexFormat() functions (and theirrespective replacement methods) will continue to work as in priorxtsversions. The attributes on the index take priority over their respectivecounterparts that may be on the xts object.

Versions 0.6.4 and prior:

Objects track their timezone and index classin their '.indexTZ' and '.indexCLASS' attributes, respectively.

Author(s)

Jeffrey A. Ryan

See Also

tformat() describes how the index values are formatted whenprinted,tclass() documents howxts handles the index class, andtzone() has more information about index timezone settings.

Examples

x <- timeBasedSeq('2010-01-01/2010-01-01 12:00/H')x <- xts(seq_along(x), x)# the index values, converted to 'tclass' (POSIXct in this case)index(x)class(index(x))  # POSIXcttclass(x)        # POSIXct# the internal numeric index.index(x)# add 1 hour (3600 seconds) to the numeric index.index(x) <- index(x) + 3600index(x)y <- timeBasedSeq('2010-01-01/2010-01-02 12:00')y <- xts(seq_along(y), y)# Select all observations in the first 6 and last 3 minutes of the# 8th and 15th hours on each dayy[.indexhour(y) %in% c(8, 15) & .indexmin(y) %in% c(0:5, 57:59)]i <- 0:60000focal_date <- as.numeric(as.POSIXct("2018-02-01", tz = "UTC"))y <- .xts(i, c(focal_date + i * 15), tz = "UTC", dimnames = list(NULL, "value"))# Select all observations for the first minute of each houry[.indexmin(y) == 0]# Select all observations on Mondaymon <- y[.indexwday(y) == 1]head(mon)tail(mon)unique(weekdays(index(mon))) # check# Disjoint time of day selections# Select all observations between 08:30 and 08:59:59.9999  or between 12:00 and 12:14:59.99999:y[.indexhour(y) == 8 & .indexmin(y) >= 30 | .indexhour(y) == 12 & .indexmin(x) %in% 0:14]### Compound selections# Select all observations for Wednesdays or Fridays between 9am and 4pm (exclusive of 4pm):y[.indexwday(y) %in% c(3, 5) & (.indexhour(y) %in%  c(9:15))]# Select all observations on Monday between 8:59:45 and 09:04:30:y[.indexwday(y) == 1 & (.indexhour(y) == 8 & .indexmin(y) == 59 & .indexsec(y) >= 45 |                        .indexhour(y) == 9 &                        (.indexmin(y) <  4 | .indexmin(y) ==  4 & .indexsec(y) <= 30))]i <- 0:30000u <- .xts(i, c(focal_date + i * 1800), tz = "UTC", dimnames = list(NULL, "value"))# Select all observations for January or February:u[.indexmon(u) %in% c(0, 1)]# Select all data for the 28th to 31st of each month, excluding any Fridays:u[.indexmday(u) %in% 28:31 & .indexwday(u) != 5]# Subset by week since originunique(.indexweek(u))origin <- xts(1, as.POSIXct("1970-01-01"))unique(.indexweek(origin))# Select all observations in weeks 2515 to 2517.u2 <- u[.indexweek(u) %in% 2515:2517]head(u2); tail(u2)# Select all observations after 12pm for day 50 and 51 in each yearu[.indexyday(u) %in% 50:51 & .indexhour(u) >= 12]

Get or Replace the Timezone of an xts Object's Index

Description

Generic functions to get or replace the timezone of an xts object's index.

Usage

indexTZ(x, ...)tzone(x, ...)indexTZ(x) <- valuetzone(x) <- value

Arguments

x

An xts object.

...

Arguments passed to other methods.

value

A valid timezone value (seeOlsonNames()).

Details

Internally, an xts object's index is anumeric value corresponding toseconds since the epoch in the UTC timezone. When an xts object is created,all time index values are converted internally toPOSIXct()(which is also in seconds since the UNIX epoch), using the underlying OSconventions and theTZ environment variable. Thexts() functionmanages timezone information as transparently as possible.

The⁠tzone<-⁠ functiondoes not change the internal index values(i.e. the index will remain the same time in the UTC timezone).

Value

A one element named vector containing the timezone of the object'sindex.

Note

BothindexTZ() and⁠indexTZ<-⁠ are deprecated in favor oftzone() and⁠tzone<-⁠, respectively.

Problems may arise when an object that had been created under one timezoneare used in a session using another timezone. This isn't usually a issue,but when it is a warning is given upon printing or subsetting. This warningmay be suppressed by settingoptions(xts_check_TZ = FALSE).

Author(s)

Jeffrey A. Ryan

See Also

index() has more information on the xts index,tformat()describes how the index values are formatted when printed, andtclass()provides details howxts handles the class of the index.

Examples

# Date indexes always have a "UTC" timezonex <- xts(1, Sys.Date())tzone(x)str(x)print(x)# The default 'tzone' is blank -- your machine's local timezone,# determined by the 'TZ' environment variable.x <- xts(1, Sys.time())tzone(x)str(x)# now set 'tzone' to different valuestzone(x) <- "UTC"str(x)tzone(x) <- "America/Chicago"str(x)y <- timeBasedSeq('2010-01-01/2010-01-03 12:00/H')y <- xts(seq_along(y), y, tzone = "America/New_York")# Changing the tzone does not change the internal index values, but it# does change how the index is printed!head(y)head(.index(y))tzone(y) <- "Europe/London"head(y)          # the index prints with hours, buthead(.index(y))  # the internal index is not changed!

Force Time Values To Be Unique

Description

A generic function to force sorted time vectors to be unique. Useful forhigh-frequency time-series where original time-stamps may have identicalvalues. For the case of xts objects, the defaulteps is set to tenmicroseconds. In practice this advances each subsequent identical time byeps over the previous (possibly also advanced) value.

Usage

is.index.unique(x)is.time.unique(x)make.index.unique(x, eps = 1e-06, drop = FALSE, fromLast = FALSE, ...)make.time.unique(x, eps = 1e-06, drop = FALSE, fromLast = FALSE, ...)

Arguments

x

An xts object, or POSIXct vector.

eps

A value to add to force uniqueness.

drop

Should duplicates be dropped instead of adjusted byeps?

fromLast

Whendrop = TRUE,fromLast controls which duplicatedtimes are dropped. WhenfromLast = FALSE, the earliest observation withan identical timestamp is kept and subsequent observations are dropped.

...

Unused.

Details

The returned time-series object will have new time-stamps so thatisOrdered(.index(x)) evaluates toTRUE.

Value

A modified version ofx with unique timestamps.

Note

Incoming values must be pre-sorted, and no check is done to make surethat this is the case. ‘integer’ index value will be coerced to‘double’ whendrop = FALSE.

Author(s)

Jeffrey A. Ryan

See Also

align.time()

Examples

ds <- options(digits.secs=6) # so we can see the changex <- xts(1:10, as.POSIXct("2011-01-21") + c(1,1,1,2:8)/1e3)xmake.index.unique(x)options(ds)

Check if Class is Time-Based

Description

Used to verify that the object is one of the known time-based classes in R.Current time-based objects supported areDate,POSIXct,chron,yearmon,yearqtr, andtimeDate.

Usage

is.timeBased(x)timeBased(x)

Arguments

x

Object to test.

Value

A logical scalar.

Author(s)

Jeffrey A. Ryan

Examples

timeBased(Sys.time())timeBased(Sys.Date())timeBased(200701)

Check If A Vector Is Ordered

Description

Check if a vector is strictly increasing, strictly decreasing, notdecreasing, or not increasing.

Usage

isOrdered(x, increasing = TRUE, strictly = TRUE)

Arguments

x

A numeric vector.

increasing

Test for increasing (TRUE) or decreasing (FALSE) values?

strictly

WhenTRUE, vectors with duplicate values arenotconsidered ordered.

Details

Designed for internal use withxts, this provides highly optimizedtests for ordering.

Value

A logical scalar indicating whether or notx is ordered.

Author(s)

Jeffrey A. Ryan

See Also

is.unsorted()

Examples

# strictly increasingisOrdered(1:10, increasing=TRUE)isOrdered(1:10, increasing=FALSE)isOrdered(c(1,1:10), increasing=TRUE)isOrdered(c(1,1:10), increasing=TRUE, strictly=FALSE)# decreasingisOrdered(10:1, increasing=TRUE)isOrdered(10:1, increasing=FALSE)

Lags and Differences of xts Objects

Description

Methods for computing lags and differences on xts objects. This providessimilar functionality as thezoo counterparts, but with some differentdefaults.

Usage

## S3 method for class 'xts'lag(x, k = 1, na.pad = TRUE, ...)## S3 method for class 'xts'diff(  x,  lag = 1,  differences = 1,  arithmetic = TRUE,  log = FALSE,  na.pad = TRUE,  ...)

Arguments

x

An xts object.

k

Number of periods to shift.

na.pad

ShouldNA be added so the result has the same number ofobservations asx?

...

Additional arguments.

lag

Period to difference over.

differences

Order of differencing.

arithmetic

Should arithmetic or geometric differencing be used?

log

Should (geometric) log differences be returned?

Details

The primary motivation for these methods was to take advantage of a fasterC-level implementation. Another motivation was to makelag() behave usingstandard sign fork. Bothzoo's lag() method andlag.default() require anegative value fork in order to shift a series backward. Sok = 1,shifts the seriesforward one observation. This is especially confusingbecausek = 1 is the default for those functions. Whenx is an xtsobject,lag(x, 1) returns an object where the value at time 't' is thevalue at time 't-1' in the original object.

Another difference is thatna.pad = TRUE by default, to better reflect thetransformation visually and for functions the require positional alignmentof data.

Setoptions(xts.compat.zoo.lag = TRUE) to use makelag.xts() consistentwithlag.zoo() by reversing the sign ofk and settingna.pad = FALSE.

Value

An xts object with the desired lag and/or differencing.

Author(s)

Jeffrey A. Ryan

References

https://en.wikipedia.org/wiki/Lag

Examples

x <- xts(1:10, Sys.Date()+1:10)lag(x)    # currently using xts-style positive k lag(x, k=2)lag(x, k=-1, na.pad=FALSE) # matches lag.zoo(x, k=1)diff(x)diff(x, lag=1)diff(x, diff=2)diff(diff(x))

Merge xts Objects

Description

Perform merge operations on xts objects by time index.

Usage

## S3 method for class 'xts'merge(  ...,  all = TRUE,  fill = NA,  suffixes = NULL,  join = "outer",  retside = TRUE,  retclass = "xts",  tzone = NULL,  drop = NULL,  check.names = NULL)## S3 method for class 'xts'cbind(..., all = TRUE, fill = NA, suffixes = NULL)

Arguments

...

One or more xts objects, or objects coercible to class xts.

all

A logical vector indicating merge type.

fill

Values to be used for missing elements.

suffixes

Suffix to be added to merged column names.

join

Type of database join. One of 'outer', 'inner', 'left', or 'right'.

retside

Which side of the merged object should be returned (2-case only)?

retclass

Either a logical value indicating whether the result shouldhave a 'class' attribute, or the name of the desired class for the result.

tzone

Time zone to use for the merged result.

drop

Not currently used.

check.names

Usemake.names() to ensure column names are vaildRobject names?

Details

This xts method is compatible withzoo's merge() method but implemented almostentirely in C-level code for efficiency.

The function can perform all common database join operations along the timeindex by setting 'join' to one of the values below. Note that 'left' and'right' are only implemented for two objects.

The above join types can also be accomplished by setting 'all' to one of thevalues below.

The result will have the timezone of the leftmost argument if available. Usethe 'tzone' argument to override the default behavior.

Whenretclass = NULL the joined objects will be split and reassignedsilently back to the original environment they are called from. This is forbackward compatibility with zoo, but unused by xts. Whenretclass = FALSEthe object will be stripped of its class attribute. This is for internal use.

See the examples in order to join using an 'all' argument that is the samearguments to join, like you can do withmerge.zoo().

Value

A new xts object containing the appropriate elements of theobjects passed in to be merged.

Note

This is a highly optimized merge, specifically designed for ordereddata. The only supported merging is based on the underlying time index.

Author(s)

Jeffrey A. Ryan

References

Merge Join Discussion:https://learn.microsoft.com/en-us/archive/blogs/craigfr/merge-join

Examples

(x <- xts(4:10, Sys.Date()+4:10))(y <- xts(1:6, Sys.Date()+1:6))merge(x,y)merge(x,y, join='inner')merge(x,y, join='left')merge(x,y, join='right')merge.zoo(zoo(x),zoo(y),zoo(x), all=c(TRUE, FALSE, TRUE))merge(merge(x,x),y,join='left')[,c(1,3,2)]# zero-width objects (only index values) can be usedxi <- xts( , index(x))merge(y, xi)

Last Observation Carried Forward

Description

xts method replaceNA with most recent non-NA

Usage

## S3 method for class 'xts'na.locf(object, na.rm = FALSE, fromLast = FALSE, maxgap = Inf, ...)

Arguments

object

An xts object.

na.rm

Logical indicating whether leading/trailingNA should beremoved. The default isFALSE unlike the zoo method.

fromLast

Logical indicating whether observations should be carriedbackward rather than forward. Default isFALSE.

maxgap

Consecutive runs of observations more than 'maxgap' willremainNA. Seena.locf() for details.

...

Unused.

Details

This is thexts method for the S3 genericna.locf(). The primarydifference to note is that after theNA fill action is carried out, thedefault it to leave trailing or leadingNA's in place. This is differentthanzoo behavior.

Value

An object where eachNA inobject is replaced by the most recentnon-NA prior to it. Seena.locf() for details.

Author(s)

Jeffrey A. Ryan

See Also

na.locf()

Examples

x <- xts(1:10, Sys.Date()+1:10)x[c(1,2,5,9,10)] <- NAxna.locf(x)na.locf(x, fromLast=TRUE)na.locf(x, na.rm=TRUE, fromLast=TRUE)

Number of Periods in Data

Description

Calculate the number of specified periods in a given time series like dataobject.

Usage

nseconds(x)nminutes(x)nhours(x)ndays(x)nweeks(x)nmonths(x)nquarters(x)nyears(x)

Arguments

x

A time-based object.

Details

Essentially a wrapper toendpoints() with the appropriate periodspecified. The result is the number of endpoints found.

As a compromise between simplicity and accuracy, the results will alwaysround up to the nearest complete period. Subtract 1 from the result toget the completed periods.

For finer grain detail one should call the higher frequency functions.

An alternative summary can be found withperiodicity(x) andunclass(periodicity(x)).

Value

The number of respective periods inx.

Author(s)

Jeffrey A. Ryan

See Also

endpoints()

Examples

## Not run: getSymbols("QQQQ")ndays(QQQQ)nweeks(QQQQ)## End(Not run)

Apply Function Over Specified Interval

Description

Apply a specified function to data over intervals specified byINDEX. Theintervals are defined as the observations fromINDEX[k]+1 toINDEX[k+1],fork = 1:(length(INDEX)-1).

Usage

period.apply(x, INDEX, FUN, ...)

Arguments

x

The data thatFUN will be applied to.

INDEX

A numeric vector of index breakpoint locations. The vectorshould begin with 0 and end withnrow(x).

FUN

A function to apply to each interval inx.

...

Additional arguments forFUN.

Details

Similar to the rest of the apply family,period.apply() calculates thespecified function's value over a subset of data. The primary difference isthatperiod.apply() applies the function to non-overlapping intervals of avector or matrix.

Useful for applying functions over an entire data object by anynon-overlapping intervals. For example, whenINDEX is the result of acall toendpoints().

period.apply() checks thatINDEX is sorted, unique, starts with 0, andends withnrow(x). All those conditions are true of vectors returned byendpoints().

Value

An object withlength(INDEX) - 1 observations, assumingINDEXstarts with 0 and ends withnrow(x).

Note

WhenFUN = mean the results will contain one column for everycolumn in the input, which is different from other math functions (e.g.median,sum,prod,sd, etc.).

FUN = mean works by column because the default methodstats::meanpreviously worked by column for matrices and data.frames. R Core changed thebehavior ofmean to always return one column in order to be consistentwith the other math functions. This broke somexts dependencies andmean.xts() was created to maintain the original behavior.

UsingFUN = mean will print a message that describes this inconsistency.To avoid the message and confusion, useFUN = colMeans to calculate meansby column and useFUN = function(x) mean to calculate one mean for all thedata. Setoptions(xts.message.period.apply.mean = FALSE) to suppress thismessage.

Author(s)

Jeffrey A. Ryan, Joshua M. Ulrich

See Also

endpoints()apply.monthly()

Examples

zoo.data <- zoo(rnorm(31)+10,as.Date(13514:13744,origin="1970-01-01"))ep <- endpoints(zoo.data,'weeks')period.apply(zoo.data, INDEX=ep, FUN=function(x) colMeans(x))period.apply(zoo.data, INDEX=ep, FUN=colMeans)                  #sameperiod.apply(letters,c(0,5,7,26), paste0)

Optimized Calculations By Period

Description

Calculate a sum, product, minimum, or maximum for each non-overlappingperiod specified byINDEX.

Usage

period.sum(x, INDEX)period.prod(x, INDEX)period.max(x, INDEX)period.min(x, INDEX)

Arguments

x

A univariate data object.

INDEX

A numeric vector of endpoints for each period.

Details

These functions are similar to callingperiod.apply() with the sameendpoints and function. There may be slight differences in the results dueto numerical accuracy.

For xts-coercible objects, an appropriateINDEX can be created by a calltoendpoints().

Value

An xts or zoo object containing the sum, product, minimum, ormaximum for each endpoint inINDEX.

Author(s)

Jeffrey A. Ryan

See Also

endpoints(),period.apply()

Examples

x <- c(1, 1, 4, 2, 2, 6, 7, 8, -1, 20)i <- c(0, 3, 5, 8, 10)period.sum(x, i)period.prod(x, i)period.min(x, i)period.max(x, i)data(sample_matrix)y <- sample_matrix[, 1]ep <- endpoints(sample_matrix)period.sum(y, ep)period.sum(as.xts(y), ep)period.prod(y, ep)period.prod(as.xts(y), ep)period.min(y, ep)period.min(as.xts(y), ep)period.max(y, ep)period.max(as.xts(y), ep)

Approximate Series Periodicity

Description

Estimate the periodicity of a time-series-like object by calculating themedian time between observations in days.

Usage

periodicity(x, ...)

Arguments

x

A time-series-like object.

...

Unused.

Details

A simple wrapper to quickly estimate the periodicity of a given data.Returning an object of typeperiodicity.

This calculates the median time difference between observations as adifftime object, the numerical difference, the units of measurement, and thederived scale of the data as a string.

The time index currently must be of either a 'Date' or 'POSIXct' class, oror coercible to one of them.

The 'scale' component of the result is an estimate of the periodicity of thedata in common terms - e.g. 7 day daily data is best described as 'weekly',and would be returned as such.

Value

A 'periodicity' object with the following elements:

Possiblescale values are: ‘minute’, ‘hourly’, ‘daily’,‘weekly’, ‘monthly’, ‘quarterly’, and ‘yearly’.

Note

This function only attempts to be agood estimate for the underlyingperiodicity. If the series is too short, or has highly irregular periodicity,the return values will not be accurate. That said, it is quite robust andused internally withinxts.

Author(s)

Jeffrey A. Ryan

See Also

difftime()

Examples

zoo.ts <- zoo(rnorm(231),as.Date(13514:13744,origin="1970-01-01"))periodicity(zoo.ts)

Plotting xts Objects

Description

Plotting for xts objects.

Usage

## S3 method for class 'xts'plot(  x,  y = NULL,  ...,  subset = "",  panels = NULL,  multi.panel = FALSE,  col = 1:8,  up.col = NULL,  dn.col = NULL,  bg = "#FFFFFF",  type = "l",  lty = 1,  lwd = 2,  lend = 1,  main = deparse(substitute(x)),  main.timespan = TRUE,  observation.based = FALSE,  log = FALSE,  ylim = NULL,  yaxis.same = TRUE,  yaxis.left = TRUE,  yaxis.right = TRUE,  yaxis.ticks = 5,  major.ticks = "auto",  minor.ticks = NULL,  grid.ticks.on = "auto",  grid.ticks.lwd = 1,  grid.ticks.lty = 1,  grid.col = "darkgray",  labels.col = "#333333",  format.labels = TRUE,  grid2 = "#F5F5F5",  legend.loc = NULL,  extend.xaxis = FALSE)## S3 method for class 'xts'lines(  x,  ...,  main = "",  on = 0,  col = NULL,  type = "l",  lty = 1,  lwd = 1,  pch = 1)## S3 method for class 'xts'points(x, ..., main = "", on = 0, col = NULL, pch = 1)

Arguments

x

A xts object.

y

Not used, alwaysNULL.

...

Any passthrough arguments forlines() andpoints().

subset

An ISO8601-style subset string.

panels

Character vector of expressions to plot as panels.

multi.panel

EitherTRUE,FALSE, or an integer less than or equalto the number of columns in the data set. WhenTRUE, each column of thedata is plotted in a separate panel. When an integer 'n', the data will beplotted in groups of 'n' columns per panel and each group will be plottedin a separate panel.

col

Color palette to use.

up.col

Color for positive bars whentype = "h".

dn.col

Color for negative bars whentype = "h".

bg

Background color of plotting area, same as inpar().

type

The type of plot to be drawn, same as inplot().

lty

Set the line type, same as inpar().

lwd

Set the line width, same as inpar().

lend

Set the line end style, same as inpar().

main

Main plot title.

main.timespan

Should the timespan of the series be shown in the topright corner of the plot?

observation.based

WhenTRUE, all the observations are equally spacedalong the x-axis. WhenFALSE (the default) the observations on the x-axisare spaced based on the time index of the data.

log

Should the y-axis be in log scale? DefaultFALSE.

ylim

The range of the y axis.

yaxis.same

Should 'ylim' be the same for every panel? DefaultTRUE.

yaxis.left

Add y-axis labels to the left side of the plot?

yaxis.right

Add y-axis labels to the right side of the plot?

yaxis.ticks

Desired number of y-axis grid lines. The actual number ofgrid lines is determined by then argument topretty().

major.ticks

Period specifying locations for major tick marks and labelson the x-axis. See Details for possible values.

minor.ticks

Period specifying locations for minor tick marks on thex-axis. WhenNULL, minor ticks are not drawn. See details for possiblevalues.

grid.ticks.on

Period specifying locations for vertical grid lines.See details for possible values.

grid.ticks.lwd

Line width of the grid.

grid.ticks.lty

Line type of the grid.

grid.col

Color of the grid.

labels.col

Color of the axis labels.

format.labels

Label format to draw lower frequency x-axis ticks andlabels passed toaxTicksByTime()

grid2

Color for secondary x-axis grid.

legend.loc

Places a legend into one of nine locations on the chart:bottomright, bottom, bottomleft, left, topleft, top, topright, right, orcenter. DefaultNULL does not draw a legend.

extend.xaxis

WhenTRUE, extend the x-axis before and/or after theplot's existing time index range, so all of of the time index values ofthe new series are included in the plot. DefaultFALSE.

on

Panel number to draw on. A new panel will be drawn ifon = NA.The default,on = 0, will add to the active panel. The active panel isdefined as the panel on which the most recent action was performed. Notethat only the first element ofon is checked for the default behavior toadd to the last active panel.

pch

the plotting character to use, same as in 'par'

Details

Possible values for argumentsmajor.ticks,minor.ticks, andgrid.ticks.on include ‘auto’, ‘minute’, ‘hours’,‘days’, ‘weeks’, ‘months’, ‘quarters’, and‘years’. The default is ‘auto’, which attempts to determinesensible locations from the periodicity and locations of observations. Theother values are based on the possible values for theticks.onargument ofaxTicksByTime().

Author(s)

Ross Bennett

References

based onchart_Series() inquantmodwritten by Jeffrey A. Ryan

See Also

addSeries(),addPanel()

Examples

## Not run: data(sample_matrix)sample.xts <- as.xts(sample_matrix)# plot the Closeplot(sample.xts[,"Close"])# plot a subset of the dataplot(sample.xts[,"Close"], subset = "2007-04-01/2007-06-31")# function to compute simple returnssimple.ret <- function(x, col.name){  x[,col.name] / lag(x[,col.name]) - 1}# plot the close and add a panel with the simple returnsplot(sample.xts[,"Close"])R <- simple.ret(sample.xts, "Close")lines(R, type = "h", on = NA)# add the 50 period simple moving average to panel 1 of the plotlibrary(TTR)lines(SMA(sample.xts[,"Close"], n = 50), on = 1, col = "blue")# add month end points to the chartpoints(sample.xts[endpoints(sample.xts[,"Close"], on = "months"), "Close"],        col = "red", pch = 17, on = 1)# add legend to panel 1addLegend("topright", on = 1,           legend.names = c("Close", "SMA(50)"),           lty = c(1, 1), lwd = c(2, 1),          col = c("black", "blue", "red"))## End(Not run)

Print An xts Time-Series Object

Description

Method for printing an extensible time-series object.

Usage

## S3 method for class 'xts'print(x, fmt, ..., show.rows = 10, max.rows = 100)

Arguments

x

An xts object.

fmt

Passed tocoredata() to format the time index.

...

Arguments passed to other methods.

show.rows

The number of first and last rows to print if the number ofrows is truncated (default 10, orgetOption("xts.print.show.rows")).

max.rows

The output will contain at mostmax.rows rows before beingtruncated (default 100, orgetOption("xts.print.max.rows")).

Value

Returnsx invisibly.

Author(s)

Joshua M. Ulrich

Examples

data(sample_matrix)sample.xts <- as.xts(sample_matrix)# output is truncated and shows first and last 10 observationsprint(sample.xts)# show the first and last 5 observationsprint(sample.xts, show.rows = 5)

Sample Data Matrix For xts Example and Unit Testing

Description

Simulated 180 observations on 4 variables.

Usage

data(sample_matrix)

Format

The format is:  num [1:180, 1:4] 50.0 50.2 50.4 50.4 50.2 ...  - attr(*, "dimnames")=List of 2    ..$ : chr [1:180] "2007-01-02" "2007-01-03" "2007-01-04" "2007-01-05" ...    ..$ : chr [1:4] "Open" "High" "Low" "Close"

Examples

data(sample_matrix)

Divide into Groups by Time

Description

Creates a list of xts objects split along time periods.

Usage

## S3 method for class 'xts'split(x, f = "months", drop = FALSE, k = 1, ...)

Arguments

x

An xts object.

f

A character vector describing the period to split by.

drop

Ignored bysplit.xts().

k

Number of periods to aggregate into each split. See details.

...

Further arguments passed to other methods.

Details

A quick way to break up a large xts object by standard time periods; e.g.'months', 'quarters', etc.

endpoints() is used to find the start and end of each period (ork-periods). See that function for valid arguments.

The inputs are passed tosplit.zoo() whenf is not a character vector.

Value

A list of xts objects.

Note

aggregate.zoo() is more flexible, though notas fast for xts objects.

Author(s)

Jeffrey A. Ryan

See Also

endpoints(),split.zoo(),aggregate.zoo()

Examples

data(sample_matrix)x <- as.xts(sample_matrix)split(x)split(x, f="weeks")split(x, f="weeks", k=4)

Get or Replace the Class of an xts Object's Index

Description

Generic functions to get or replace the class of an xts object's index.

Usage

tclass(x, ...)## Default S3 method:tclass(x, ...)## S3 method for class 'xts'tclass(x, ...)tclass(x) <- value## Default S3 replacement method:tclass(x) <- valueindexClass(x)indexClass(x) <- value## S3 replacement method for class 'xts'tclass(x) <- value

Arguments

x

An xts object.

...

Arguments passed to other methods.

value

The new index class (see Details for valid values).

Details

Internally, an xts object's index is anumeric value corresponding toseconds since the epoch in the UTC timezone. The index class is stored asthetclass attribute on the internal index. This is used to convertthe internal index values to the desired class when theindexfunction is called.

Thetclass function retrieves the class of the internal index, andthe⁠tclass<-⁠ function sets it. The specified value for⁠tclass<-⁠ must be one of the following character strings:"Date","POSIXct","chron","yearmon","yearqtr", or"timeDate".

Value

A vector containing the class of the object's index.

Note

BothindexClass and⁠indexClass<-⁠ are deprecated in favoroftclass and⁠tclass<-⁠, respectively.

Replacing thetclass canpotentially change the values of the internalindex. For example, changing the 'tclass' from POSIXct to Date willtruncate the POSIXct value and convert the timezone to UTC (since the Dateclass doesn't have a timezone). See the examples.

Author(s)

Jeffrey A. Ryan

See Also

index() has more information on the xts index,tformat()details how the index values are formatted when printed, andtzone()has more information about the index timezone settings.

The following help pages describe the characteristics of the valid indexclasses:POSIXct(),Date(),chron(),yearmon(),yearqtr(),timeDate()

Examples

x <- timeBasedSeq('2010-01-01/2010-01-02 12:00')x <- xts(seq_along(x), x)y <- timeBasedSeq('2010-01-01/2010-01-03 12:00/H')y <- xts(seq_along(y), y, tzone = "America/New_York")# Changing the tclass *changes* the internal index valueshead(y)          # the index has timeshead(.index(y))tclass(y) <- "Date"head(y)          # the index prints as a Datehead(.index(y))  # the internal index is truncated

Get or Replace the Format of an xts Object's Index

Description

Generic functions to get or replace the format that determines how an xtsobject's index is printed.

Usage

tformat(x, ...)tformat(x) <- valueindexFormat(x)indexFormat(x) <- value

Arguments

x

An xts object.

...

Arguments passed to other methods.

value

New index format string (seestrptime() details for validvalues).

Details

Valid values for thevalue argument are the same as specified in theDetails section ofstrptime().

An xts object'stformat isNULL by default, so the index will bebe formatted according to itstclass() (e.g. Date, POSIXct, timeDate,yearmon, etc.).

Thetformat only changes how the index isprinted and how the row namesare formatted when xts objects are converted to other classes (e.g. matrixor data.frame). It does not affect the internal index in any way.

Value

A vector containing the format for the object's index.

Note

BothindexFormat() and⁠indexFormat<-⁠ are deprecated infavor oftformat() and⁠tformat<-⁠, respectively.

Author(s)

Jeffrey A. Ryan

See Also

index() has more information on the xts index,tclass()details howxts handles the class of the index,tzone() has moreinformation about the index timezone settings.

Examples

x <- timeBasedSeq('2010-01-01/2010-01-02 12:00')x <- xts(seq_along(x), x)# set a custom index formathead(x)tformat(x) <- "%Y-%b-%d %H:%M:%OS3"head(x)

Create a Sequence or Range of Times

Description

A function to create a vector of time-based objects suitable for indexing anxts object, given a string conforming to the ISO-8601 time and date standardfor range-based specification. The resulting series can be of any classsupported by xts, including POSIXct, Date, chron, timeDate, yearmon, andyearqtr.

Usage

timeBasedRange(x, ...)timeBasedSeq(x, retclass = NULL, length.out = NULL)

Arguments

x

An ISO-8601 time-date range string.

...

Unused.

retclass

The return class desired.

length.out

Passed toseq() internally.

Details

timeBasedRange() creates a one or two element numeric vector representingthe start and end number of seconds since epoch (1970-01-01). For internaluse.

timeBasedSeq() creates sequences of time-based observations using stringsformatted according to the ISO-8601 specification. The general format isfrom/to/by orfrom::to::by, whereto andby are optional when the'length.out' argument is specified.

Thefrom andto elements of the string must be left-specified withrespect to the standardCCYYMMDD HHMMSS form. All dates/times specifiedwill be set to either the earliest point (from) or the latest (to), to thegiven the level of specificity. For example, ‘1999’ in thefromfield would set the start to the beginning of 1999. ‘1999’ in theto field would set the end to the end of 1999.

The amount of resolution in the result is determined by the resolution ofthefrom andto component, unless the optionalby component isspecified.

For example,timeBasedSeq("1999/2008") returns a vector of Dates forJanuary 1st of each year.timeBasedSeq("199501/1996") returns a yearmonvector of 24 months in 1995 and 1996. AndtimeBasedSeq("19950101/1996")creates a Date vector for all the days in those two years.

The optionalby field (the third delimited element to the string), willthe resolution heuristic described above and will use the specifiedbyresolution. The possible values forby are: 'Y' (years), 'm' (months),'d' (days), 'H' (hours), 'M' (minutes), 'S' (seconds). Sub-secondresolutions are not supported.

Value

timeBasedSeq() returns a vector of time-based observations.timeBasedRange() returns a one or two element numeric vector representingthe start and end number of seconds since epoch (1970-01-01).

Whenretclass = NULL, the result oftimeBasedSeq() is a named listcontaining elements "from", "to", "by" and "length.out".

Author(s)

Jeffrey A. Ryan

References

International Organization for Standardization: ISO 8601https://www.iso.org

See Also

timeBased(),xts()

Examples

timeBasedSeq('1999/2008')timeBasedSeq('199901/2008')timeBasedSeq('199901/2008/d')timeBasedSeq('20080101 0830',length=100) # 100 minutestimeBasedSeq('20080101 083000',length=100) # 100 seconds

Convert time series data to an OHLC series

Description

Convert an OHLC or univariate object to a specified periodicity lower thanthe given data object. For example, convert a daily series to a monthlyseries, or a monthly series to a yearly one, or a one minute series to anhourly series.

Usage

to.period(  x,  period = "months",  k = 1,  indexAt = NULL,  name = NULL,  OHLC = TRUE,  ...)to.minutes(x, k, name, ...)to.minutes3(x, name, ...)to.minutes5(x, name, ...)to.minutes10(x, name, ...)to.minutes15(x, name, ...)to.minutes30(x, name, ...)to.hourly(x, name, ...)to.daily(x, drop.time = TRUE, name, ...)to.weekly(x, drop.time = TRUE, name, ...)to.monthly(x, indexAt = "yearmon", drop.time = TRUE, name, ...)to.quarterly(x, indexAt = "yearqtr", drop.time = TRUE, name, ...)to.yearly(x, drop.time = TRUE, name, ...)

Arguments

x

A univariate or OHLC type time-series object.

period

Period to convert to. See details.

k

Number of sub periods to aggregate on (only for minutes andseconds).

indexAt

Convert final index to new class or date. See details.

name

Override column names?

OHLC

Should an OHLC object be returned? (onlyOHLC = TRUEcurrently supported)

...

Additional arguments.

drop.time

Remove time component of POSIX datestamp (if any)?

Details

The result will contain the open and close for the given period, as well asthe maximum and minimum over the new period, reflected in the new high andlow, respectively. Aggregate volume will also be calculated if applicable.

An easy and reliable way to convert one periodicity of data into any newperiodicity. It is important to note that all dates will be aligned to theend of each period by default - with the exception ofto.monthly() andto.quarterly(), which use thezoo package'syearmon andyearqtr classes, respectively.

Valid period character strings include:"seconds","minutes","hours","days","weeks","months","quarters", and"years". These arecalculated internally viaendpoints(). See that function's help page forfurther details.

To adjust the final indexing style, it is possible to setindexAt to oneof the following: ‘yearmon’, ‘yearqtr’, ‘firstof’,‘lastof’, ‘startof’, or ‘endof’. The final index willthen beyearmon,yearqtr, the first time of the period, the last timeof the period, the starting time in the data for that period, or the endingtime in the data for that period, respectively.

It is also possible to pass a single time series, such as a univariateexchange rate, and return an OHLC object of lower frequency - e.g. theweekly OHLC of the daily series.

Settingdrop.time = TRUE (the default) will convert a series that includesa time component into one with just a date index, since the time componentis often of little value in lower frequency series.

Value

An object of the original type, with new periodicity.

Note

In order for this function to work properly on OHLC data, it isnecessary that the Open, High, Low and Close columns be names as such;including the first letter capitalized and the full spelling found.Internally a call is made to reorder the data into the correct column order,and then a verification step to make sure that this ordering and naming hassucceeded. All other data formats must be aggregated with functions such asaggregate() andperiod.apply().

This method should work on almost all time-series-like objects. Including‘timeSeries’, ‘zoo’, ‘ts’, and ‘irts’. It iseven likely to work well for other data structures - including‘data.frames’ and ‘matrix’ objects.

Internally a call toas.xts() converts the originalx into theuniversal xts format, and then re-converts back to the original type.

A special note with respect to ‘ts’ objects. As these are strictlyregular they may includeNA values. These are removed before aggregation,though replaced before returning the result. This inevitably leads to manyadditionalNA values in the result. Consider using an xts object orconverting to xts usingas.xts().

Author(s)

Jeffrey A. Ryan

Examples

data(sample_matrix)samplexts <- as.xts(sample_matrix)to.monthly(samplexts)to.monthly(sample_matrix)str(to.monthly(samplexts))str(to.monthly(sample_matrix))

Convert Objects to xts and Back to Original Class

Description

Functions to convert objects of arbitrary classes to xts and then back tothe original class, without losing any attributes of the original class.

Usage

try.xts(x, ..., error = TRUE)reclass(x, match.to, error = FALSE, ...)Reclass(x)

Arguments

x

Data object to convert. See details for supported types.

...

Additional parameters or attributes.

error

Error handling option. See Details.

match.to

An xts object whose attributes will be copied to the result.

Details

A simple and reliable way to convert many different objects into a uniformformat for use withinR.

try.xts() andreclass() are functions that enable external developersaccess to the reclassing tools withinxts to help speed development oftime-aware functions, as well as provide a more robust and seemless end-userexperience, regardless of the end-user's choice of data-classes.

try.xts() callsas.xts() internally. Seeas.xts() for available xtsmethods and arguments for each coercible class. Since it callsas.xts(),you can add custom attributes asname = value pairs in the same way. Butthese custom attributes will not be copied back to the original object whenreclass() is called.

Theerror argument can be a logical value indicating whether an errorshould be thrown (or fail silently), a character string allowing for customerror error messages, or a function of the formf(x, ...) that will becalled if the conversion fails.

reclass() converts an object created bytry.xts() back to its originalclass with all the original attributes intact (unless they were changedafter the object was converted to xts). Thematch.to argument allows youcopy the index attributes (tclass,tformat, andtzone) andxtsAttributes() from another xts object to the result.match.to mustbe an xts object with an index value for every observation inx.

Reclass() is designed for top-level use, where it is desirable to havethe object returned from an arbitrary function in the same class as theobject passed in. Most functions inR are not designed to return objectsmatching the original object's class. It attempts to handle conversion andreconversion transparently but it requires the original object must becoercible to xts, the result of the function must have the same number ofrows as the input, and the object to be converted/reclassed must be thefirst argument to the function being wrapped. Note that this functionhasn't been tested for robustness.

See the accompanying vignette for more details on the above usage.

Value

try.xts() returns an xts object when conversion is successful.Theerror argument controls the function's behavior when conversion fails.

Reclass() andreclass() return the object as its original class, asspecified by the 'CLASS' attribute.

Author(s)

Jeffrey A. Ryan

See Also

as.xts()

Examples

a <- 1:10# fails silently, the result is still an integer vectortry.xts(a, error = FALSE)# control the result with a functiontry.xts(a, error = function(x, ...) { "I'm afraid I can't do that." })z <- zoo(1:10, timeBasedSeq("2020-01-01/2020-01-10"))x <- try.xts(z)  # zoo to xtsstr(x)str(reclass(x))  # reclass back to zoo

Extract Time Windows from xts Objects

Description

Method for extracting time windows from xts objects.

Usage

## S3 method for class 'xts'window(x, index. = NULL, start = NULL, end = NULL, ...)

Arguments

x

An xts object.

index.

A user defined time index (default.index(x)).

start

A start time coercible to POSIXct.

end

An end time coercible to POSIXct.

...

Unused.

Details

The xtswindow() method provides an efficient way to subset an xts objectbetween a start and end date using a binary search algorithm. Specifically,it convertsstart andend to POSIXct and then does a binary search ofthe index to quickly return a subset ofx betweenstart andend.

Bothstart andend may be any class that is convertible to POSIXct, suchas a character string in the format ‘yyyy-mm-dd’. Whenstart = NULLthe returned subset will begin at the first value ofindex.. Whenend = NULL the returned subset will end with the last value ofindex..Otherwise the subset will contain all timestamps whereindex. is betweenstart andend, inclusive.

Whenindex. is specified,findInterval() is used to quickly retrievelarge sets of sorted timestamps. For the best performance,index. must beasorted POSIXct vector or a numeric vector of seconds since the epoch.index. is typically a subset of the timestamps inx.

Value

The subset ofx that matches the time window.

Author(s)

Corwin Joy

See Also

subset.xts(),findInterval(),xts()

Examples

## xts examplex.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,19,2), sep = "-"))x <- xts(matrix(rnorm(20), ncol = 2), x.date)xwindow(x, start = "2003-02-01", end = "2003-03-01")window(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01"))window(x, index. = x.date[1:6], start = as.Date("2003-02-01"))window(x, index. = x.date[c(4, 8, 10)])## Assign to subsetwindow(x, index. = x.date[c(4, 8, 10)]) <- matrix(1:6, ncol = 2)x

Create or Test For An xts Time-Series Object

Description

Constructor function for creating an extensible time-series object.

Usage

xts(  x = NULL,  order.by = index(x),  frequency = NULL,  unique = TRUE,  tzone = Sys.getenv("TZ"),  ...).xts(  x = NULL,  index,  tclass = c("POSIXct", "POSIXt"),  tzone = Sys.getenv("TZ"),  check = TRUE,  unique = FALSE,  ...)is.xts(x)

Arguments

x

An object containing the underlying data.

order.by

A corresponding vector of dates/times of a known time-basedclass. See Details.

frequency

Numeric value indicating the frequency oforder.by. Seedetails.

unique

Can the index only include unique timestamps? Ignored whencheck = FALSE.

tzone

Time zone of the index (ignored for indices without a timecomponent, e.g. Date, yearmon, yearqtr). Seetzone().

...

Additional attributes to be added. See details.

index

A correspondingnumeric vector specified as seconds sincethe UNIX epoch (1970-01-01 00:00:00.000).

tclass

Time class to use for the index. Seetclass().

check

Must the index be ordered? The index cannot contain duplicateswhencheck = TRUE andunique = TRUE.

Details

xts() is used to create an xts object from raw data inputs. The xts classinherits from and extends the zoo class, which means most zoo functions canbe used on xts objects.

Thexts() constructor is the preferred way to create xts objects. Itperforms several checks to ensure it returns a well-formed xts object. The.xts() constructor is mainly for internal use. It is more efficient thenthe regularxts() constructor because it doesn't perform as many validitychecks. Use it with caution.

Similar to zoo objects, xts objects must have an ordered index. While zooindexes cannot contain duplicate values, xts objects have optionallysupported duplicate index elements since version 0.5-0. The xts class hasone additional requirement: the index must be a time-based class. Currentlysupported classes include: ‘Date’, ‘POSIXct’, ‘timeDate’,as well as ‘yearmon’ and ‘yearqtr’ where the index valuesremain unique.

The uniqueness requirement was relaxed in version 0.5-0, but is stillenforced by default. Settingunique = FALSE skips the uniqueness check andonly ensures that the index is ordered via theisOrdered() function.

As of version 0.10-0, xts no longer allows missing values in the index. Thisis because many xts functions expect all index values to be finite. The mostimportant of these ismerge.xts(), which is used ubiquitously. Missingvalues in the index are usually the result of a date-time conversion error(e.g. incorrect format, non-existent time due to daylight saving time, etc.).Because of how non-finite numbers are represented, a missing timestamp willalways be at the end of the index (except if it is-Inf, which will befirst).

Another difference fromzoo is that xts object may carry additionalattributes that may be desired in individual time-series handling. Thisincludes the ability to augment the objects data with meta-data otherwisenot cleanly attachable to a standard zoo object. These attributes may beassigned and extracted viaxtsAttributes() andxtsAttributes<-,respectively.

Examples of usage from finance may include the addition of data for keepingtrack of sources, last-update times, financial instrument descriptions ordetails, etc.

The idea behindxts is to offer the user the ability to utilize astandard zoo object, while providing an mechanism to customize the object'smeta-data, as well as create custom methods to handle the object in a mannerrequired by the user.

Many xts-specific methods have been written to better handle the uniqueaspects of xts. These include, subsetting ([),merge(),cbind(),rbind(),c(), math and logical operations,lag(),diff(),coredata(),head(), andtail(). There are also xts-specific methodsfor converting to/from R's different time-series classes.

Subsetting via[ methods offers the ability to specify dates by range, ifthey are enclosed in quotes. The style borrows from python by creatingranges separated by a double colon “"::"” or “"/"”. Each sideof the range may be left blank, which would then default to the start andend of the data, respectively. To specify a subset of times, it is onlyrequired that the time specified be in standard ISO format, with some formof separation between the elements. The time must beleft-filled, that isto specify a full year one needs only to provide the year, a month requiresthe full year and the integer of the month requested - e.g. '1999-01'. Thisformat would extend all the way down to seconds - e.g. '1999-01-01 08:35:23'.Leading zeros are not necessary. See the examples for more detail.

Users may also extend the xts class to new classes to allow for methodoverloading.

Additional benefits derive from the use ofas.xts() andreclass(),which allow for lossless two-way conversion between common R time-seriesclasses and the xts object structure. See those functions for more detail.

Value

An S3 object of class xts.

Author(s)

Jeffrey A. Ryan and Joshua M. Ulrich

References

zoo

See Also

as.xts(),index(),tclass(),tformat(),tzone(),xtsAttributes()

Examples

data(sample_matrix)sample.xts <- as.xts(sample_matrix, descr='my new xts object')class(sample.xts)str(sample.xts)head(sample.xts)  # attribute 'descr' hidden from viewattr(sample.xts,'descr')sample.xts['2007']  # all of 2007sample.xts['2007-03/']  # March 2007 to the end of the data setsample.xts['2007-03/2007']  # March 2007 to the end of 2007sample.xts['/'] # the whole data setsample.xts['/2007'] # the beginning of the data through 2007sample.xts['2007-01-03'] # just the 3rd of January 2007

Internal Documentation

Description

This help file is to help in development of xts, as well as provide someclarity and insight into its purpose and implementation.

Details

Last modified: 2008-08-06 by Jeffrey A. Ryan Version: 0.5-0 and above

Thexts package xts designed as a drop-in replacement for the verypopularzoo package. Most all functionality of zoo has been extendedor carries into the xts package.

Notable changes in direction include the use of time-based indexing, atfirst explicitely, now implicitely.

An xts object consists of data in the form of a matrix, an index -ordered and increasing, either numeric or integer, and additional attributesfor use internally, or for end-user purposes.

The current implementation enforces two major rules on the object. One isthat the index must be coercible to numeric, by way ofas.POSIXct.There are defined types that meet this criteria. SeetimeBased fordetails.

The second requirement is that the object cannot have rownames. Themotivation from this comes in part from the work Matthew Doyle has done inhis data.table class, in the package of the same name. Rownames in must becharacter vectors, and as such are inefficient in both storage andconversion. By eliminating the rownames, and providing a numeric index ofinternal typeREAL orINTEGER, it is possible to maintain aconnection to standard date and time classes via the POSIXct functions,while at at the same time maximizing efficiencies in data handling.

User level functionsindex, as well as conversion to other classesproceeds as if there were rownames. The code forindex automaticallyconverts time to numeric in both extraction and replacement functionality.This provides a level of abstraction to facilitate internal, and externalpackage use and inter-operability.

There is also new work on providing a C-level API to some of the xtsfunctionality to facilitate external package developers to utilize the fastutility routines such as subsetting and merges, without having to call onlyfrom . Obviously this places far more burden on the developer to not onlyunderstand the internal xts implementation, but also to understand all ofwhat is documented for R-internals (and much that isn't). At present thefunctions and macros available can be found in the ‘xts.h’ file inthe src directory.

There is no current documentation for this API. The adventure starts here.Future documentation is planned, not implemented.

Author(s)

Jeffrey A. Ryan


xts C API Documentation

Description

This help file is to help in development of xts, as well as provide someclarity and insight into its purpose and implementation.

Details

By Jeffrey A. Ryan, Dirk Eddelbuettel, and Joshua M. Ulrich Last modified:2018-05-02 Version: 0.10-3 and above

At present thexts API has publicly available interfaces to thefollowing functions (as defined inxtsAPI.h):

Callable from other R packages:  SEXP xtsIsOrdered(SEXP x, SEXP increasing, SEXP strictly)  SEXP xtsNaCheck(SEXP x, SEXP check)  SEXP xtsTry(SEXP x)  SEXP xtsRbind(SEXP x, SEXP y, SEXP dup)  SEXP xtsCoredata(SEXP x)  SEXP xtsLag(SEXP x, SEXP k, SEXP pad)Internal use functions:  SEXP isXts(SEXP x)  void copy_xtsAttributes(SEXP x, SEXP y)  void copy_xtsCoreAttributes(SEXP x, SEXP y)Internal use macros:  xts_ATTRIB(x)  xts_COREATTRIB(x)  GET_xtsIndex(x)  SET_xtsIndex(x,value)  GET_xtsIndexFormat(x)  SET_xtsIndexFormat(x,value)  GET_xtsCLASS(x)  SET_xtsCLASS(x,value)Internal use SYMBOLS:  xts_IndexSymbol  xts_ClassSymbol  xts_IndexFormatSymbolCallable from R:  SEXP mergeXts(SEXP args)  SEXP rbindXts(SEXP args)  SEXP tryXts(SEXP x)

Author(s)

Jeffrey A. Ryan

Examples

## Not run: # some example code to look atfile.show(system.file('api_example/README', package="xts"))file.show(system.file('api_example/src/checkOrder.c', package="xts"))## End(Not run)

Extract and Replace xts Attributes

Description

Extract and replace non-core xts attributes.

Usage

xtsAttributes(x, user = NULL)xtsAttributes(x) <- value

Arguments

x

An xts object.

user

Should user-defined attributes be returned? The default ofNULL returns all xts attributes.

value

A list of newname = value attributes.

Details

This function allows users to assign custom attributes to the xts objects,without altering core xts attributes (i.e. tclass, tzone, and tformat).

attributes() returns all attributes, including core attributes of thexts class.

Value

A named list of user-defined attributes.

Author(s)

Jeffrey A. Ryan

See Also

attributes()

Examples

x <- xts(matrix(1:(9*6),nc=6),         order.by=as.Date(13000,origin="1970-01-01")+1:9,         a1='my attribute')xtsAttributes(x)xtsAttributes(x) <- list(a2=2020)xtsAttributes(x)xtsAttributes(x) <- list(a1=NULL)xtsAttributes(x)

[8]ページ先頭

©2009-2025 Movatter.jp