1. Time Series and Data Management
1.1. Dates
In the RISE toolbox, dates play a crucial role in representing time series data. Dates can be either explicit, where each observation is associated with a specific date, or undated, where dates are simply represented as a sequence of integers.
To handle dates efficiently, RISE provides an abstract class
called rise_dates.dates, from which various derived classes
inherit. These derived classes include:
rise_dates.DailyDate(shortcut:rd)rise_dates.WeeklyDate(shortcut:rw)rise_dates.MonthlyDate(shortcut:rm)rise_dates.QuarterlyDate(shortcut:rq)rise_dates.HalfYearlyDate(shortcut:rh)rise_dates.YearlyDate(shortcuts:ryorra)
Each derived class represents a specific frequency.
A date object holds one date. A date of a period is the last day of
that period (March 31 for 1990Q1). A week runs from Sunday to
Saturday and a weekly date is its Saturday: week 1 of a year is the
week of January 1st, and the label of a week is the year of its
Saturday followed by its rank in that year. For instance rw(2021,1)
is the week ending Saturday January 2, 2021, labeled 2021W01,
and rw('12/29/2020') is that same week. Build a range of dates
with the colon operator, e.g. rd(2023,1,1):rd(2023,1,3).
1.1.1. Base Class Methods
The base class rise_dates.dates provides several methods that
can be used with any derived class:
char()– converts dates to character representations.convert()– converts dates to another frequency.datestr()– returns a string representation of dates.eq()– equality check.gt(),ge(),lt(),le()– comparisons.ismember()– membership test.min(),max()– minimum / maximum date.ne()– inequality check.unique()– unique dates in a sequence.colon()– creates a sequence of dates.double()– converts dates to double format.intersect()– intersection of two sets of dates.minus(),plus()– date arithmetic.ymd()– extracts year, month, day components.
char and datestr write the labels of the frequency
(2020Q1, 2021W01, 03/04/2021). Given a format, a
datetime display format, they write the day that represents each
date instead: the last day of its period, the Saturday of a week:
datestr(rq(2020,1),'yyyy-MM-dd') % '2020-03-31'
char(rm(2021,1):rm(2021,2),'MM/yyyy')
In the format, MM is the month and mm the minutes.
When passing a date to an estimation option (estim_start_date,
estim_end_date, …), use date2serial to convert the char
form to the numeric / rise_dates.dates form the modern
validators accept:
estim_start_date = date2serial('1990Q1')
1.1.2. Help Text for Derived Classes
Daily dates: rd
RD DailyDate constructor.
Usage:
- obj = rd(year, month, dayOfTheMonth) creates a
rd object for the specified year, month, and day.
- obj = rd(year, dayOfTheYear) creates a rd
object for the specified year and day of the year.
- obj = rd(dateString) creates a rd object from
a string in the format ‘mm/dd/yyyy’ or ‘yyyyDddd’ or ‘yyyy-mm-dd’.
- obj = rd(dateNumber) creates a rd object from
a serial date number.
Inputs:
year: Year of the date.
month: Month of the date.
dayOfTheMonth: Day of the month.
dayOfTheYear: Day of the year.
dateString: A string in the format ‘mm/dd/yyyy’ or ‘yyyyDddd’.
dateNumber: A serial date number representing the date.
Example:
dateObj = rd(2023, 7, 15);
dateObj = rd(2023, 165);
dateObj = rd(‘07/15/2023’);
dateObj = rd(‘2023D165’);
dateObj = rd(737999);
See also rd, rw, rm, rq, rh, ra, ry
Weekly dates: rw
RW constructor.
Usage:
obj = rw(year, fullWeeks)
obj = rw(dateString)
obj = rw(datenumber)
Inputs:
year: Year of the date.
fullWeeks: Week of the year, from 1 to 52 or 53. A week runs from Sunday to Saturday and a weekly date is the Saturday that closes its week. Week 1 is the week of January 1st and the label of a week is the year of its Saturday followed by its rank in that year: rw(2021,1) is the week ending Saturday January 2, 2021, labeled 2021W01. A week number beyond the last week of the year is clamped to the last week, with a warning.
dateString: A string in the format ‘mm/dd/yyyy’ or ‘yyyyWp’ or ‘yyyy-mm-dd’.
Example:
dateObj = rw(2023, 10);
dateObj = rw(‘07/01/2023’);
dateObj = rw(‘1990W1’);
dateObj = rw(737999);
See also rd, rm, rq, rh, ra, ry
Monthly dates: rm
RM constructor.
Usage:
obj = rm(year, month)
obj = rm(dateString)
obj = rm(datenumber)
Inputs:
year: Year of the date.
month: Month of the date (1 to 12).
dateString: A string in the format ‘mm/dd/yyyy’ or ‘yyyy-mm-dd’.
datenumber: regular date number
Example:
dateObj = rm(2023, 7);
dateObj = rm(‘07/01/2023’);
dateObj = rm(737999);
See also rd, rw, rq, rh, ra, ry
Quarterly dates: rq
RQ constructor.
Usage:
obj = rq(year, quarter)
obj = rq(dateString)
obj = rq(datenumber)
Inputs:
year: Year of the date.
quarter: Quarter of the date (1, 2, 3, or 4).
dateString: A string in the format ‘mm/dd/yyyy’ or ‘yyyyQp’ where p=1,2,3,4 or ‘yyyy-mm-dd’
Example:
dateObj = rq(2023, 2);
dateObj = rq(‘2023Q2’);
dateObj = rq(‘04/01/2023’);
dateObj = rq(737999);
See also rd, rw, rm, rh, ra, ry
Half-yearly dates: rh
RH constructor.
Usage:
obj = rh(year, semi)
obj = rh(dateString)
obj = rh(datenumber)
Inputs:
year: The year of the date.
semi: The semi-annual period (1 or 2).
dateString: A string in the format ‘mm/dd/yyyy’ or ‘yyyyHp’ where p=1,2 or ‘yyyy-mm-dd’.
datenumber: regular date number
Example:
dateObj = rh(2023, 1);
dateObj = rh(‘2023H1’);
dateObj = rh(‘01/01/2023’);
dateObj = rh(737999);
See also rd, rw, rm, rq, ra, ry
Yearly dates: ry
RY constructor for YearlyDate.
Usage:
obj = ry(year)
obj = ry(dateString)
dateObj = ry(datenumber);
Inputs:
year: Year of the date in double (e.g., 2023)
dateString: A string in the format ‘mm/dd/yyyy’ or ‘yyyy’ or ‘yyyy-mm-dd’
datenumber: A regular matlab datenumber. Note that the function will treat the input as a date number if it has more than 4 digits. A warning will be issued as well
Example:
dateObj = ry(2023);
dateObj = ry(‘2023’);
dateObj = ry(‘01/01/2023’);
dateObj = ry(737999);
See also rd, rw, rm, rq, rh, ra.
Annual dates: ra
RA constructor for YearlyDate.
Usage:
obj = ra(year)
obj = ra(dateString)
dateObj = ra(datenumber);
Inputs:
year: Year of the date in double (e.g., 2023)
dateString: A string in the format ‘mm/dd/yyyy’ or ‘yyyy’ or ‘yyyy-mm-dd’
datenumber: A regular matlab datenumber. Note that the function will treat the input as a date number if it has more than 4 digits. A warning will be issued as well
Example:
dateObj = ra(2023);
dateObj = ra(‘2023’);
dateObj = ra(‘01/01/2023’);
dateObj = ra(737999);
See also rd, rw, rm, rq, rh, ry
1.2. Time Series
This section provides information about time series and their usage in the context of the RISE toolbox.
Time series data in essence is just a matrix, so in theory one
can just use matrices to represent the data. However, all
practitioners will share their frustration in trying to remember
the index location of the GDP and the annoyance in trying to
find out what data(:, 5) written by a co-worker represents.
The RISE toolbox addresses this problem by providing a time
series object that uses natural indices, improving readability
and reducing errors.
To use the time series object, initialize it with:
db = ts('1990q1', randn(10, 4), {'gdp','r','wage','capital'})
The first argument specifies the starting date of the time series and its frequency (here, 1990Q1). The second argument is the data matrix, where each row represents a time period and each column represents a variable. The third argument provides the natural names of the variables for intuitive indexing.
The first argument can also be a vector of increasing dates, one per row of data: each row is then placed at its own date, and the dates missing from the vector become NaN observations:
d = rd('2021-01-01'); d(2) = rd('2021-01-04');
db = ts(d, [1; 2]) % January 1 to 4, NaN on the 2nd and the 3rd
If you want to provide descriptions or comments for each variable:
db = ts('1990q1', randn(10, 2), {'gdp','pi'}, {'real gdp','inflation rate'})
You can display the time series with:
disp(db)
Alternatively, set variable names and descriptions with set.
A time series is a value object: set returns the modified copy,
and db changes only if you assign the result to it:
db=set(db,'varnames',{'gdp','pi'},'description',{'real gdp','inflation rate'});
1.2.1. Indexing and assignment
The indexing surface of the time series object mirrors the
built-in table / timetable conventions, so that users
familiar with those classes feel at home, and the distinction
between “sub-time-series” and “raw values” is explicit.
Expression |
Result |
|---|---|
|
a property of the ts ( |
|
if |
|
a sub-time-series (returns a ts). |
|
the raw numeric block at that selection (a double array of size |
|
(dated ts only, |
|
replace one variable’s column from a ts or a numeric column. |
|
replace a sub-time-series (rhs ts or numeric). |
|
raw numeric block write. |
Scalar-numeric assignment (db{-1} = X, db(-1) = X) is
not supported. The time-shift shortcut is read-only; build the
shifted ts first and assign with a date or logical selector if
you need to write into it.
Examples:
db = ts('1990q1', randn(10, 4), {'gdp','r','wage','capital'});
% Access values
db.wage % single-variable ts
db('wage') % same, sub-ts form
db{'wage'} % raw 10x1 double array
% Slice rows and columns
db('1991q2', 'wage') % single observation, as a ts
db{'1991q2', 'wage'} % the same value as a 1x1 double
db('1990q2:1991q2', {'gdp','wage'}) % sub-ts (5 rows, 2 vars)
db{:, {'gdp','wage'}} % full sample, two vars, as a 10x2 double
% Whole-year selection works across frequencies
db(ry(1991)) % the 4 quarters of 1991, as a ts
% Underlying data, when you need plain MATLAB
values(db) % equivalent to db.data
Time shifts (lags and leads) are expressed either with the
explicit methods lag(db, k), lead(db, k), shift(db, k)
or, on a dated ts, with the brace/paren shortcut. Both preserve
the date axis – the leading or trailing k observations are
NaN-padded so that the length of the output equals the length of
the input. The two forms are equivalent on a dated ts:
growth = 100*(db.gdp / lag(db.gdp, 1) - 1); % q/q growth, % terms
growth = 100*(db.gdp / db.gdp{-1} - 1); % same thing, shorter
On an undated ts the shortcut is unavailable (a scalar numeric in
the braces is treated as the date value itself); use lag,
lead, shift explicitly there.
Elementwise functions (log, exp, abs, apply, …)
and arithmetic with numbers (db+1, 100*db) keep the names
and the descriptions of the variables. Arithmetic between two time
series works on their common dates; the result keeps the names
(and the descriptions) when the two series have the same ones, and
has unnamed variables otherwise:
db = ts('1990q1', rand(10,2)+1, {'gdp','pi'});
ldb = log(db); % still gdp and pi
d = db.gdp - db.pi; % one unnamed variable
The time series object seamlessly integrates with other parts of the RISE toolbox, enabling you to perform VAR and DSGE analyses effortlessly.
1.2.2. Getting data from FRED
fetch_fred downloads current observations and series metadata without a
key by default:
db=fetch_fred({'GDPC1','UNRATE'});
opts=struct('observation_start','2019-01-01','observation_end','2020-12-31');
bounded=fetch_fred('UNRATE',opts);
The keyless route reads observations from the public graph CSV and metadata
from the public data page. If the CSV cannot be retrieved or parsed, it uses
the data-page observation table. Missing values represented by . or empty
CSV fields become NaN. Each observation retains its own date; gaps become
missing periods in the RISE time series. Its constructor retains its existing
trimming of leading and trailing missing values.
The output fields retain their existing shapes: fetch_fred returns
header, Title, Frequency and series. The extended interface
returns SeriesID, Title, Frequency, Units, DateRange and a
timetable in Data:
detail=fetch_fred_extended('UNRATE','',opts);
If the metadata page is unavailable or cannot be parsed, a warning names the
series and the data is still returned. Metadata fields are empty and frequency
is inferred from the complete date sequence before applying date bounds.
An isolated observation has no inferable cadence and uses a daily date.
The bounds observation_start and observation_end are inclusive and
applied locally on either route, using yyyy-MM-dd text.
An explicit API key takes precedence over FRED_API_KEY. An empty or
omitted key reads the environment and uses the keyless route if it is unset:
setenv('FRED_API_KEY',myKey);
db=fetch_fred('UNRATE');
explicit=fetch_fred('UNRATE',myKey);
setenv('FRED_API_KEY','');
setenv affects the current MATLAB process. To persist the setting, add a
user environment variable named FRED_API_KEY through the operating system
and restart MATLAB. No credential belongs in the source files. A supplied key
uses the existing FRED metadata and observation API; see the FRED observation
API.
The keyless header Last Updated value uses the API-style 24-hour clock
and numeric UTC offset (CDT is -05:00, CST is -06:00). The public page
has minute precision: seconds are set to :00 by convention. Unrecognized
timestamp text is retained with a warning; the authenticated API timestamp
is unchanged. The optional live equivalence test requires a newly supplied
FRED_API_KEY and compares timestamps to the minute. It skips when no key
or network is available; synthetic API-shaped fixtures remain labeled as such.
1.2.3. Data Cleaning
db=set(db,'data',newData)– replaces the data (as many variables asdbhas names).db=set(db,'start',newDate)– moves the start date.interpolate– fills in missing data.newdb=convert(db,newFrequency,squash)– changes the frequency ('D','W','M','Q','H','Y'). Going to a lower frequency aggregates the observations of each period withsquash(a function handle or name, defaultmean); going to a higher one places each observation at its date and leaves the other datesNaN.ts.dummy– creates a dummy variable.ts.step_dummy– creates a step-dummy variable.cat– joins multiple time series objects.
1.2.4. Time Series Transformations
hpfilter– the Hodrick-Prescott filter.ma_filter– a moving-average filter.pdecomp– parametric trend-seasonal-residual decomposition.npdecomp– non-parametric trend-seasonal-residual decomposition. It needs 6 observations of each season (6 years of data) and 13 observations in all.transform– standard time-series transformations (level, growth, difference, log change, year-over-year variants), following the Haver mnemonics.
1.2.5. Time shifts
These methods preserve the date axis – the leading or trailing
k rows are NaN-padded so that length(out) == length(db):
lag(db, k)– lag byk.out.data(t,:,:) = db.data(t-k,:,:).lead(db, k)– lead byk.out.data(t,:,:) = db.data(t+k,:,:).shift(db, k)– generic shift. Positivekis a lead, negative is a lag.
On a dated ts these are also available as the shortcut
db{-k} / db(-k) (lag) and db{+k} / db(+k) (lead) –
see Indexing and assignment above.
1.2.6. Statistical Analysis
regress– OLS regression on the time series data.chowlin– temporal disaggregation via Chow-Lin (interpolates a low-frequency series to high frequency using one or more related indicators).jbtest– Jarque-Bera test.rolling(db,func,window)– appliesfuncto every window ofwindowconsecutive observations; the window is a positive integer no larger than the number of observations, and the result starts at the end of the first window.expanding(db,func)– appliesfuncto the observations from the first one to each date.spectrum– the periodogram at the Fourier frequencies, for a sample without missing values inside it.
1.2.7. Plotting tools for time series
bar– bar plot.fanchart– fan chart.plot– plot the time series data.plot_real_time– plot in real-time-conditioning format.plotyy– plot with two separate axes.
See Plotting tools for the broader plotting surface.