.. index:: ts .. _ts: .. _ts_properties_methods: The properties =============== .. index:: ts.varnames .. _ts.varnames: varnames --------- names of the variables in the database .. index:: ts.data .. _ts.data: data ----- time series .. index:: ts.description .. _ts.description: description ------------ comments on the time series .. index:: ts.NumberOfObservations .. _ts.NumberOfObservations: NumberOfObservations --------------------- number of observations in the time series .. index:: ts.NumberOfPages .. _ts.NumberOfPages: NumberOfPages -------------- number of pages (third dimension) of the time series .. index:: ts.NumberOfVariables .. _ts.NumberOfVariables: NumberOfVariables ------------------ number of variables in the time series .. index:: ts.finish .. _ts.finish: finish ------- end time of the time series .. index:: ts.frequency .. _ts.frequency: frequency ---------- frequency of the time series .. index:: ts.start .. _ts.start: start ------ start time of the time series The methods ============ .. index:: ts.abs .. _ts.abs: abs ---- Computes the absolute value of a ts object :: db=abs(db) Args: db (ts ): RISE time series object Returns: : - **db** : [ts]: a time series .. index:: ts.acos .. _ts.acos: acos ----- Overloaded acos function for ts object .. index:: ts.acosh .. _ts.acosh: acosh ------ Overloaded acosh function for ts object .. index:: ts.acot .. _ts.acot: acot ----- Overloaded acot for ts object .. index:: ts.acoth .. _ts.acoth: acoth ------ Overloaded acoth for ts object .. index:: ts.allmean .. _ts.allmean: allmean -------- Compute all different type of means for the time series variables :: m = allmean(db); Args: db (ts object): the times series object to compute the mean of Returns: : - m (cell): Cell containing - 1st column: strings denoting the type of mean (Harmonic, Geometric, Arithmetic, Quadratic) - 1st row: variable names - otherwise: mean value corresponding to the variable and mean concept. .. index:: ts.and .. _ts.and: and ---- INTERNAL FUNCTION: Combines two databases into a combined database Note: - It is assumed that the frequency and length of time series are the same between the two databases. .. index:: ts.apply .. _ts.apply: apply ------ APPLY - Applies a unary function to each element of a time series database Syntax: db = apply(db, fhandle) Inputs: db - Time series database (ts object) fhandle - Unary function handle that accepts a scalar input and returns a scalar output Outputs: db - Resulting time series database after applying the unary function to each element Description: The 'apply' function applies a unary function to each element of a time series database. It performs the operation element-wise and returns a new time series database with the transformed values. Examples: % Create a time series database dates = rd('2000-01-01'); data = rand(5, 3); varnames = {'Var1', 'Var2', 'Var3'}; db = ts(dates, data, varnames); % Define a unary function fhandle = @(x) log(x); % Apply the function to each element of the time series database transformed_db = apply(db, fhandle); % Display the resulting time series database disp(transformed_db); .. seealso:: ts, unary_operation .. index:: ts.area .. _ts.area: area ----- AREA Overloaded area function for time series (ts) objects. This function creates area plots for time series (:ref:`ts `) objects by extending MATLAB's `area` functionality. It allows for specifying a date range for plotting and supports full customization using name-value pairs. Syntax: area(xrange, ts1, ..., 'Name', Value, ...) area(ts1, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to plot. If omitted, the entire range of the time series is used. Example: `xrange = rq(2020,1):rq(2022,4);` - ts1: A :ref:`ts ` object representing the data to be plotted as an area chart. - Name, Value: Additional name-value pairs to customize the plot. These are passed directly to MATLAB's `area` function. Outputs: - varargout: Handles to the graphical objects created by the area plot. Features: - Supports area plotting for :ref:`ts ` objects, automatically extracting dates and data. - Aligns data to the specified date range (`xrange`), if provided. - Fully compatible with MATLAB's `area` customization options, including colors, transparency, and stacking. Examples: % Create a basic area plot for a time series area(ts1); % Create an area plot for a specific date range xrange = rq(2020,1):rq(2022,4); area(xrange, ts1, 'FaceColor', 'blue', 'EdgeColor', 'black'); % Customize the appearance of the area plot area(ts1, 'FaceAlpha', 0.5, 'LineWidth', 1.5); .. seealso:: area, ts, utils.plot.myplot .. index:: ts.asin .. _ts.asin: asin ----- Overloaded asin for ts object .. index:: ts.asinh .. _ts.asinh: asinh ------ Overloaded asinh for ts object .. index:: ts.atan .. _ts.atan: atan ----- Overloaded atan for ts object .. index:: ts.atanh .. _ts.atanh: atanh ------ Overloaded atanh for ts object .. index:: ts.bar .. _ts.bar: bar ---- Make bar graph of the time series :: varargout = bar(X,db,varargin); Args: X (dates): Date description - string of dates, e.g., X='1990:2000' - serial dates, e.g., X=date2serial('1990Q1'):date2serial('2000Q1') db (ts object): Time series object with data options (options): Options need to come in pairs - 'figsize' ([value, value]): the figure size (multiple plots) with default [3,3] - 'figtitle' (string): the figure title (multiple plots) with default '' - the number of tick marks (integer): 'nticks', with default 8 - 'date_format': the date format (see matlab's datestr) with default '' - 'logy' (bool): the log scale with default false - 'secondary_y': the list of variables going to the secondary y axis - 'subplots' (bool): the flag for multiple plots with default false Note: - bar(db) uses the dates within db. The colors are set by the colormap. - bar(X,db,WIDTH) or bar(db,WIDTH) specifies the width of the bars. Values of WIDTH > 1, produce overlapped bars. The default value is WIDTH=0.8 - bar(...,'grouped') produces the default vertical grouped bar chart. bar(...,'stacked') produces a vertical stacked bar chart. bar(...,LINESPEC) uses the line color specified (one of 'rgbymckw'). - H = bar(...) returns a vector of handles to barseries objects. - Use SHADING FACETED to put edges on the bars. Use SHADING FLAT to turn them off. Example: :: bar('1994m7:1997m1',db(:,:,1),... 'figsize',[2,2],... 'figtitle','no title',... 'nticks',10,... 'legend',{'v1','v2'},... 'legend_loc','BO',... 'logy',true,... 'secondary_y',{'v1','v4'},... 'subplots',true,... 'linewidth',2,... 'date_format',17); xrotate(90) .. seealso:: - ``hist`` - ``plot`` - ``barh`` - ``bar3`` - ``bar3h`` .. index:: ts.barh .. _ts.barh: barh ----- Make bar graph of the time series :: varargout = bar(X,db,varargin); Args: X (string \| serial): Date description - string of dates, e.g., X='1990:2000' - serial dates, e.g., X=date2serial('1990Q1'):date2serial('2000Q1') db (ts object): Time series object with data options (pairs): Options need to come in pairs - 'figsize' ([value, value]): the figure size (multiple plots) with default [3,3] - 'figtitle' (string): the figure title (multiple plots) with default '' - the number of tick marks (integer): 'nticks', with default 8 - 'date_format': the date format (see matlab's datestr) with default '' - 'logy' (bool): the log scale with default false - 'secondary_y': the list of variables going to the secondary y axis - 'subplots' (bool): the flag for multiple plots with default false Note: - bar(db) uses the dates within db. The colors are set by the colormap. - bar(X,db,WIDTH) or bar(db,WIDTH) specifies the width of the bars. Values of WIDTH > 1, produce overlapped bars. The default value is WIDTH=0.8 - bar(...,'grouped') produces the default vertical grouped bar chart. bar(...,'stacked') produces a vertical stacked bar chart. bar(...,LINESPEC) uses the line color specified (one of 'rgbymckw'). - H = bar(...) returns a vector of handles to barseries objects. - Use SHADING FACETED to put edges on the bars. Use SHADING FLAT to turn them off. Example: :: bar('1994m7:1997m1',db(:,:,1),... 'figsize',[2,2],... 'figtitle','no title',... 'nticks',10,... 'legend',{'v1','v2'},... 'legend_loc','BO',... 'logy',true,... 'secondary_y',{'v1','v4'},... 'subplots',true,... 'linewidth',2,... 'date_format',17); xrotate(90) .. seealso:: - ``hist`` - ``plot`` - ``barh`` - ``bar3`` - ``bar3h`` .. index:: ts.boxplot .. _ts.boxplot: boxplot -------- Make box plots of multiple time series in a frame. Overloads Matlab's boxplot function for ts objects :: h = boxplot(db); h = boxplot(xrange, db); h = boxplot(..., varargin); Args: db (ts object): time series object xrange (char \| cellstr \| serial date): Range of the data to plot varargin (pairs): additional matlab (See BOXPLOT) and RISE (PARSE_PLOT_ARGS) options coming in pairs .. seealso:: parse_plot_args .. index:: ts.bsxfun .. _ts.bsxfun: bsxfun ------- Overloaded bsxfun for ts object .. index:: ts.cat .. _ts.cat: cat ---- Concatenates time series along the specified dimension :: db=cat(1,db1,db2,...,dbn) db=cat(2,db1,db2,...,dbn) db=cat(3,db1,db2,...,dbn) Args: dim (1 \| 2 \| 3): dimension along which concatenation is done dbi (ts object): time series object Returns: - **db** [ts] : time series with concatenated series Note: - all times series must be of the same frequency (see ``aggregate``) - Concatenation along the second dimension requires that variables have the same number of columns if no names are specified - if names are specified in the first time series, then names should be specified in all of the others as well. - empty time series are discarded but there should be at least one non-empty time series .. index:: ts.chebyshev_box .. _ts.chebyshev_box: chebyshev_box -------------- Constructs chebyshev boxes for multivariate-multiperiods densities :: mvcb=chebyshev_box(this,gam) Args: this (ts \| rts) : time series with many pages (number of simulations) and potentially many columns (number of variables) gam (scalar \| vector) : percentile(s) Returns: : - **mvcb** [struct] : structure with time series in its fields. Each field represents a particular variable - **gam_** [scalar\|vector] : sorted percentile(s) - **my** [ts] : mean across simulations .. index:: ts.chowlin .. _ts.chowlin: chowlin -------- Temporal disaggregation using the Chow-Lin method :: [yh,res]=chowlin(y0,Xh0) [yh,res]=chowlin(y0,Xh0,aggreg_type) [yh,res]=chowlin(y0,Xh0,aggreg_type,estim_method) [yh,res]=chowlin(y0,Xh0,aggreg_type,estim_method,ngrid) Args: y0 (ts object): low-frequency left-hand-side variable Xh0 (ts \| struct): high-frequency right-hand-side explanatory variables aggreg_type ('flow' \| {'average'} \| 'index' \| 'last' \| 'first'): type of aggregation: - 'flow' (or 1) is the sum, - 'average','index' (or 2) is the average, - 'last' (or 3) is the last element, - 'first' (or 4) is the first element, estim_method ({0} \| 1 \| 2) : estimation method - 0 : Generalized/Weighted Least squares (with grid) - 1 : Maximum Likelihood (with grid), - 2 : Maximum Likelihood (without grid) using fmincon as optimizer ngrid (integer \| {250}) : number of grid points Returns: : - **yh** [ts] : (disaggregated) high-frequency left-hand-side variable - **res** [struct] : structure with further details on the computations REFERENCES: - Chow, G. and Lin, A.L. (1971) "Best linear unbiased distribution and extrapolation of economic time series by related series", Review of Economic and Statistics, vol. 53, n. 4, p. 372-375. - Bournay, J. y Laroque, G. (1979) "Reflexions sur la methode d'elaboration des comptes trimestriels", Annales de l'INSEE, n. 36, p. 3-30. .. index:: ts.collect .. _ts.collect: collect -------- Brings together several time series objects into a one time series Syntax: this=ts.collect(v1,v2,...,vn) Args: Vi (cell \| ts \| struct): time series in ts format: - cell: When Vi is a cell, then its format should be {vname,ts} i.e. the first element is the name of the variable and the second is the data for the variable. In this case, the data must be a single time series - ts: - struct: the fields of the structure should be of the ts format. Returns: - **this** [ts]: a time series with many columns and potentially many pages .. index:: ts.concatenator .. _ts.concatenator: concatenator ------------- Concatenate outputs from multiple time series or structures of time series :: myirfs=concatenator(db1,db2,...,dbn) Args: dbi (struct \| ts): time series or structure of time series Returns: - **myirfs** [struct] : structure containing the concatenated time series .. index:: ts.convert .. _ts.convert: convert -------- CONVERT Converts data in different frequencies. Usage: newdb = convert(db, newFrequency) newdb = convert(db, newFrequency, squash) Inputs - db: Time series data structure (ts class) with the following fields: - db.dates: Dates of the time series data - db.data: Data values corresponding to the dates - newFrequency: Desired frequency for the converted time series. Supported frequencies are: - 'D': Daily - 'W': Weekly - 'M': Monthly - 'Q': Quarterly - 'H': Half-yearly - 'Y': Yearly - squash (optional): Aggregation function used to combine data points within each time period. It can be either a function handle or a character array representing a function name. If not provided, the default aggregation function is 'mean'. NOTE : The squash function will be applied ONLY when going from higher to lower frequency (aggregation). Otherwise, the higher frequency is written as is in the dates corresponding to the observations, and nan elsewhere. Outputs: - newdb: Converted time series data structure (ts class) with the following fields: - newdb.dates: Dates of the converted time series - newdb.data: Data values corresponding to the dates Example: dates = rd(2022, 1, 1); data = randn(365, 1); db = ts(dates, data); newdb = convert(db, 'M', @sum); See also MEAN, SUM. Notes: - The function converts the data in the time series db into the specified newFrequency by aggregating the data using the provided squash function. - If the newFrequency is the same as the original frequency of the time series, the function returns the input db unchanged. - The function supports different aggregation functions specified by the squash argument. The default aggregation function is 'mean'. - The input db must be a time series represented by the ts class, with dates and data values provided. - The function works with daily, weekly, monthly, quarterly, half-yearly and yearly frequencies. - For frequencies higher than daily (e.g., weekly, monthly), the function aggregates the data within each time period based on the specified squash function. .. index:: ts.corr .. _ts.corr: corr ----- Computes correlation for time series: It is an interface to MATLAB implementation of corr :: varargout = corr(db,varargin); Args: db (ts object): times series object varargin: varargin for corr function in MATLAB Returns: : varargout: output from corr function .. index:: ts.corrcoef .. _ts.corrcoef: corrcoef --------- Computes correlation for time series: It is an interface to MATLAB implementation of corrcoef :: varargout = corrcoef(db,varargin); Args: db (ts object): times series object varargin: varargin for corrcoef function in MATLAB Returns: : varargout: output from corrcoef function .. index:: ts.cos .. _ts.cos: cos ---- Overloaded cos function for ts object .. index:: ts.cosh .. _ts.cosh: cosh ----- Overloaded cosh function for ts object .. index:: ts.cot .. _ts.cot: cot ---- Overloaded cot function for ts object .. index:: ts.coth .. _ts.coth: coth ----- Overloaded coth function for ts object .. index:: ts.cov .. _ts.cov: cov ---- Computes covariances for time series: It is an interface to MATLAB implementation of cov adjusted to handle nan properly :: varargout = cov(db,varargin); Args: db (ts object): times series object varargin: varargin for cov function in MATLAB Returns: : varargout: output from cov function .. index:: ts.cumprod .. _ts.cumprod: cumprod -------- Overloaded cumprod function for ts object .. index:: ts.cumsum .. _ts.cumsum: cumsum ------- Overloaded cumsum function for ts object .. index:: ts.describe .. _ts.describe: describe --------- Print the description of the time series object Args: db (ts object): time series to describe Note: The function prints - mean - standard deviation - min - 25th percentile - 50th percentile - 75th percentile - max - variable names - variable descriptions .. index:: ts.disp .. _ts.disp: disp ----- Overloaded disp function for ts object .. index:: ts.double .. _ts.double: double ------- DOUBLE: Returns the underlying data of the time series :: data = double(db); Args: db (ts object): time series object Returns: : - data (numeric): vector/matrix/tensor form of the data underlying the time series .. index:: ts.drop .. _ts.drop: drop ----- Drops the variable from the time series :: db=drop(db,'var_name'); Args: db (ts object): time series object varargin (string): names of the variables to drop Returns: : - db (ts object): time series object with corresponding variables dropped .. index:: ts.dummy .. _ts.dummy: dummy ------ Creates a dummy observation times series :: db=dummy(start_date,end_date,dummy_date) Args: - **start_date** (char \| serial date): start date of the time series - **end_date** (char \| serial date): end date of the time series - **dummy_date** (char \| serial date): date(s) at which to time series is 1 and not 0 Returns: - **db** [ts]: scalar time series of dummy observations .. index:: ts.dust_up .. _ts.dust_up: dust_up -------- Sets insignificant digits to zero :: this=dust_up(this) this=dust_up(this,crit) Args: this (rts \| ts): time-series object crit (numeric \| {sqrt(eps)}): cutoff point Returns: : - **this** [rts\|ts]: time-series object .. index:: ts.end .. _ts.end: end ---- END Overloads end to time series (ts) class. ind = END(self, k, n) This function overloads the end function for the time series (ts) class. It computes the index at the end of a given dimension. - `self`: Time series object. - `k`: Dimension requested. - `n`: Number of dimensions of self Returns: - `ind`: Index at the end of the specified dimension. Example: - ind = END(self, k, n) .. seealso:: ts .. index:: ts.errorbar .. _ts.errorbar: errorbar --------- ERRORBAR Overloaded errorbar function for time series (ts) objects. This function creates error bar plots for time series (:ref:`ts `) objects by extending MATLAB's `errorbar` functionality. It allows for specifying a date range for plotting and supports full customization using name-value pairs. Syntax: errorbar(xrange, ts1, ts2, ts3, ..., 'Name', Value, ...) errorbar(ts1, ts2, ts3, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to plot. If omitted, the entire range of the time series is used. - ts1: A :ref:`ts ` object representing the central data values (y-coordinates). - ts2: A :ref:`ts ` object representing the lower error bounds. - ts3: A :ref:`ts ` object representing the upper error bounds. - Name, Value: Additional name-value pairs to customize the plot. These are passed directly to MATLAB's `errorbar` function. Outputs: - varargout: Handles to the graphical objects created by the plot. Features: - Automatically aligns data to a specified date range (`xrange`), if provided. - Supports error bar plotting for :ref:`ts ` objects, automatically extracting dates and data from the input time series. - Maintains compatibility with MATLAB's `errorbar` customization options. Examples: % Basic error bar plot with time series data errorbar(ts1, ts2, ts3); % Error bar plot with a specified date range xrange = rq(2020,1):rq(2022,4); errorbar(xrange, ts1, ts2, ts3, 'LineWidth', 1.5, 'Color', 'k'); % Customize error bar appearance errorbar(ts1, ts2, ts3, 'LineStyle', '--', 'Marker', 'o'); .. seealso:: errorbar, ts, utils.plot.myplot .. index:: ts.exp .. _ts.exp: exp ---- Overloaded exp function for ts object .. index:: ts.expanding .. _ts.expanding: expanding ---------- Applies a function to an expanding window of the time series :: h = expanding(db,func); h = expanding(db,func,varargin); Args: db (ts object): time series object to get data func: function that will apply to the expanding window of the time series. The function is recursively applied to the data 1:t for t=1,2,3,...,T, where T is the number of observations varargin: additional arguments to func .. index:: ts.fanchart .. _ts.fanchart: fanchart --------- FANCHART Creates data for plotting a fan chart. out = fanchart(this, ci) generates the data required to plot a fan chart. The input "this" is a time series object with either multiple pages or multiple columns, but not both. The input "ci" is a vector specifying the confidence levels in the range [0, 1] or [0, 100] to be used in calculating the width of the fans. The output "out" is a structure with the following fields: - ci: Vector of confidence levels (same as input ci) - median: Vector of medians of the data - variance: Vector of variances of the data - quantiles: Matrix of quantiles defined by ci - prob_index: Vector of locations of the cutoffs in the data - probs: Vector of probabilities for the quantiles (function of ci) - dates: Vector of serial dates for reconstructing the time series Example: - Generate data for a fan chart and plot it: this = ts('1990Q2', rand(100, 1000)); out = fanchart(this, [30, 50, 70, 90]); plot_fanchart(out, 'r', 10); Note: - If the input time series contains several variables, the output is a structure with the names of the different variables in the first level of the fields. See also PLOT_FANCHART. .. index:: ts.fold .. _ts.fold: fold ----- Folds the first page of possibly several databases and adds further pages using the information from a pivot date. Usage: this = fold(last_hist_date, obj) this = fold(last_hist_date, obj1, obj2, ..., objn) Inputs: - last_hist_date: A character string or serial date representing the pivot date. The rows after this date will be folded behind the corresponding row. - obj: A time series object (ts). - obj1, obj2, ..., objn: Additional time series objects (ts). Output: - this: A folded time series object (ts) with the first page of data from the input time series objects, followed by folded pages. .. seealso:: - ``unfold`` .. index:: ts.get .. _ts.get: get ---- get Access/Query time series property values. VALUE = get(TS,'PropertyName') returns the value of the specified property of the time series object. An equivalent syntax is VALUE = TS.PropertyName get(TS) displays all properties of TS and their values. .. index:: ts.group .. _ts.group: group ------ Groups contributions :: g=group(this,{group1,{v11,v12,...}},...,{groupn,{vn1,vn2,...}}) Args: - **this** (ts): time series of multiple variables - **groups** : [structure\|cell array \|{empty}] grouping of shocks in the decomposition. By default, the shocks are not grouped. The syntax is of the form {group1,{v11,v12,...},...,groupn,{vn1,vn2,...}}. The shocks that are not listed are put in a special group called "others". The "others" group does not include the effect of initial conditions. e.g.:: p=struct(); p.demand={'Ey','Er'}; p.supply={'Ep'}; e.g. p={'demand',{'Ey','Er'},'supply',{'Ep'}}; Returns: - **g** [ts]: new time series with grouped contributions .. index:: ts.head .. _ts.head: head ----- Returns the first few sample dates of the time series Syntax: db = head(db); db = head(db,n); Args: - db (ts object): time series object - n (integer): number of time steps to show Returns: - db (ts object): time series with the first n-time steps Note: - This is similar to the head function in stata. .. index:: ts.hist .. _ts.hist: hist ----- Make histograms from time series :: h = hist(db); h = hist(xrange, db); h = hist(xrange, db, M); h = hist(xrange, db, X); Args: db (ts object): time series object xrange: date range. Check XXXXX for correct format M (integer): number of bins (default 10) X (vector): histogram with bin centers given by X Returns: : h (figure handle): handle to the plotted histogram Example: :: hist('1994m7:1997m1',db(:,:,1),... 'figsize',[2,2],... 'figtitle','no title',... 'logy',true,... 'subplots',true) Note: In addition to those matlab properties, RISE adds further properties, which allow to control for. See parse_plot_args .. index:: ts.histogram .. _ts.histogram: histogram ---------- HISTOGRAM Overloaded histogram function for time series (ts) objects. This function creates histograms for time series (:ref:`ts `) objects by extending MATLAB's `histogram` functionality. It allows for specifying a date range for the data used to construct the histogram and supports full customization using name-value pairs. Syntax: histogram(xrange, ts1, ..., 'Name', Value, ...) histogram(ts1, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to use for the histogram. If omitted, the entire range of the time series is used. Example: `xrange = rq(2020,1):rq(2022,4);` - ts1: A :ref:`ts ` object representing the data for which the histogram is constructed. - Name, Value: Additional name-value pairs to customize the histogram. These are passed directly to MATLAB's `histogram` function. Outputs: - varargout: Handles to the graphical objects created by the histogram plot. Features: - Supports histogram creation for :ref:`ts ` objects, automatically extracting data from the specified time range (`xrange`) if provided. - Fully compatible with MATLAB's `histogram` customization options, including binning, normalization, and styling. Examples: % Create a histogram for the entire time series histogram(ts1); % Create a histogram for data within a specific date range xrange = rq(2020,1):rq(2022,4); histogram(xrange, ts1, 'BinWidth', 0.5, 'Normalization', 'probability'); % Customize the appearance of the histogram histogram(ts1, 'FaceColor', 'blue', 'EdgeColor', 'black'); .. seealso:: histogram, ts, utils.plot.myplot .. index:: ts.horzcat .. _ts.horzcat: horzcat -------- Combines/concatenate databases into a combined database Note: - It is assumed that the frequency and length of time series are the same between the two databases. .. index:: ts.hpfilter .. _ts.hpfilter: hpfilter --------- HPFILTER Applies the Hodrick-Prescott filter to a ts object. Applies the Hodrick-Prescott (HP) filter to each variable in a ts object. Two call styles are supported: - legacy: hpfilter(db, 1600) - modern: hpfilter(db, smoothing=1600) Args: - db (ts): time series object. - smoothing (double, name-value, optional): the smoothing parameter (lambda). In the modern API it must be passed as a name-value pair, e.g. hpfilter(db, smoothing=1600); a legacy positional value is still accepted for backward compatibility. Returns: - hptrend (ts): trend component - hpcycle (ts): cyclical component .. index:: ts.imag .. _ts.imag: imag ----- imag : overloads imag for time series Syntax :: this=imag(this); Args: this (ts object): time series object Returns: - **this** (ts object): time series object .. index:: ts.interpolate .. _ts.interpolate: interpolate ------------ Interpolate based on the time series to fill in the missing dates :: db = interpolate(db); db = interpolate(db, method, varargin); Args: db (ts object): time series object to interpolate from method (string): interpolate method (default: spline). Same as the option used in MATLAB, i.e., - 'nearest': nearest neighbor interpolation - 'linear': linear interpolation - 'spline': piecewise cubic spline interpolation (SPLINE) - 'pchip': shape-preserving piecewise cubic interpolation - 'cubic': same as 'pchip' - 'v5cubic': the cubic interpolation from MATLAB 5, which does not extrapolate and uses 'spline' if X is not equally spaced. varargin{1}: optional condition for extrapolation (default: no extrapolation) - 'extrap': extrapolate out for dates outside the dates with observations - extrapval (double): use extrapval for dates outside the dates with observations .. index:: ts.isfinite .. _ts.isfinite: isfinite --------- Returns whether the corresponding data is finite :: flag = isfinite(db); Args: db (ts object): time series object Returns: : - flag (bool): whether the corresponding data is finite or not Note: - Since the time series object supports logical indexing, one can directly use the resulting flag with the time series object. .. index:: ts.isinf .. _ts.isinf: isinf ------ Returns whether the corresponding data is infinite :: flag = isinfinite(db); Args: db (ts object): time series object Returns: : - flag (bool): whether the corresponding data is infinite or not Note: - Since the time series object supports logical indexing, one can directly use the resulting flag with the time series object. .. index:: ts.isnan .. _ts.isnan: isnan ------ Returns whether the corresponding data is nan :: flag = isnan(db); Args: db (ts object): time series object Returns: : - flag (bool): whether the corresponding data is nan or not Note: - Since the time series object supports logical indexing, one can directly use the resulting flag with the time series object. .. index:: ts.jbtest .. _ts.jbtest: jbtest ------- Overloads Matlab's jbtest for ts objects. performs the Jarque-Bera goodness-of-fit test of composite normality :: [h,p,jbstat,critval]=jbtest(this) [h,p,jbstat,critval]=jbtest(this,alpha) [h,p,jbstat,critval]=jbtest(this,alpha,mctol) Args: - **this** (ts): time series object - **alpha** (numeric \| {0.05}): significance level - **mctol** (numeric \| {[]}): significance level when Monte Carlo is used (instead of interpolation) in the computation of **p** (see below) Returns: - **h** (0\|1): result of the test. H=0 indicates that the null hypothesis ("the data are normally distributed") cannot be rejected at the 5% significance level. H=1 indicates that the null hypothesis can be rejected at the 5% level. - **p**: p-value computed using inverse interpolation into the look-up table of critical values. Small values of p cast doubt on the validity of the null hypothesis - **jbstat**: test statistic - **critval**: critical value for the test .. seealso:: jbtest .. index:: ts.kurtosis .. _ts.kurtosis: kurtosis --------- Computes kurtosis for time series: It is an interface to MATLAB implementation of kurtosis :: varargout = kurtosis(db,varargin); Args: db (ts object): times series object varargin: varargin for kurtosis function in MATLAB Returns: : - **varargout**: output from kurtosis function .. index:: ts.lag .. _ts.lag: lag ---- LAG - lagged copy of a time series (value of k periods ago). :: out = lag(db) % equivalent to lag(db, 1) out = lag(db, k) Args: db (ts): time series. k (positive integer, default 1): number of periods to lag. Returns: out (ts): time series with the same dates and length as db, in which out.data(t,:,:) = db.data(t-k,:,:). The first k rows are NaN because those periods have no defined lag. Example: db = ts(rq(2000,1), (1:5)'); lag(db, 1) % data = [NaN; 1; 2; 3; 4] See also lead, shift. .. index:: ts.lead .. _ts.lead: lead ----- LEAD - leading copy of a time series (value k periods ahead). :: out = lead(db) % equivalent to lead(db, 1) out = lead(db, k) Args: db (ts): time series. k (positive integer, default 1): number of periods to look ahead. Returns: out (ts): time series with the same dates and length as db, in which out.data(t,:,:) = db.data(t+k,:,:). The last k rows are NaN because those periods have no defined lead within the sample. Example: db = ts(rq(2000,1), (1:5)'); lead(db, 1) % data = [2; 3; 4; 5; NaN] See also lag, shift. .. index:: ts.log .. _ts.log: log ---- Overloaded log function for ts object .. index:: ts.ma_filter .. _ts.ma_filter: ma_filter ---------- Moving average filter .. index:: filtering :: [trend,detrended]=ma_filter(y,q) [trend,detrended]=ma_filter(y,q,extend) Args: y (ts object): time series object q (integer \| {0.5\*frequency}): number of periods before or after the current one to be considered in the moving average calculation. The total window length is 2q+1 extend (true \| {'false'}): if true, replicated observations are added both at the beginning and at the end of the original dataset in order to avoid losing some observations during the filtering process. Returns: - **trend** [ts] : (non-parametric) trend - **detrended** [ts] : y-trend - **q** (integer \| {0.5\*frequency}) : value used in the computations .. index:: ts.max .. _ts.max: max ---- Overloaded max function for ts object .. index:: ts.mean .. _ts.mean: mean ----- Computes the mean of the time series :: m = mean(db); m = mean(db,dim); Args: db (ts object): times series object to compute the mean dim (integer): (optional; default 1) direction to compute the mean, e.g., dim = 1 is time mean of each variables, and dim = 3 would be panel mean Returns: : - m (double): mean values .. index:: ts.median .. _ts.median: median ------- Computes the median of the time series :: m = median(db); m = median(db,dim); Args: db (ts object): times series object to compute the median dim (integer): (optional; default 1) direction to compute the median, e.g., dim = 1 is time median of each variables, and dim = 3 would be panel median Returns: : - m (double): median values .. index:: ts.min .. _ts.min: min ---- Overloaded min function for ts object .. index:: ts.minus .. _ts.minus: minus ------ Overloaded minus function for ts object .. index:: ts.mode .. _ts.mode: mode ----- Computes mode for the time series: It is an interface to MATLAB implementation of mode :: varargout = mode(db,varargin); Args: db (ts object): times series object varargin: varargin for mode function in MATLAB Returns: : varargout: output from mode function .. index:: ts.moments .. _ts.moments: moments -------- Computes the empirical moments of a time series :: oo_ = moments(db); oo_ = moments(db,drange); oo_ = moments(db,drange,ar); oo_ = moments(db,drange,ar,lambda); Args: db (ts object): time series object to get data drange (char \| serial date \| cellstr \| {[]}): Range of the data to use ar (integer \| {1}): order of autocorrelation lambda (numeric \| {[]}): hyperparameter for hp-filtering the data before computing the moments. If empty, the data are not hp-filtered. Returns: - **oo_** [struct]: structure with fields - vcov : variance covariance - skewness : skewness - kurtosis : kurtosis - variance : variance - stdev : standard deviation - corrcoef : correlation array .. index:: ts.mpower .. _ts.mpower: mpower ------- Overloaded mpower function for ts object .. index:: ts.mrdivide .. _ts.mrdivide: mrdivide --------- Overloaded mrdivide for ts object Note: It matrix multiplication does not make sense for a time series object, so automatically defaults to element-wise division .. index:: ts.mtimes .. _ts.mtimes: mtimes ------- Overloaded times function for ts object Note: Matrix product does not make sense for time series object, so automatically defaults to element-wise product .. index:: ts.nan .. _ts.nan: nan ---- Initializes a ts object with the given start data and data initialized to nan :: db=ts.nan(start_date,varargin) Args: - **start_date** : [numeric\|char]: a valid time series (ts) date - varargin : [numeric]: arguments to matlab's **nan** function. Returns: : - **db** : [ts]: a time series Note: - this is a static method and so it has to be called with the **ts.** prefix - ts.nan does not allow more than 3 dimensions Example: :: db=ts.nan(1990,10,1) db=ts.nan('1990',10,3) db=ts.nan('1990Q3',10,5,100) .. index:: ts.npdecomp .. _ts.npdecomp: npdecomp --------- Non-parametric decomposition into trend, seasonal and irregular components .. index:: filtering :: out=npdecomp(y) out=npdecomp(y,doLog) Args: y (ts): time series to decompose doLog (true \| {false}): if log, do a multiplicative decomposition otherwise the decomposition is additive Returns: : - **out** [struct] : - **trend** [ts] : estimated trend - **sc** [ts] : estimated seasonal component - **sa** [ts] : seasonally adjusted data - **ic** [ts] : estimated irregular component Note: If there are many variables and the variables are named, the first level of the structure will be the names of the different variables. .. seealso:: - ``pdecomp`` .. index:: ts.numel .. _ts.numel: numel ------ Returns the number of data, i.e., (length of time)x(number of variables)x(number of panels) Syntax: n = numel(db); Args: db (ts object): time series object Returns: - n (integer): total number of data points, i.e., (length of time)x(number of variables)x(number of panels) .. index:: ts.ones .. _ts.ones: ones ----- Initializes a ts object with the given start data and data initialized to ones :: db=ts.ones(start_date,varargin) Args: start_date (numeric \| char): a valid time series (ts) date varargin (numeric): arguments to matlab's **ones** function. Returns: : - **db** : [ts]: a time series Note: - this is a static method and so it has to be called with the **ts.** prefix - ts.ones does not allow more than 3 dimensions Example: :: db=ts.ones(1990,10,1) db=ts.ones('1990',10,3) db=ts.ones('1990Q3',10,5,100) .. index:: ts.pages2struct .. _ts.pages2struct: pages2struct ------------- Turns multivariable ts object into a struct with time series object :: output = pages2struct(input) Args: input (ts object): ts object to turn into struct form of data Returns: : - **output** (struct): a struct with - fieldname: variable names of input - value: ts object corresponding to the variable (with data and description) .. index:: ts.pdecomp .. _ts.pdecomp: pdecomp -------- Parametric decomposition into trend, seasonal and irregular components .. index:: filtering :: out=pdecomp(y) out=pdecomp(y,doLog) out=pdecomp(y,doLog,dorder) Args: - **y** (ts): time series to decompose - **doLog** (true \| {false}): if log, do a multiplicative decomposition otherwise the decomposition is additive - **dorder** (integer \| {2}): detrending order Returns: : - **out** [struct] : - **trend** [ts] : estimated trend - **sc** [ts] : estimated seasonal component - **sa** [ts] : seasonally adjusted data - **ic** [ts] : estimated irregular component .. note:: If there are many variables and the variables are named, the first level of the structure will be the names of the different variables. .. seealso:: - ``npdecomp`` .. index:: ts.permute .. _ts.permute: permute -------- Overloaded permute function for ts object .. index:: ts.plot .. _ts.plot: plot ----- Plots a rise time series :: plot(db); plot(daterange,db); plot(daterange,db, varargin); Args: db (ts object): time series object daterange: date range. See ts for different formats varargin: need to come in pairs (except for string format) - s (string): line type, symbol spec, and color spec (same as MATLAB's plot function) - 'nticks': integer (default 8) number of xticks - 'date_format': date format option used in MATLAB. - **vline** [char\|cellstr\|serial dates\|{''}] : vertical line(s) e.g. 'vline' = '2000Q1'= '2000Q1,2003Q2' must be in the same frequency as the database to be plotted - **hline** [integer\|{''}] : horizontal line(s) 'hline' =1, =[1 5.5 2] - **logy** [true\|{false}] : log the database or not Returns: : - **varargout** [scalar\|vector] : handle to the lines of plot Example: :: plot('1994m7:1997m1',db(:,:,1),... 'figsize',[2,2],... 'figtitle','no title',... 'nticks',10,... 'legend',{'v1','v2'},... 'legend_loc','BO',... 'logy',true,... 'secondary_y',{'v1','v4'},... 'subplots',true,... 'linewidth',2,... 'date_format',17); xrotate(90) Note: In addition to those matlab properties, RISE adds further properties, which allow to control for. See parse_plot_args .. index:: ts.plot3 .. _ts.plot3: plot3 ------ PLOT3 Overloaded plot3 function for time series (ts) objects. This function creates three-dimensional line plots for time series (:ref:`ts `) objects by extending MATLAB's `plot3` functionality. It allows for specifying a date range for plotting and supports full customization using name-value pairs. Syntax: plot3(xrange, ts1, ..., 'Name', Value, ...) plot3(ts1, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to plot. If omitted, the entire range of the time series is used. - ts1, ts2, ts3: Three :ref:`ts ` objects to plot. The first :ref:`ts ` provides the x-coordinates, the second provides the y-coordinates, and the third provides the z-coordinates. - Name, Value: Additional name-value pairs to customize the plot. These are passed directly to MATLAB's `plot3` function. Outputs: - varargout: Handles to the graphical objects created by the plot. Features: - Supports 3D plotting for three :ref:`ts ` objects representing x, y, and z data. - Automatically aligns data to a specified date range (`xrange`), if provided. - Maintains compatibility with MATLAB's `plot3` customization options. Examples: % Plot three time series in 3D plot3(ts1, ts2, ts3); % Plot with a specified date range xrange = datetime(2020, 1, 1):datetime(2022, 12, 31); plot3(xrange, ts1, ts2, ts3, 'LineWidth', 2); % Customize the plot plot3(ts1, ts2, ts3, 'Color', 'b', 'LineStyle', '--'); .. seealso:: plot3, ts, utils.plot.myplot .. index:: ts.plot_decomp .. _ts.plot_decomp: plot_decomp ------------ PLOT_DECOMP Create decomposition bar plots with stacked components for time series. This function generates a decomposition plot to visualize how different components contribute to an aggregate time series. Positive and negative contributions are represented as stacked bars, while the total is overlayed as a line plot. The function supports time series (:ref:`ts `) objects and allows filtering data by a date range. It can also be called with a date range (`xrange`) as the first argument to limit the plot to a specific time period. Syntax: plot_decomp(xrange, ts1, ..., 'Name', Value, ...) plot_decomp(ts1, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to plot. If omitted, the entire range of the time series is used. Example: `xrange = rq(2020,1):rq(2022,4);` - ts1 : :ref:`ts ` object where each column represents a component of the decomposition, and each row corresponds to a time point. - Name, Value: Additional name-value pairs to customize the overlayed line plot. These options are passed directly to MATLAB's `plot` function. Outputs: - plot_handle: Handle to the current axes (`gca`), which contains the decomposition bar plot and the overlayed line plot. Features: - Stacked bar visualization for positive and negative contributions. - Overlayed line plot showing the total contribution across time. - Automatic color assignment using a perceptually distinct colormap. Examples: % Create a decomposition plot for a single time series plot_decomp(ts1); % Create a decomposition plot for a specific date range xrange = rq(2020,1):rq(2022,4); plot_decomp(xrange, ts1, ts2, 'LineWidth', 1.5, 'Color', 'r'); % Customize the decomposition plot plot_decomp(ts1, 'LineStyle', '--', 'Marker', 'o'); Notes: - If called with `xrange` as the first argument, it must be a valid date vector or a custom dates object supported by the time series (:ref:`ts `) class. - The function internally uses `utils.plot.myplot` to handle data extraction, alignment, and plotting logic. .. seealso:: utils.plot.myplot, ts .. index:: ts.plot_real_time .. _ts.plot_real_time: plot_real_time --------------- plot_real_time - hairy plot :: plot_handle=plot_real_time(rts) plot_handle=plot_real_time(xrange,rts) plot_handle=plot_real_time(rts,varargin) plot_handle=plot_real_time(xrange,rts,varargin) Args: - **rts** (ts \| rts): valid time series object with possibly several columns and exactly one page - **xrange** : range over which to restrict the plots - **varargin** : valid matlab arguments for plot, coming in pairs Returns: - **plot_handle** : handle to the plot .. index:: ts.plotyy .. _ts.plotyy: plotyy ------- Plot figure with y tick labels on the left and right :: [ax, h1, h2] = plotyy(y1,y2); [ax, h1, h2] = plotyy(xrange, y1, y2); [ax, h1, h2] = plotyy(xrange, y1, y2, func); [ax, h1, h2] = plotyy(xrange, y1, y2, func1, func2); Args: y1 (ts object): time series to plot with left axis tick y2 (ts object): time series to plot with right axis tick xrange: date range to plot. See ts for formats func (string/func-handle): use the function to make the plots instead func1 (string/func-handle): use the function to make the plot for y1 func2 (string/func-handle): use the function to make the plot for y2 Returns: : - ax: axis handle - h1: handle to the graphics object corresponding to y1 - h2: handle to the graphics object corresponding to y2 Example: :: [ax,h1,h2]=plotyy('1994m7:1997m1',... db(:,'v1',1),... db(:,'v2',1),... 'nticks',10,... 'date_format',17) xrotate(90) Note: In addition to those matlab properties, RISE adds further properties, which allow to control for. See parse_plot_args .. index:: ts.plus .. _ts.plus: plus ----- Overloaded + function for ts object .. index:: ts.power .. _ts.power: power ------ Overloaded power function for ts object .. index:: ts.prctile .. _ts.prctile: prctile -------- Compute the percentiles of a time series (ts) Syntax db=prctile(db,p) Args: - db (ts): time series with many pages (third dimension). The time series may have one or several variables. - p (scalar \| vector): scalar or a vector of percent values Returns: - **db** [ts] : time series with as many pages as the length of **p**. Example: test=ts(1990,rand(100,3,200),{'a','b','c'}); tmp=prctile(test,[10,50,90]) plot(tmp('a')) .. index:: ts.quantile .. _ts.quantile: quantile --------- Computes quantile for time series: It is an interface to MATLAB implementation of quantile :: varargout = quantile(db,varargin); Args: db (ts object): times series object varargin: varargin for quantile function in MATLAB Returns: : - **varargout**: output from quantile function .. index:: ts.rand .. _ts.rand: rand ----- Initializes a ts object with the given start data and data initialized to uniform random numbers :: db=ts.rand(start_date,varargin) Args: start_date (numeric \| char): a valid time series (ts) date varargin (numeric): arguments to matlab's **rand** function. Returns: : - **db** : [ts]: a time series Note: - this is a static method and so it has to be called with the **ts.** prefix - ts.rand does not allow more than 3 dimensions Example: :: db=ts.rand(1990,10,1) db=ts.rand('1990',10,3) db=ts.rand('1990Q3',10,5,100) .. index:: ts.randn .. _ts.randn: randn ------ Initializes a ts object with the given start data and data initialized to normal random number :: db=ts.randn(start_date,varargin) Args: start_date (numeric \| char): a valid time series (ts) date varargin (numeric): arguments to matlab's **randn** function. Returns: : - **db** : [ts]: a time series Note: - this is a static method and so it has to be called with the **ts.** prefix - ts.randn does not allow more than 3 dimensions Example: :: db=ts.randn(1990,10,1) db=ts.randn('1990',10,3) db=ts.randn('1990Q3',10,5,100) .. index:: ts.range .. _ts.range: range ------ Overloads Matlab's range for ts objects. returns the range of the values in the time series :: Y = range(this,varargin); Args: this (ts object): time series object varargin : additional matlab arguments for the range function Returns: : - **Y** [numeric]: Difference between maximum and minimum values .. seealso:: - range .. index:: ts.rdivide .. _ts.rdivide: rdivide -------- Overloaded rdivide function for ts object .. index:: ts.real .. _ts.real: real ----- real : overloads real for time series Syntax :: this=real(this); Args: this (ts object): time series object Returns: - **this** (ts object): time series object .. index:: ts.regress .. _ts.regress: regress -------- Linear regression :: [B,BINT,R,RINT,STATS] = regress(this,this2) [B,BINT,R,RINT,STATS] = regress(this,this2,varargin) Args: - **this** (ts): left-hand-side variable - **this2** (ts): right-hand-side variables - **varargin** (comma separated): additional inputs for Matlab's REGRESS function Returns: - **B**: vector of regression coefficients in the linear model Y = X\*B. - **BINT**: of 95% confidence intervals for B - **R**: vector of residuals - **RINT**: matrix of intervals that can be used to diagnose outliers. If RINT(i,:) does not contain zero, then the i-th residual is larger than would be expected, at the 5% significance level. This is evidence that the I-th observation is an outlier. - **STATS**: vector containing, in the following order, the R-square statistic, the F statistic and p value for the full model, and an estimate of the error variance. Example:: y = ts(1990,rand(100,1)); % random series X = y(-1)&y(-2)&y(-3); % columns of lags X = ones(X); % add a column of ones [B,BINT,R,RINT,STATS] = regress(y,X) .. index:: ts.rmse .. _ts.rmse: rmse ----- Compute the Root Mean Square Error :: [Rmse,Pe] = rmse(rawdata) Args: rawdata (T x (h+1) x nsim ts): Time series with - T observations - h+1 columns, where the first column represents the actual data and the remaining h columns are forecasts - nsim number of simulations Returns: : - **Rmse** : [h x nsim]. Matrix of root mean square errors - **Pe** : [T x h x nsim ts]. Time series of prediction errors .. index:: ts.rolling .. _ts.rolling: rolling -------- Applies a function to a rolling window of the time series :: h = rolling(db,func,window); h = rolling(db,func,window,varargin); Args: db (ts object): time series object to get data func: function that will apply to the rolling window of the time series. The function is recursively applied to the data t+(1:window) for t=0,1,2,3,...,T-window, where T is the number of observations window: number of observations in the rolling window varargin: additional arguments to func .. index:: ts.scatter .. _ts.scatter: scatter -------- SCATTER Overloaded scatter function for time series (ts) objects. This function creates scatter plots for time series (:ref:`ts `) objects by extending MATLAB's `scatter` functionality. It allows for specifying a date range for plotting and supports full customization using name-value pairs. Syntax: scatter(xrange, ts1, ts2, ..., 'Name', Value, ...) scatter(ts1, ts2, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to plot. If omitted, the entire range of the time series is used. - ts1: A :ref:`ts ` object representing the x-coordinates of the scatter points. - ts2: A :ref:`ts ` object representing the y-coordinates of the scatter points. - Name, Value: Additional name-value pairs to customize the plot. These are passed directly to MATLAB's `scatter` function. Outputs: - varargout: Handles to the graphical objects created by the scatter plot. Features: - Supports scatter plotting for :ref:`ts ` objects, extracting dates and data seamlessly. - Automatically aligns data to a specified date range (`xrange`), if provided. - Fully compatible with MATLAB's `scatter` customization options, including marker size, color, and other properties. Examples: % Basic scatter plot with time series data scatter(ts1, ts2); % Scatter plot with a specified date range xrange = rq(2020,1):rq(2022,4); scatter(xrange, ts1, ts2, 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'g'); % Customize marker appearance scatter(ts1, ts2, 'Marker', 'o', 'SizeData', 36, 'LineWidth', 1.5); .. seealso:: scatter, ts, utils.plot.myplot .. index:: ts.semilogy .. _ts.semilogy: semilogy --------- SEMILOGY Overloaded semilogy function for time series (ts) objects. This function plots time series data on a semi-logarithmic scale (logarithmic y-axis) using MATLAB's `semilogy` function. It extends the standard behavior to handle :ref:`ts ` (time series) objects and allows for specifying a date range for plotting. Syntax: semilogy(xrange, ts1, ..., 'Name', Value, ...) semilogy(ts1, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to plot. If omitted, the entire range of the time series is used. - ts1, ts2, ...: One or more :ref:`ts ` objects to plot. Each :ref:`ts ` object represents a time series, and their data will be plotted against their dates. - Name, Value: Additional name-value pairs to customize the plot. These are passed directly to MATLAB's `semilogy` function. Outputs: - varargout: Handles to the graphical objects created by the plot. Features: - Automatically extracts dates and data from :ref:`ts ` objects. - Supports date-based x-axis formatting and RISE-specific plotting options. - Integrates seamlessly with MATLAB's `semilogy` functionality, allowing customization via name-value pairs. Examples: % Plot a single time series semilogy(ts1); % Plot multiple time series with a date range xrange = rq(2020,1):rq(2022,4); semilogy(xrange, ts1, ts2, 'LineWidth', 2); % Customize the plot semilogy(ts1, 'Color', 'r', 'LineWidth', 1.5); .. seealso:: semilogy, ts, utils.plot.myplot .. index:: ts.set .. _ts.set: set ---- SET Sets properties of the ts object, including 'start' and other properties. Usage: self = set(self, property, value) Inputs: - self: The ts object. - propName: The name of the property to set. This can be: - 'start': Sets the start date of the ts object. - Other properties inherited from the gogetter class, such as 'data', 'varnames', 'description', etc. - value: The new value to assign to the specified property. Outputs: - self: The updated ts object with the specified property set. Notes: - This method overrides the 'set' method from the gogetter class to handle specific properties, such as 'start', for the ts object. - For properties like 'start', it updates the 'firstDateObj' property based on the input value. - For all other properties, the method calls the parent class's set method to handle them. This ensures that inherited properties (e.g., 'data' and others) are managed correctly. Example: obj = set(obj, 'start', rq(1971,2)); % Sets the start date. obj = set(obj, 'data', someData); % Calls the gogetter set method for 'data'. obj = set(obj, 'propertyX', valueX); % Sets another property from gogetter or ts class. .. seealso:: ts, gogetter, get.start .. index:: ts.shift .. _ts.shift: shift ------ SHIFT - return a time series with values shifted along the time axis. :: out = shift(db, k) Args: db (ts): time series. k (integer): number of periods to shift. - k > 0 is a LEAD: out.data(t) = db.data(t+k); the last k rows are NaN-padded. - k < 0 is a LAG: out.data(t) = db.data(t-\|k\|); the first \|k\| rows are NaN-padded. - k = 0 is identity. Returns: out (ts): time series of the same dates and length as db. See also lag, lead. .. index:: ts.sin .. _ts.sin: sin ---- Overloaded sin function for ts object .. index:: ts.sinh .. _ts.sinh: sinh ----- Overloaded sinh function for ts object .. index:: ts.size .. _ts.size: size ----- Computes the size of the data stored in a ts object. See Matlab's size for more detail. .. index:: ts.skewness .. _ts.skewness: skewness --------- Computes skewness for time series: It is an interface to MATLAB implementation of skewness :: varargout = skewness(db,varargin); Args: db (ts object): times series object varargin: varargin for skewness function in MATLAB Returns: : - **varargout**: output from skewness function .. index:: ts.spectrum .. _ts.spectrum: spectrum --------- Computes the spectral density of the data :: [sw,jj,T]=spectrum(this) Args: - **this** (ts object): time series object Returns: - **sw** (matrix\|vector): spectrum of potentially multiple time series in columns - **jj** (vector): range of the spectrum (x-axis) - **T** (integer): number of observations .. index:: ts.stairs .. _ts.stairs: stairs ------- STAIRS Overloaded stairs function for time series (ts) objects. Syntax: stairs(ts1, ...) stairs(xrange, ts1, ...) .. seealso:: stairs, ts, utils.plot.myplot .. index:: ts.std .. _ts.std: std ---- Computes standard deviation for time series: It is an interface to MATLAB implementation of std, but adjusted to handle nan properly :: varargout = std(db,varargin); Args: db (ts object): times series object varargin: varargin for std function in MATLAB Returns: : - **varargout**: output from std function .. index:: ts.stem .. _ts.stem: stem ----- STEM Overloaded stem function for time series (ts) objects. This function creates stem plots for time series (:ref:`ts `) objects by extending MATLAB's `stem` functionality. It allows for specifying a date range for plotting and supports full customization using name-value pairs. Syntax: stem(xrange, ts1, ..., 'Name', Value, ...) stem(ts1, ..., 'Name', Value, ...) Inputs: - xrange: (Optional) A date vector specifying the range of dates to plot. If omitted, the entire range of the time series is used. Example: `xrange = rq(2020,1):rq(2022,4);` - ts1: A :ref:`ts ` object representing the data to be plotted as stems. - Name, Value: Additional name-value pairs to customize the plot. These are passed directly to MATLAB's `stem` function. Outputs: - varargout: Handles to the graphical objects created by the stem plot. Features: - Supports stem plotting for :ref:`ts ` objects, automatically extracting dates and data. - Automatically aligns data to the specified date range (`xrange`), if provided. - Fully compatible with MATLAB's `stem` customization options, including marker and line styles. Examples: % Create a basic stem plot for a time series stem(ts1); % Create a stem plot for a specific date range xrange = rq(2020,1):rq(2022,4); stem(xrange, ts1, 'MarkerFaceColor', 'red', 'LineWidth', 1.5); % Customize the appearance of the stem plot stem(ts1, 'Marker', 'o', 'LineStyle', '--', 'Color', 'blue'); .. seealso:: stem, ts, utils.plot.myplot .. index:: ts.step_dummy .. _ts.step_dummy: step_dummy ----------- Implements a step dummy in the time series Args: start_date: start date of the time series end_date: end date of the time series dummy_start_date: start date of the step dummy Returns: : - **db** (ts object): a time series with zeros from the first observation to the date before the start of the dummy and ones from then on. .. index:: ts.subsasgn .. _ts.subsasgn: subsasgn --------- SUBSASGN - subscripted assignment for ts objects. Mirrors @ts/subsref. Three forms: db.PROP = value - assign to a property (data, varnames, ...). db.VARNAME = rhs - if VARNAME is not a ts property but matches one of the variable names, replace that variable's data. rhs may be a ts (its data field is used after a length/page check) or a numeric array of size (nobs, 1, npages). db(I[,J[,K]]) = rhs - replace the selected sub-time-series. rhs may be a ts of the matching shape, or a numeric array of the matching shape. db{I[,J[,K]]} = rhs - replace the selected raw data block. rhs must be a numeric array matching the selected (nobs, nvars, npages) shape. The legacy single-arg numeric form db{-1} = ... / db(+3) = ... is no longer supported; use lag/lead/shift to build the desired ts first and then assign with db(I,J[,K]) = ... . See also subsref, lag, lead, shift, ts. .. index:: ts.subsref .. _ts.subsref: subsref -------- SUBSREF - subscripted reference for ts objects. The indexing contract is the same as for built-in `table` / `timetable`: db.PROP - access the property PROP (data, dates, frequency, NumberOfObservations, ...). db.VARNAME - if VARNAME is not a ts property but matches one of the variable names, returns the corresponding single-variable ts. Equivalent to db('VARNAME'). db(I) - return a SUB-TIME-SERIES selected by I. I may be a variable name (char) or list of names (cellstr) to select columns; a date string ('1991Q1', '1991Q1:1992Q4', ':') or a rise_dates.dates array to select rows; or a logical row mask. db(ROWS, VARS) - rectangular sub-ts (rows = dates/date strings/ logical; vars = names/positions/':'). db(ROWS, VARS, P) - cubic sub-ts (P = page indices, ':', or a function handle filtering pages by predicate). db{I} - same selection as db(I) but returns the raw numeric block (a nobs x nvars x npages double). Use this when you want to feed the values into a numeric routine; use db(I) when you want to stay in the ts world. **Time-shift shortcut (dated time series only).** db{-k} db(-k) equivalent to lag(db, k) on a DATED ts. db{+k} db(+k) equivalent to lead(db, k) on a DATED ts. db{0} db(0) identity (returns db unchanged). The shortcut is **dated-only**: it fires when the argument is a single real-integer scalar AND db's date axis is a rise_dates.dates array (i.e. quarterly, monthly, daily, ... - anything but undated). The returned value is a ts (NaN-padded by shift()), so it composes naturally with ts arithmetic: growth = db.gdp / db.gdp{-1}; % q/q gross growth yoy_l = db.cpi - db.cpi{-4}; % year-over-year difference, quarterly For UNDATED ts (built with ts(integer, data)), a scalar integer in the braces is NOT a shift - it is an implicit date value. db{1990} on ts(1990, data) returns the row whose date value is 1990 (i.e. row 1). This is consistent with the rule "single numeric argument is the date" because the date values of an undated ts are themselves integers. Use lag/lead/shift explicitly if you want a shift on an undated ts. Examples: db = ts('1990q1', randn(10,4,3), {'v1','v2','v3','v4'}); db.v1 % single-variable ts (dot access) db('v1') % same, sub-ts form db{'v1'} % raw double array, 10x1x3 db({'v1','v3'}) % sub-ts with two columns db('1991Q1') % single-row sub-ts db('1991Q1:1992Q4', {'v1','v2'}) db(:, :, 1) % first page only, as a sub-ts db{:, :, 1} % first page as a 10x4 double db{-1} % == lag(db, 1) on a dated ts db.v1{-1} % == lag(db.v1, 1) db.v1 / db.v1{-1} % q/q gross growth, stays a ts See also subsasgn, lag, lead, shift, ts. .. index:: ts.sum .. _ts.sum: sum ---- Overloaded sum function for ts object .. index:: ts.tail .. _ts.tail: tail ----- Returns the last few sample dates of the time series Syntax: db = tail(db); db = tail(db,n); Args: - db (ts object): time series object - n (integer): number of time steps to show Returns: - **db** (ts object): time series with the last n-time steps Note: - This is similar to the tail function in stata. .. index:: ts.times .. _ts.times: times ------ Overloaded times function for ts object .. index:: ts.transform .. _ts.transform: transform ---------- TRANSFORM - apply a standard time-series transformation (level, growth, log change, ...) following the Haver mnemonics. :: out = transform(db, type) Args: db (ts): time series. type: transformation to apply. Available types: - 1 or 'level' : untransformed level (default) - 2 or 'pct_ch_ar' : percentage change at compound annual rate - 3 or 'pct_ch' : period-to-period percentage change - 4 or 'yoy_pct_ch' : year-over-year percentage change - 5 or 'diff' : period-to-period difference - 6 or 'yoy_diff' : year-over-year difference - 7 or 'log_ch_ar' : log change at compound annual rate - 8 or 'log_ch' : period-to-period log change (x100) - 9 or 'yoy_log_ch' : year-over-year log change (x100) Returns: out (ts): transformed time series. The dates are preserved; the leading rows for which the transformation requires unavailable past observations are filled with NaN (use [[lag]] / [[lead]] semantics). See also lag, lead, shift. .. index:: ts.ts .. _ts.ts: ts --- Constructor for the time series (ts) object self=ts(); % construct a time series with no observations self=ts(start_date,data); self=ts(start_date,data,varnames); self=ts(start_date,data,varnames,description); self=ts(start_date,data,varnames,description,trailnans); Args: start_date (integer \| char \| serial date): start date of the time series. The following are admitted: - annual data : - '1990'\|ry('1990')\|ra('1990') - ry(1990)\|ra(1990) - ry(datenum)\|ra(datenum) - ry('mm/dd/yyyy')\|ra('mm/dd/yyyy') - ry('yyyy-mm-dd')\|ra('yyyy-mm-dd') - bi-annual data : - '1990H1'\|rh('1990H1')\|rh(1990,1) - rh(datenum) - rh('mm/dd/yyyy')\|rh('yyyy-mm-dd') - Quarterly data : - '1990Q1'\|rq('1990Q1')\|rq(1990,1) - rq(datenum) - rq('mm/dd/yyyy')\|rq('yyyy-mm-dd') - monthly data : - '1990M1'\|rm('1990M1')\|rm(1990,1) - rm(datenum) - rm('mm/dd/yyyy')\|rm('yyyy-mm-dd') - Weekly data : - '1990W1'\|rw('1990W1')\|rw(1990,1) - rw(datenum) - rw('mm/dd/yyyy')\|rw('yyyy-mm-dd') - Daily data : - '1990D1'\|rd('1990D1')\|rd(1990,12,31) - rd(datenum) - rd('mm/dd/yyyy')\|rd('yyyy-mm-dd') data (numeric): the format is nobs x nvars x npages, where: - **nobs** is the number of observations - **nvars** is the number of variables - **npages** is the number of pages (3rd dimension) varnames (char \| cellstr): names of the variables in the database description (char \| cellstr \| {''}): comments on each variable in the database trailnans (true\|{false}): keep or remove nans (missing observations) Returns: - **self** [ts] : time series Documentation for ts/ts helpwin ts .. index:: ts.uminus .. _ts.uminus: uminus ------- Overloaded uminus function for ts object .. index:: ts.unfold .. _ts.unfold: unfold ------- Takes a folded times series and turns it into a one-page time series :: this=unfold(last_hist_date,obj) this=unfold(last_hist_date,obj1,obj2,...,objn) Args: last_hist_date (char \| serial date): obj (ts): time series Returns: : - **this** [ts]: unfolded time series .. index:: ts.values .. _ts.values: values ------- Returns the underlying data of the time series :: data = value(db); Args: - **db** (ts object): time series object Returns: - **d** (double): vector/matrix/tensor form of the data underlying the time series .. index:: ts.var .. _ts.var: var ---- Computes variance for time series: It is an interface to MATLAB implementation of var adjusted to handle nan properly :: varargout = var(db,varargin); Args: db (ts object): times series object varargin: varargin for var function in MATLAB Returns: : - **varargout**: output from var function .. index:: ts.zeros .. _ts.zeros: zeros ------ Initializes a ts object with the given start data and data initialized to zeros :: db=ts.zeros(start_date,varargin) Args: start_date (numeric \| char): a valid time series (ts) date varargin (numeric): arguments to matlab's **zeros** function. Returns: : - **db** : [ts]: a time series Note: - this is a static method and so it has to be called with the **ts.** prefix - ts.zeros does not allow more than 3 dimensions Example: :: db=ts.zeros(1990,10,1) db=ts.zeros('1990',10,3) db=ts.zeros('1990Q3',10,5,100)