| Type: | Package |
| Title: | Modified and Fully Modified Hodrick-Prescott Filters |
| Version: | 1.0.0 |
| Date: | 2026-11-05 |
| Description: | Decomposes macroeconomic time series into trend and cycle with the Hodrick-Prescott (HP) filter and two data-driven versions of it. The modified HP filter of McDermott (1997), assessed by Choudhary, Hanif and Iqbal (2014) <doi:10.1080/00036846.2014.894631>, chooses the smoothing parameter of every series by generalised cross-validation (as described in Coe and McDermott (1997) <doi:10.2307/3867497>). The fully modified HP filter of Hanif, Iqbal and Choudhary (2017, State Bank of Pakistan Working Paper 88) also reduces the end-point bias of the HP filter: it raises the smoothing parameter at the first and last observations, with linear or quadratic weights chosen to minimise the loss of Bloechl (2014, University of Munich Discussion Paper 2014-1). Every filter is a banded linear solve, so the searches are fast; batch processing of many series, comparisons of the filters, the filter weights, gain functions and end-point loss, simulation of trend-plus-cycle series and the power comparison of the paper, 'ggplot2' graphics, a plain-language interpretation of every result and a built-in 'shiny' application. |
| License: | MIT + file LICENSE |
| URL: | https://myaseen208.com/mhpfilter/, https://github.com/myaseen208/mhpfilter |
| BugReports: | https://github.com/myaseen208/mhpfilter/issues |
| Encoding: | UTF-8 |
| Language: | en-US |
| LazyData: | true |
| Depends: | R (≥ 4.2) |
| Imports: | data.table, ggplot2, grDevices, Rcpp, scales, stats, utils |
| LinkingTo: | Rcpp, RcppArmadillo |
| Suggests: | bslib, DT, knitr, magick, pkgload, quarto, ragg, R.rsp, shiny, svglite, testthat (≥ 3.0.0), withr |
| VignetteBuilder: | quarto, R.rsp |
| Config/testthat/edition: | 3 |
| Config/skill/prefix: | mhp |
| RoxygenNote: | 7.3.1 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-09 02:26:15 UTC; myaseen208 |
| Author: | Muhammad Yaseen |
| Maintainer: | Muhammad Yaseen <myaseen208@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-09 08:50:09 UTC |
mhpfilter: Modified and Fully Modified Hodrick-Prescott Filters
Description
mhpfilter splits a macroeconomic time series into a trend and a cycle with the filter of Hodrick and Prescott (1997) and with two versions whose settings come from the data: the modified HP filter of McDermott (1997), which chooses the smoothing parameter of each series by generalised cross-validation (Choudhary, Hanif and Iqbal 2014), and the fully modified HP filter of Hanif, Iqbal and Choudhary (2017), which also reduces the bias of the HP filter at the ends of the series by raising the smoothing parameter there, with weights that minimise the end-point loss of Bloechl (2014).
Details
Functions, in the order of an analysis:
-
hp_filter,mhp_filter,fmhp_filter: the three filters. -
mhp_batch,fmhp_batch: many series at once. -
mhp_compare,batch_compare,fmhp_compare: the filters compared, by the moments of the cycles and the end-point loss. -
hp_weights,hp_gain,hp_loss,hp_schedule: the weights, gains and end-point loss of any HP-type filter. -
mhp_designs,mhp_simulate,fmhp_simulation: simulated series and the power comparison of the paper. -
autoplot.mhp,plot_comparison,plot_batch: graphics;get_lambda,get_gcv: accessors. -
mhp_interpret,mhp_cite: a plain-language interpretation and the references of a result;mhp_app: the built-in application.
Every filter is an S3 generic with a .default method. With as_dt = TRUE (the default) the filters
return a data.table, as in version 0.1.0; with as_dt = FALSE a list with a class and the methods of
mhp-methods. Utilities: mhp_theme, mhp_save, mhp_notation,
mhp_reference.
Data. us_macro: quarterly real GDP, consumption and investment of the United States,
1959 to 2009.
Vignettes. Start with vignette("mhpfilter_01_getting_started", package = "mhpfilter");
browseVignettes("mhpfilter") lists all of them, in HTML and PDF.
Notation
Scalars are upper-case letters in normal face, indices lower-case italic, vectors lower-case bold and matrices
upper-case bold; Greek letters follow the same rule. The full table is mhp_notation().
T | number of observations |
\mathbf{x}, \mathbf{g}, \mathbf{c} | series, trend and cycle |
\mathbf{K}, \mathbf{A} = \mathbf{K}^\top\mathbf{K} | second differences and the penalty matrix |
\mathbf{B} | smoother (filter weights) |
\lambda, \lambda_t | smoothing parameter(s) |
\alpha, k | end-point weight and number of end values |
P_t(\omega), l(t), L | gain, loss and total loss |
Author(s)
Muhammad Yaseen (myaseen208@gmail.com), ORCID 0000-0002-5923-1714.
References
Bloechl, A. (2014). Reducing the excess variability of the Hodrick-Prescott filter by flexible penalization. Discussion Paper 2014-1, University of Munich.
Choudhary, M. A., Hanif, M. N. and Iqbal, J. (2014). On smoothing macroeconomic time series using the modified HP filter. Applied Economics, 46(19), 2205–2214. doi:10.1080/00036846.2014.894631
Hanif, M. N., Iqbal, J. and Choudhary, M. A. (2017). Fully modified HP filter. SBP Working Paper Series, No. 88, State Bank of Pakistan.
Hodrick, R. J. and Prescott, E. C. (1997). Postwar U.S. business cycles: an empirical investigation. Journal of Money, Credit and Banking, 29(1), 1–16. doi:10.2307/2953682
McDermott, C. J. (1997). An automatic method for choosing the smoothing parameter in the HP filter. Unpublished, International Monetary Fund, Washington DC.
See Also
Plot the decomposition of a series
Description
autoplot() (and plot()) of a filter result draws the series with its trend and, below, the cycle,
with the time of a ts on the horizontal axis. For the modified HP filter which = "gcv" draws the
criterion against \lambda; for the fully modified HP filter which = "lambda" draws the
smoothing parameters \lambda_t and which = "loss" the end-point loss.
Usage
autoplot.mhp(object, which = c("decomposition", "gcv", "lambda", "loss"), ...)
Arguments
object |
a result of |
which |
|
... |
not used. |
Value
A ggplot object.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
Examples
data(us_macro)
f <-
fmhp_filter(
x = us_macro$gdp
, max_lambda = 3000
, k_linear = 15
, k_quadratic = NULL
, alpha_linear = seq(from = 0, to = 2000, by = 10)
, alpha_quadratic = seq(from = 0, to = 2000, by = 5)
, schemes = c("linear", "quadratic")
, form = "rows"
, lambda = NULL
, log_scale = TRUE
, as_dt = FALSE
)
ggplot2::autoplot(object = f)
plot(x = f, which = "lambda")
Fully modified HP filter of many series
Description
fmhp_batch() applies fmhp_filter() to every column of a matrix or data frame, as
mhp_batch() does for the modified HP filter.
Usage
fmhp_batch(
X,
max_lambda = 3000L,
k_linear = 15L,
k_quadratic = NULL,
alpha_linear = seq(0, 2000, 10),
alpha_quadratic = seq(0, 2000, 5),
schemes = c("linear", "quadratic"),
form = c("rows", "differences"),
lambda = NULL,
log_scale = TRUE
)
## Default S3 method:
fmhp_batch(
X,
max_lambda = 3000L,
k_linear = 15L,
k_quadratic = NULL,
alpha_linear = seq(0, 2000, 10),
alpha_quadratic = seq(0, 2000, 5),
schemes = c("linear", "quadratic"),
form = c("rows", "differences"),
lambda = NULL,
log_scale = TRUE
)
Arguments
X |
a numeric matrix or data frame, one series per column; missing values only at the start or the end. |
max_lambda |
the largest |
k_linear |
number of end values with linear weights (default 15). |
k_quadratic |
number of end values with quadratic weights (default |
alpha_linear, alpha_quadratic |
the grids of the weight |
schemes |
the schemes compared: |
form |
|
lambda |
|
log_scale |
filter the logarithm of the series (default |
Value
A data.table with the columns series, t, original, trend,
cycle and the attribute lambdas, a data.table with series, lambda,
gcv, lambda_mhp, scheme, alpha, k and loss.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
fmhp_filter, mhp_batch, plot_batch
Examples
data(us_macro)
X <- as.matrix(us_macro[, c("gdp", "consumption", "investment")])
fb <-
fmhp_batch(
X = X
, max_lambda = 3000
, k_linear = 15
, k_quadratic = NULL
, alpha_linear = seq(from = 0, to = 2000, by = 10)
, alpha_quadratic = seq(from = 0, to = 2000, by = 5)
, schemes = c("linear", "quadratic")
, form = "rows"
, lambda = NULL
, log_scale = TRUE
)
attr(x = fb, which = "lambdas")
Compare the HP, modified HP and fully modified HP filters
Description
fmhp_compare() filters one series with the three filters and compares their cycles and their end-point
loss (Hanif et al. 2017, Tables 3a and 3b): the HP filter at the conventional \lambda of the
frequency, the modified HP filter and the fully modified HP filter.
Usage
fmhp_compare(
x,
frequency = c("quarterly", "annual", "monthly"),
max_lambda = 3000L,
log_scale = TRUE,
end_share = 0.1
)
## Default S3 method:
fmhp_compare(
x,
frequency = c("quarterly", "annual", "monthly"),
max_lambda = 3000L,
log_scale = TRUE,
end_share = 0.1
)
Arguments
x |
a numeric vector or a |
frequency |
|
max_lambda |
the largest |
log_scale |
filter the logarithm of the series (default |
end_share |
share of the observations counted as ends on each side (default 0.1, as in Table 2 of the paper). |
Details
Besides the moments of mhp_compare(), the table gives the total loss L of each filter
(hp_loss()), its standard deviation of the cycle at the ends (the first and last
end_share of the observations) and in the middle. A filter without end-point bias has a loss near zero and
about the same cycle variability at the ends as in the middle.
Value
A data.table with one row per filter (HP, Modified HP, Fully modified HP) and
the columns method, lambda, cycle_sd, cycle_mean, ar1, cycle_range,
gcv, loss, sd_ends, sd_middle.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
fmhp_filter, mhp_compare, hp_loss
Examples
data(us_macro)
fc <-
fmhp_compare(
x = us_macro$gdp
, frequency = "quarterly"
, max_lambda = 3000
, log_scale = TRUE
, end_share = 0.1
)
fc
Fully modified Hodrick-Prescott filter
Description
fmhp_filter() applies the fully modified HP (FMHP) filter of Hanif, Iqbal and Choudhary (2017). It removes
the two weaknesses of the HP filter at once: the smoothing parameter is chosen from the data (as in the modified
HP filter of McDermott 1997), and the end-point bias is reduced by raising the smoothing parameter at the first
and last k observations, with weights chosen to minimise the loss of Bloechl (2014), the distance of the
gain of every estimate from the gain at the centre of the series.
Usage
fmhp_filter(
x,
max_lambda = 3000L,
k_linear = 15L,
k_quadratic = NULL,
alpha_linear = seq(0, 2000, 10),
alpha_quadratic = seq(0, 2000, 5),
schemes = c("linear", "quadratic"),
form = c("rows", "differences"),
lambda = NULL,
log_scale = TRUE,
as_dt = TRUE
)
## Default S3 method:
fmhp_filter(
x,
max_lambda = 3000L,
k_linear = 15L,
k_quadratic = NULL,
alpha_linear = seq(0, 2000, 10),
alpha_quadratic = seq(0, 2000, 5),
schemes = c("linear", "quadratic"),
form = c("rows", "differences"),
lambda = NULL,
log_scale = TRUE,
as_dt = TRUE
)
Arguments
x |
a numeric vector or a |
max_lambda |
the largest |
k_linear |
number of end values with linear weights (default 15). |
k_quadratic |
number of end values with quadratic weights (default |
alpha_linear, alpha_quadratic |
the grids of the weight |
schemes |
the schemes compared: |
form |
|
lambda |
|
log_scale |
filter the logarithm of the series (default |
as_dt |
|
Details
Gain and loss. Row t of the smoother \mathbf{B} holds the weights of
\hat{g}_t; its gain at frequency \omega is
P_t(\omega) = \left|\sum_{j=1}^{T} b_{tj}\,e^{i\omega(j - t)}\right|
(Hanif et al. 2017, eq. 6), and the loss of the estimate is l(t) = \theta\sum_{\omega}[P_c(\omega) -
P_t(\omega)]^2 over \omega = 0, 0.1, \dots,
3.1 with \theta = 0.1 and c the centre of the series
(eq. 7); the total loss is L = \sum_t l(t) (eq. 8). See hp_loss().
End-point weights. The smoothing parameter of observation t is \lambda_t = \lambda in the middle and \lambda + \alpha j^{i} for the j-th observation from
the middle among the last (and the first) k, j = 1, \dots, k, linear
(i = 1) or quadratic (i = 2) (eqs. 9a and 9b). See hp_schedule().
The procedure (Section 5 of the paper):
-
\lambda^{\mathrm{MHP}}of the modified HP filter (mhp_filter()), searched over1, \dots,max_lambda; for each scheme (linear and quadratic), the weight
\alphaof the grid that minimises the total lossLat\lambda^{\mathrm{MHP}};with that weight,
\lambda^{\mathrm{FMHP}}minimising McDermott's criterion again;the scheme whose loss in step 2 is smaller gives the trend and the cycle.
The defaults are those of the published MATLAB code (Hanif 2017): max_lambda = 3000; linear weights on
k = 15 end values with \alpha \in \{0, 10, \dots, 2000\};
quadratic weights on k = \mathrm{round}(\min(22, T/2 - 5)) end values with
\alpha \in \{0, 5, \dots, 2000\}; logarithms of the series. The working paper
states k = 20 in the text; set k_linear and k_quadratic to use it.
Form of the weights. The published code multiplies row t of \mathbf{A} by
\lambda_t, \hat{\mathbf{g}} = (\mathbf{I} + \mathrm{diag}(\lambda_t)\mathbf{A})^{-1}
\mathbf{x} (form = "rows", the default). The penalised least-squares
problem with a separate \lambda_r for each second difference gives instead \hat{\mathbf{g}} =
(\mathbf{I} + \mathbf{K}^\top\mathrm{diag}(\lambda_r)\mathbf{K})^{-1}\mathbf{x}, a symmetric smoother (form = "differences", the scheme of eq. 9 written on the
T - 2 differences). Both are solved in O(T) operations; the gains need two solves per
frequency and the smoother itself is never formed.
With lambda given, the smoothing parameter is fixed (steps 1 and 3 are skipped): the HP filter with the
endogenous weights of the paper (Table 3a, column "HP (our scheme)").
Value
With as_dt = TRUE, a data.table with the columns original, trend,
cycle (and time for a ts) and the attributes lambda, gcv, lambda_mhp,
scheme, alpha, k, loss and lambda_t. With as_dt = FALSE, a list of
class c("mhp_fmhp", "mhp", "mhp_result", "list"):
original,trend,cyclethe series, its trend and its cycle (on the scale of the series).
lambda,gcv\lambda^{\mathrm{FMHP}}and its criterion.lambda_mhp\lambda^{\mathrm{MHP}}of step 1.scheme,alpha,kthe chosen scheme, its weight and its number of end values.
lossthe total loss
Lof the chosen scheme at\lambda^{\mathrm{MHP}}(the criterion of step 4).lambda_tthe smoothing parameters of the trend.
schemesdata.table, one row per scheme:scheme,k,alpha,loss,lambda,gcv.form,log_scalethe settings; then
trend_log,cycle_log(withlog_scale = TRUE),timeandfrequency(for ats).
Methods: print(), plot(), ggplot2::autoplot(), hp_loss(),
mhp_interpret().
Author(s)
Muhammad Yaseen (myaseen208@gmail.com), from the MATLAB code of Muhammad Nadim Hanif
References
Hanif, M. N., Iqbal, J. and Choudhary, M. A. (2017). Fully modified HP filter. SBP Working Paper Series, No. 88, State Bank of Pakistan.
Hanif, M. N. (2017). Fully modified HP filter function (MATLAB code). MATLAB Central File Exchange, 63198.
Bloechl, A. (2014). Reducing the excess variability of the Hodrick-Prescott filter by flexible penalization. Discussion Paper 2014-1, University of Munich.
McDermott, C. J. (1997). An automatic method for choosing the smoothing parameter in the HP filter. Unpublished, International Monetary Fund, Washington DC.
See Also
mhp_filter, fmhp_batch, fmhp_compare, hp_loss
Examples
data(us_macro)
gdp <- ts(data = us_macro$gdp, start = c(1959, 1), frequency = 4)
fm <-
fmhp_filter(
x = gdp
, max_lambda = 3000
, k_linear = 15
, k_quadratic = NULL
, alpha_linear = seq(from = 0, to = 2000, by = 10)
, alpha_quadratic = seq(from = 0, to = 2000, by = 5)
, schemes = c("linear", "quadratic")
, form = "rows"
, lambda = NULL
, log_scale = TRUE
, as_dt = FALSE
)
fm
fm$schemes
plot(x = fm)
Power comparison of the filters on simulated series
Description
fmhp_simulation() repeats the simulation study of Hanif, Iqbal and Choudhary (2017, Tables 1 and 2): for
each design it simulates series with mhp_simulate(), filters them with the HP, modified HP and fully
modified HP filters, and compares the root mean square error of the estimated cycles against the true one, over
the whole series, its middle and its ends.
Usage
fmhp_simulation(
designs = mhp_designs(),
n_rep = 100L,
T = 200L,
trend = c("linear", "nonlinear"),
aggregate = c("none", "systematic", "sum", "average"),
lambda = NULL,
max_lambda = 3000L,
seed = NULL,
form = c("rows", "differences")
)
Arguments
designs |
designs as in |
n_rep |
replicates per design (default 100; the paper used 1000). |
T |
number of quarterly observations (default 200). |
trend, aggregate |
as in |
lambda |
the HP smoothing parameter (default |
max_lambda |
the largest |
seed |
seed of the random numbers ( |
form |
the form of the end-point weights of the fully modified HP filter (default |
Details
The RMSE of a filter is \{T^{-1}\sum_t(\hat{c}_t - c_t)^2\}^{1/2}; the middle is
the central 80% of the observations and the ends the first and last 10%. fmhp_better is the share of
replicates in which the FMHP filter has a smaller RMSE than the HP filter (Table 1 of the paper reports it in
percent). The series are filtered on their own scale (log_scale = FALSE).
Value
An object of class c("mhp_simulation", "mhp_result", "list"): rmse (a data.table
with one row per design and filter: model, sd_ratio, ar1, ar2, method,
rmse, rmse_middle, rmse_ends), power (one row per design: the share of replicates in
which FMHP beats HP and MHP) and settings. plot() draws the RMSE by design.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
References
Hanif, M. N., Iqbal, J. and Choudhary, M. A. (2017). Fully modified HP filter. SBP Working Paper Series, No. 88, State Bank of Pakistan.
See Also
Examples
sim <-
fmhp_simulation(
designs = mhp_designs()[c(3, 13, 23)]
, n_rep = 2
, T = 120
, trend = "linear"
, aggregate = "none"
, lambda = NULL
, max_lambda = 3000
, seed = 1
, form = "rows"
)
sim$power
Extract the smoothing parameter or the criterion of a result
Description
get_lambda() returns the smoothing parameter and get_gcv() the value of McDermott's criterion of a
result of hp_filter(), mhp_filter() or fmhp_filter(), whether it is a
data.table (as_dt = TRUE) or a list (as_dt = FALSE).
Usage
get_lambda(x)
## Default S3 method:
get_lambda(x)
get_gcv(x)
## Default S3 method:
get_gcv(x)
Arguments
x |
a filter result. |
Value
get_lambda(): the smoothing parameter; get_gcv(): the criterion at that value.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
Examples
data(us_macro)
m <-
mhp_filter(
x = log(us_macro$gdp)
, max_lambda = 100000
, as_dt = TRUE
, log_scale = FALSE
, criterion = c("approximate", "exact")
)
get_lambda(x = m)
get_gcv(x = m)
Hodrick-Prescott filter with a fixed smoothing parameter
Description
hp_filter() splits a time series into a smooth trend and a cycle with the filter of Hodrick and Prescott
(1997) and a smoothing parameter \lambda chosen by the user: 1600 for quarterly data, 100 for annual
data and 129600 for monthly data are the conventional values (Ravn and Uhlig 2002).
Usage
hp_filter(x, lambda = 1600, as_dt = TRUE, log_scale = FALSE)
## Default S3 method:
hp_filter(x, lambda = 1600, as_dt = TRUE, log_scale = FALSE)
Arguments
x |
a numeric vector or a |
lambda |
the smoothing parameter |
as_dt |
|
log_scale |
filter the logarithm of the series (default |
Details
The trend \mathbf{g} = (g_1, \dots, g_T)^\top of the series \mathbf{x} minimises
\sum_{t=1}^{T}(x_t - g_t)^2 + \lambda\sum_{t=2}^{T-1}\left[(g_{t+1} - g_t) - (g_t - g_{t-1})\right]^2,
so that \hat{\mathbf{g}} = (\mathbf{I} + \lambda\mathbf{A})^{-1}\mathbf{x} = \mathbf{B}\mathbf{x} with \mathbf{A} = \mathbf{K}^\top\mathbf{K} and \mathbf{K} the
(T - 2) \times T matrix of second differences (rows (1, -2, 1)). The cycle is
\mathbf{c} = \mathbf{x} - \hat{\mathbf{g}}. The system is pentadiagonal, symmetric and positive
definite and is solved in O(T) operations.
With log_scale = TRUE the filter is applied to \log x_t; the trend is returned as
\exp(\hat{g}_t) and the cycle as x_t - \exp(\hat{g}_t), and the components
on the log scale are added to the list result.
Value
With as_dt = TRUE, a data.table with the columns original, trend,
cycle (and time for a ts) and the attribute lambda. With as_dt = FALSE, a list
of class c("mhp_hp", "mhp", "mhp_result", "list") with original, trend, cycle,
lambda, then log_scale, trend_log and cycle_log (with log_scale = TRUE) and
time and frequency (for a ts). Methods: print(), plot(),
ggplot2::autoplot(), mhp_interpret().
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
References
Hodrick, R. J. and Prescott, E. C. (1997). Postwar U.S. business cycles: an empirical investigation. Journal of Money, Credit and Banking, 29(1), 1–16. doi:10.2307/2953682
Ravn, M. O. and Uhlig, H. (2002). On adjusting the Hodrick-Prescott filter for the frequency of observations. The Review of Economics and Statistics, 84(2), 371–376. doi:10.1162/003465302317411604
See Also
mhp_filter, fmhp_filter, mhp_compare
Examples
data(us_macro)
gdp <- ts(data = us_macro$gdp, start = c(1959, 1), frequency = 4)
hp <-
hp_filter(
x = log(gdp)
, lambda = 1600
, as_dt = TRUE
, log_scale = FALSE
)
hp
attr(x = hp, which = "lambda")
Gain functions of an HP-type filter
Description
hp_gain() gives the gain of the estimate at every time t as a function of the frequency
(Hanif et al. 2017, eq. 6, Figures 2 and 2b): the factor by which the filter scales an oscillation of that
frequency. In the middle of a series the gain of the trend falls to zero at high frequencies; at the ends it does
not, so the trend there keeps part of the cycle.
Usage
hp_gain(
x,
lambda = 1600,
form = c("rows", "differences"),
theta = seq(0, pi, length.out = 101),
rows = NULL
)
## Default S3 method:
hp_gain(
x,
lambda = 1600,
form = c("rows", "differences"),
theta = seq(0, pi, length.out = 101),
rows = NULL
)
Arguments
x |
the length |
lambda |
a smoothing parameter, or one per observation ( |
form |
|
theta |
the frequencies (default 101 values from 0 to |
rows |
the rows drawn by |
Details
With b_{tj} the weights of hp_weights(), P_t(\omega) = |\sum_j b_{tj}
e^{i\omega(j - t)}|. It is computed from two solves of the
smoothing system per frequency.
Value
An object of class c("mhp_gain", "mhp_result", "list"): gain (a data.table with
t, theta, gain for every time and frequency), lambda_t, form, rows.
plot() draws the gains of the chosen rows.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Examples
g <-
hp_gain(
x = 50
, lambda = 100
, form = "rows"
, theta = seq(from = 0, to = pi, length.out = 101)
, rows = NULL
)
plot(x = g)
End-point loss of an HP-type filter
Description
hp_loss() measures the end-point bias of a filter by the loss of Bloechl (2014) used by Hanif, Iqbal and
Choudhary (2017): for every time t, the squared distance of the gain of its estimate from the gain at
the centre of the series. The loss is zero in the middle and grows towards the ends; the fully modified HP filter
chooses its end-point weights to make the total small.
Usage
hp_loss(
x,
lambda = 1600,
form = c("rows", "differences"),
theta = seq(0, 3.1, 0.1),
weight = 0.1
)
## Default S3 method:
hp_loss(
x,
lambda = 1600,
form = c("rows", "differences"),
theta = seq(0, 3.1, 0.1),
weight = 0.1
)
Arguments
x |
the length |
lambda |
a smoothing parameter, or one per observation ( |
form |
|
theta |
the frequencies (default |
weight |
the factor |
Details
l(t) = \theta\sum_{\omega}\left[P_c(\omega) - P_t(\omega)\right]^2, \qquad L = \sum_{t=1}^{T} l(t),
with the gains P_t of hp_gain(), \omega = 0, 0.1, \dots, 3.1, \theta = 0.1 (their spacing) and c = \mathrm{round}(T/2)
(Hanif et al. 2017, eqs. 7 and 8, and their MATLAB code). The loss depends on T and the smoothing
parameters only, not on the data: for the HP filter with \lambda = 100 it is 1.731 to 1.735
for 41 to 55 observations, the values of Table 3a of the paper.
Value
An object of class c("mhp_loss", "mhp_result", "list"): loss (a data.table with
t and loss), total (L), lambda_t, form. plot() draws
l(t) against t (Figures 3 and 3b of the paper).
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
References
Bloechl, A. (2014). Reducing the excess variability of the Hodrick-Prescott filter by flexible penalization. Discussion Paper 2014-1, University of Munich.
Hanif, M. N., Iqbal, J. and Choudhary, M. A. (2017). Fully modified HP filter. SBP Working Paper Series, No. 88, State Bank of Pakistan.
See Also
fmhp_filter, hp_gain, fmhp_compare
Examples
hl <-
hp_loss(
x = 55
, lambda = 100
, form = "rows"
, theta = seq(from = 0, to = 3.1, by = 0.1)
, weight = 0.1
)
hl$total
plot(x = hl)
Smoothing parameters with raised end values
Description
hp_schedule() gives the smoothing parameter of every observation (or second difference) under the
end-point schemes of Hanif, Iqbal and Choudhary (2017, eqs. 9a and 9b): \lambda in the middle and
\lambda + \alpha j^{i} for the j-th of the k values at each end,
counted from the middle (j = k at the first and last observation).
Usage
hp_schedule(T, lambda, alpha, k, power = 1, form = c("rows", "differences"))
Arguments
T |
length of the series. |
lambda |
the base smoothing parameter. |
alpha |
the weight |
k |
number of raised values at each end. |
power |
|
form |
|
Value
A numeric vector of smoothing parameters.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Examples
hp_schedule(
T = 50
, lambda = 100
, alpha = 10
, k = 20
, power = 1
, form = "rows"
)
Weights of an HP-type filter
Description
hp_weights() gives the matrix \mathbf{B} of the trend \hat{\mathbf{g}} =
\mathbf{B}\mathbf{x}: row t holds the weights of the estimate at time t. Symmetric in
the middle of the series, the rows become asymmetric near the ends, the source of the end-point bias (Hanif et
al. 2017, Figures 1 and 1a).
Usage
hp_weights(x, lambda = 1600, form = c("rows", "differences"), rows = NULL)
## Default S3 method:
hp_weights(x, lambda = 1600, form = c("rows", "differences"), rows = NULL)
Arguments
x |
the length |
lambda |
a smoothing parameter, or one per observation ( |
form |
|
rows |
the rows drawn by |
Value
An object of class c("mhp_weights", "mhp_result", "list"): weights (the
T \times T matrix), lambda_t, form, rows. plot() draws the chosen rows.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Examples
w <-
hp_weights(
x = 50
, lambda = 100
, form = "rows"
, rows = NULL
)
round(x = w$weights[1:3, 1:6], digits = 3)
plot(x = w)
Methods for mhpfilter results
Description
The analysis functions of mhpfilter return the named list they have always returned, now with the class
c("mhp_<analysis>", "mhp_result", "list"). Components are read as before (x$ANOVA,
x[["Means"]]); the methods below print, summarise and plot the result and turn any component into a
data.table.
Usage
## S3 method for class 'mhp_result'
print(x, digits = 4L, ...)
## S3 method for class 'mhp_result'
summary(object, ...)
## S3 method for class 'summary.mhp_result'
print(x, ...)
## S3 method for class 'mhp_result'
format(x, ...)
## S3 method for class 'mhp_result'
as.data.table(x, keep.rownames = FALSE, ..., component = 1L)
## S3 method for class 'mhp_result'
as.data.frame(x, row.names = NULL, optional = FALSE, ..., component = 1L)
## S3 method for class 'mhp_result'
plot(x, ...)
Arguments
x, object |
a mhpfilter result. |
digits |
significant digits of printed numbers (default 4). |
... |
passed on (to |
keep.rownames, row.names, optional |
as in |
component |
name or number of the component to convert (default: the first one). |
Value
print() returns x invisibly; summary() an object of class
summary.mhp_result; format() a character string; as.data.table() and
as.data.frame() the chosen component as a table; plot() a ggplot object.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
Trend and cycle analysis in a web browser
Description
mhp_app() starts the application of mhpfilter: load a series (the example us_macro or
a CSV file), filter it with the HP, modified HP or fully modified HP filter, compare the three filters, inspect
their weights, gains and end-point loss, filter all the series of a file at once and run the power comparison of
Hanif, Iqbal and Choudhary (2017). Every result page shows an interpretation computed from the results
(mhp_interpret()), the output as R prints it, formatted tables, plots and the R code that repeats the
analysis, each with a Copy button.
Usage
mhp_app(launch.browser = interactive(), ...)
mhp_app_object()
Arguments
launch.browser |
passed to |
... |
further arguments to |
Details
The application needs the suggested packages shiny, bslib and DT. Plots are sent to the browser as WebP images when magick is installed (smaller than PNG; PNG otherwise) and can be downloaded as PNG, PDF or WebP. Text is set in IBM Plex Sans and output in IBM Plex Mono when the browser can reach Google Fonts, in the system fonts otherwise.
Value
mhp_app() is called for its side effect and returns the value of shiny::runApp() when the
application is closed; mhp_app_object() returns the application object (for shiny::runApp(),
shiny::testServer() or deployment on a server).
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
mhp_filter, fmhp_filter, fmhp_compare, mhp_interpret
Examples
if (interactive()) {
mhp_app(
launch.browser = TRUE
)
}
Modified HP filter of many series
Description
mhp_batch() applies mhp_filter() to every column of a matrix or data frame and returns one
long table, with the smoothing parameter of each series in an attribute. Series of different lengths can share
the matrix: leading and trailing missing values are dropped series by series.
Usage
mhp_batch(X, max_lambda = 100000L)
## Default S3 method:
mhp_batch(X, max_lambda = 100000L)
Arguments
X |
a numeric matrix or data frame, one series per column; missing values only at the start or the end. |
max_lambda |
the largest |
Value
A data.table with the columns series, t, original, trend,
cycle and the attribute lambdas, a data.table with series, lambda and
gcv (as in version 0.1.0).
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
mhp_filter, fmhp_batch, batch_compare, plot_batch
Examples
data(us_macro)
X <- log(as.matrix(us_macro[, c("gdp", "consumption", "investment")]))
mb <-
mhp_batch(
X = X
, max_lambda = 100000
)
attr(x = mb, which = "lambdas")
References of a result or of the package
Description
mhp_cite() gives the references of the methods behind a result of the package, or the references of every
method in the package, as text or BibTeX. citation("mhpfilter") cites the package and its main methods.
Usage
mhp_cite(x = NULL, style = c("text", "bibtex"))
## Default S3 method:
mhp_cite(x = NULL, style = c("text", "bibtex"))
Arguments
x |
a result of a function of the package (with |
style |
|
Value
An object of class bibentry (printed in the chosen style).
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
Examples
mhp_cite(
x = NULL
, style = "text"
)
data(us_macro)
f <-
mhp_filter(
x = log(us_macro$gdp)
, max_lambda = 100000
, as_dt = FALSE
, log_scale = FALSE
, criterion = "approximate"
)
mhp_cite(
x = f
, style = "bibtex"
)
Compare the HP and the modified HP filter
Description
mhp_compare() filters one series with the HP filter at the conventional \lambda of its
frequency and with the modified HP filter, and compares the cycles; batch_compare() does the same for
every column of a matrix.
Usage
mhp_compare(
x,
frequency = c("quarterly", "annual", "monthly"),
max_lambda = 100000L
)
## Default S3 method:
mhp_compare(
x,
frequency = c("quarterly", "annual", "monthly"),
max_lambda = 100000L
)
batch_compare(
X,
frequency = c("quarterly", "annual", "monthly"),
max_lambda = 100000L
)
## Default S3 method:
batch_compare(
X,
frequency = c("quarterly", "annual", "monthly"),
max_lambda = 100000L
)
Arguments
x |
a numeric vector or a |
frequency |
|
max_lambda |
the largest |
X |
a numeric matrix or data frame, one series per column. |
Details
The conventional values are \lambda = 1600 (quarterly), 100 (annual) and 129600 (monthly,
Ravn and Uhlig 2002). ar1 is the first-order autocorrelation of the cycle, \sum_t c_t c_{t+1} /
\sum_t c_t^2.
Value
mhp_compare(): a data.table with one row per method (HP, Modified HP) and
the columns method, lambda, cycle_sd, cycle_mean, ar1, cycle_range,
gcv. batch_compare(): a data.table with one row per series and the columns
series, hp_lambda, mhp_lambda, hp_cycle_sd, mhp_cycle_sd, sd_diff,
hp_ar1, mhp_ar1, ar1_diff, relative_sd.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Examples
data(us_macro)
cmp <-
mhp_compare(
x = log(us_macro$gdp)
, frequency = "quarterly"
, max_lambda = 100000
)
cmp
bc <-
batch_compare(
X = log(as.matrix(us_macro[, c("gdp", "consumption", "investment")]))
, frequency = "quarterly"
, max_lambda = 100000
)
bc
The 30 simulation designs of Hanif, Iqbal and Choudhary (2017)
Description
mhp_designs() lists the 30 combinations of Table 1 of the paper: five ratios
\sigma_\varepsilon / \sigma_\delta of the standard deviations of the trend and cycle
shocks (10, 5, 2, 1, 0.5) crossed with six AR(2) cycles (\phi_1, \phi_2): (0.9, 0.01),
(1.2, -0.25), (1.2, -0.4), (1.2, -0.55), (1.2, -0.75) and (0.8, 0). The designs of Choudhary, Hanif and Iqbal
(2014, Table 1) have the same cycles and the ratios 10, 5, 1, 0.5 and 0.01.
Usage
mhp_designs(paper = c("2017", "2014"))
Arguments
paper |
|
Value
A data.table with the columns model (1 to 30, as in the paper), sd_ratio,
ar1, ar2.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
References
Choudhary, M. A., Hanif, M. N. and Iqbal, J. (2014). On smoothing macroeconomic time series using the modified HP filter. Applied Economics, 46(19), 2205–2214. doi:10.1080/00036846.2014.894631
Hanif, M. N., Iqbal, J. and Choudhary, M. A. (2017). Fully modified HP filter. SBP Working Paper Series, No. 88, State Bank of Pakistan.
See Also
Examples
mhp_designs(
paper = "2017"
)
Modified Hodrick-Prescott filter: the smoothing parameter chosen from the data
Description
mhp_filter() applies the modified HP filter of McDermott (1997), studied by Choudhary, Hanif and Iqbal
(2014): the smoothing parameter \lambda is the one of 1, 2, \dots,
max_lambda that minimises a generalised cross-validation criterion, so that every series gets its own
\lambda instead of the conventional 1600 or 100.
Usage
mhp_filter(
x,
max_lambda = 100000L,
as_dt = TRUE,
log_scale = FALSE,
criterion = c("approximate", "exact")
)
## Default S3 method:
mhp_filter(
x,
max_lambda = 100000L,
as_dt = TRUE,
log_scale = FALSE,
criterion = c("approximate", "exact")
)
Arguments
x |
a numeric vector or a |
max_lambda |
the largest |
as_dt |
|
log_scale |
filter the logarithm of the series (default |
criterion |
|
Details
For each candidate \lambda the trend \hat{\mathbf{g}}(\lambda) of
hp_filter() is computed and
\mathrm{GCV}(\lambda) = \frac{1}{T}\left(1 + \frac{2T}{\lambda}\right)\sum_{t=1}^{T}\left(x_t -
\hat{g}_t(\lambda)\right)^2
(Choudhary et al. 2014, eq. 6; Hanif et al. 2017, eq. 4); \hat\lambda minimises it. This is
Silverman's (1984) approximation of generalised cross-validation (Craven and Wahba 1979),
\mathrm{GCV}(\lambda) = \frac{T^{-1}\sum_{t}(x_t - \hat{g}_t(\lambda))^2}{\left(1 -
T^{-1}\mathrm{tr}\,\mathbf{B}(\lambda)\right)^2}
(Choudhary et al. 2014, eq. 5), which criterion = "exact" uses: the eigenvalues
\mu_i of \mathbf{A}, computed once, give \mathrm{tr}\,\mathbf{B}(\lambda) =
\sum_i (1 + \lambda\mu_i)^{-1} and the residual sum of squares for
every \lambda in O(T) operations (the decomposition costs O(T^3), a
fraction of a second for a few hundred observations). Each trend costs
O(T) operations, so the search over 100000 values takes about a second for 200 quarterly observations.
The search is that of the authors' MATLAB code (modifiedhpfilternew.m, Choudhary et al. 2014), which
omits the factor 1/T (it does not change the minimum) and works on the series as given; filter the
logarithm of a series (as in the papers) with log_scale = TRUE or by passing log(x).
Changes from version 0.1.0. The criterion is unchanged (the help page of 0.1.0 printed the factor as
1 + 2/(T\lambda), but the code used 1 + 2T/\lambda); every trend is now
a banded solve instead of a dense one, so results agree with 0.1.0 to rounding error at a fraction of the time.
Value
With as_dt = TRUE, a data.table with the columns original, trend,
cycle (and time for a ts) and the attributes lambda and gcv. With
as_dt = FALSE, a list of class c("mhp_mhp", "mhp", "mhp_result", "list") with original,
trend, cycle, lambda, gcv as in version 0.1.0, then gcv_path (the criterion
for every \lambda of the search), log_scale, criterion, trend_log and
cycle_log (with
log_scale = TRUE), time and frequency (for a ts). Methods: print(),
plot(),
ggplot2::autoplot(), mhp_interpret().
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
References
Choudhary, M. A., Hanif, M. N. and Iqbal, J. (2014). On smoothing macroeconomic time series using the modified HP filter. Applied Economics, 46(19), 2205–2214. doi:10.1080/00036846.2014.894631
Craven, P. and Wahba, G. (1979). Smoothing noisy data with spline functions. Numerische Mathematik, 31, 377–403. doi:10.1007/BF01404567
Silverman, B. W. (1984). A fast and efficient cross-validation method for smoothing parameter choice in spline regression. Journal of the American Statistical Association, 79(387), 584–589. doi:10.1080/01621459.1984.10478084
McDermott, C. J. (1997). An automatic method for choosing the smoothing parameter in the HP filter. Unpublished, International Monetary Fund, Washington DC; described in Coe, D. T. and McDermott, C. J. (1997). Does the gap model work in Asia? IMF Staff Papers, 44(1), 59–80. doi:10.2307/3867497
See Also
hp_filter, fmhp_filter, mhp_batch, get_lambda
Examples
data(us_macro)
gdp <- ts(data = us_macro$gdp, start = c(1959, 1), frequency = 4)
mhp <-
mhp_filter(
x = log(gdp)
, max_lambda = 100000
, as_dt = FALSE
, log_scale = FALSE
, criterion = "approximate"
)
mhp
plot(x = mhp)
Plain-language interpretation of a result
Description
mhp_interpret() turns a result of the package into a short report: a headline, findings, recommendations
and cautions, computed from its numbers, with the sources of the method. It covers the filters
(hp_filter(), mhp_filter(), fmhp_filter(), as lists or as
data.tables), the end-point loss (hp_loss()) and the power comparison
(fmhp_simulation()).
Usage
mhp_interpret(x, top = 3L, ...)
## Default S3 method:
mhp_interpret(x, top = 3L, ...)
## S3 method for class 'mhp_interpretation'
print(x, ...)
## S3 method for class 'mhp_interpretation'
format(x, style = c("text", "markdown"), width = getOption("width", 80L), ...)
Arguments
x |
a result of a function of the package. |
top |
number of largest positive and negative cycle values named (default 3). |
... |
unused. |
style |
|
width |
line width of the text (default |
Details
For a filter the report compares the chosen smoothing parameter with the conventional one of the frequency (1600
quarterly, 100 annual, 129600 monthly; known when the series is a ts), names the largest booms and
recessions of the cycle, and warns when a search ended at its limit or the series is short. For the fully
modified HP filter it also gives the reduction of the end-point loss against the HP filter with the same
\lambda.
Value
An object of class "mhp_interpretation": a list with analysis, title,
headline, findings, recommendations, cautions, facts (the numbers behind the
sentences), guide (how to read the method) and sources. format() gives it as text or
Markdown.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Examples
data(us_macro)
gdp <- ts(data = us_macro$gdp, start = c(1959, 1), frequency = 4)
f <-
fmhp_filter(
x = gdp
, max_lambda = 3000
, k_linear = 15
, k_quadratic = NULL
, alpha_linear = seq(from = 0, to = 2000, by = 10)
, alpha_quadratic = seq(from = 0, to = 2000, by = 5)
, schemes = c("linear", "quadratic")
, form = "rows"
, lambda = NULL
, log_scale = TRUE
, as_dt = FALSE
)
mhp_interpret(
x = f
, top = 3
)
Notation of mhpfilter
Description
The symbols used in the help pages and vignettes of mhpfilter, with their meaning and the argument or result
component that holds them. The notation follows one rule throughout: scalars are upper-case letters in normal
face (P, R), indices lower-case italic (i, j), vectors lower-case bold
(\mathbf{y}, \boldsymbol{\beta}) and matrices upper-case bold (\mathbf{X},
\boldsymbol{\Sigma}).
Usage
mhp_notation(format = c("table", "path", "tex"))
Arguments
format |
|
Value
See format.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Other mhpfilter utilities:
mhp_reference(),
mhp_save(),
mhp_theme()
Examples
mhp_notation(
format = c("table", "path", "tex")[1]
)
Published values used by the tests and vignettes
Description
Reads inst/extdata/reference.csv: one row per published number, with its source, the R call
that recomputes it with this package (call), the expression that extracts the number from the result
(extract, in terms of x), the printed value and the digits to compare. The same file drives the test
of published values and the vignette that reproduces the published examples. Each distinct call is evaluated once.
Usage
mhp_reference(source = NULL, evaluate = FALSE, level = 1)
Arguments
source |
optional regular expression; keep rows whose |
evaluate |
logical; evaluate the rows and add columns |
level |
largest |
Value
A data.table with columns id, source, quantity, call, extract,
value, digits, level, note (and computed, agrees).
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Other mhpfilter utilities:
mhp_notation(),
mhp_save(),
mhp_theme()
Examples
ref <-
mhp_reference(
source = NULL
, evaluate = FALSE
, level = 1
)
ref
mhp_reference(
source = "."
, evaluate = TRUE
, level = 1
)
Save a figure (vector PDF by default)
Description
A wrapper of ggsave with the defaults of the package: a vector PDF through
cairo_pdf (embedded fonts, correct glyphs), A4 landscape (11.69 x 8.27 inches) and 600
dpi for raster formats. The device follows the file extension for other formats (.png, .svg,
.tiff, ...).
Usage
mhp_save(
plot = ggplot2::last_plot(),
filename,
path = NULL,
width = 11.69,
height = 8.27,
units = c("in", "cm", "mm"),
dpi = 600,
scale = 1,
device = NULL,
limitsize = TRUE,
...
)
## Default S3 method:
mhp_save(
plot = ggplot2::last_plot(),
filename,
path = NULL,
width = 11.69,
height = 8.27,
units = c("in", "cm", "mm"),
dpi = 600,
scale = 1,
device = NULL,
limitsize = TRUE,
...
)
Arguments
plot |
a |
filename |
file name; its extension chooses the format. |
path |
directory to save in (default |
width, height |
size (default 11.69 x 8.27, A4 landscape, in |
units |
|
dpi |
resolution for raster formats (default 600). |
scale |
multiplicative scaling factor (default 1). |
device |
|
limitsize |
logical; refuse images larger than 50 x 50 inches (default |
... |
passed to |
Value
The file name, invisibly.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Other mhpfilter utilities:
mhp_notation(),
mhp_reference(),
mhp_theme()
Examples
library(ggplot2)
p <-
ggplot(data = data.frame(x = 1:10, y = (1:10)^2), mapping = aes(x = x, y = y)) +
geom_line() +
mhp_theme(
base_size = 11
, base_family = "serif"
, ticks_inward = TRUE
, legend_position = "bottom"
)
f <- tempfile(fileext = ".pdf")
mhp_save(
plot = p
, filename = f
, path = NULL
, width = 11.69
, height = 8.27
, units = c("in", "cm", "mm")[1]
, dpi = 600
, scale = 1
, device = NULL
, limitsize = TRUE
)
mhp_save(
plot = p
, filename = basename(f)
, path = tempdir()
, width = 11.69
, height = 8.27
, units = c("in", "cm", "mm")[1]
, dpi = 600
, scale = 1
, device = grDevices::cairo_pdf
, limitsize = TRUE
)
mhp_save(
plot = p
, filename = tempfile(fileext = ".png")
, path = NULL
, width = 6
, height = 4
, units = c("in", "cm", "mm")[1]
, dpi = 300
, scale = 1
, device = NULL
, limitsize = TRUE
)
Simulate a series with a known trend and cycle
Description
mhp_simulate() generates a series x_t = g_t + c_t from the data generating process
of Hanif, Iqbal and Choudhary (2017, eqs. 10a and 10b), after Harvey and Jaeger (1993) and Guay and St-Amant
(2005): a random walk trend with drift and an AR(2) cycle,
g_t = \mu + \tau_t + g_{t-1} + \varepsilon_t, \qquad c_t = \phi_1 c_{t-1} + \phi_2 c_{t-2} + \delta_t,
with \varepsilon_t \sim N(0, \sigma_\varepsilon^2) and \delta_t \sim N(0,
\sigma_\delta^2). Quarterly series can be aggregated to annual ones as in the paper.
Usage
mhp_simulate(
T = 200L,
sd_ratio = 1,
ar = c(1.2, -0.4),
sd_cycle = 1,
drift = 0.5,
trend = c("linear", "nonlinear"),
aggregate = c("none", "systematic", "sum", "average"),
seed = NULL
)
Arguments
T |
number of (quarterly) observations (default 200, as in the paper). |
sd_ratio |
|
ar |
|
sd_cycle |
|
drift |
|
trend |
|
aggregate |
|
seed |
seed of the random numbers ( |
Details
The paper does not give the drift \mu or the form of the nonlinear trend term \tau_t. Here
\tau_t = 0 for trend = "linear", and \tau_t = \mu\sin(2\pi t/T) for trend = "nonlinear", a drift that rises and falls once over the sample. The cycle starts from a
burn-in of 100 values. Aggregation to annual data takes every fourth value ("systematic"), the sum of four
consecutive values ("sum") or their average ("average"), for the series and both components.
Value
A data.table with the columns t, x, trend, cycle.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
References
Guay, A. and St-Amant, P. (2005). Do the Hodrick-Prescott and Baxter-King filters provide a good approximation of business cycles? Annales d'Economie et de Statistique, 77, 133–155. doi:10.2307/20079119
Harvey, A. C. and Jaeger, A. (1993). Detrending, stylized facts and the business cycle. Journal of Applied Econometrics, 8(3), 231–247. doi:10.1002/jae.3950080302
See Also
Examples
s <-
mhp_simulate(
T = 200
, sd_ratio = 1
, ar = c(1.2, -0.4)
, sd_cycle = 1
, drift = 0.5
, trend = "linear"
, aggregate = "none"
, seed = 1
)
s
ggplot2 theme of mhpfilter
Description
The theme used by every plot() method of mhpfilter (identical in all packages of the
author): theme_classic with a serif font, black axis lines, ticks pointing inwards and no
grid, close to the look of TikZ/pgfplots figures in LaTeX documents. The plot() methods also use
scales::pretty_breaks(n = 10) on every continuous axis. Save figures with mhp_save.
Usage
mhp_theme(
base_size = 11,
base_family = "serif",
ticks_inward = TRUE,
legend_position = "bottom"
)
Arguments
base_size |
base font size in points (default 11). |
base_family |
font family (default |
ticks_inward |
logical; ticks point into the panel, as in pgfplots (default |
legend_position |
position of the legend (default |
Value
A ggplot2 theme.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
See Also
Other mhpfilter utilities:
mhp_notation(),
mhp_reference(),
mhp_save()
Examples
library(ggplot2)
p <-
ggplot(data = data.frame(x = 1:20, y = cumsum(sin(1:20))), mapping = aes(x = x, y = y)) +
geom_line()
p +
mhp_theme(
base_size = 11
, base_family = "serif"
, ticks_inward = TRUE
, legend_position = "bottom"
)
p +
mhp_theme(
base_size = 12
, base_family = "serif"
, ticks_inward = FALSE
, legend_position = "right"
) +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10))
Plot the results of many series
Description
plot_batch() draws the cycles (or trends) of a result of mhp_batch() or
fmhp_batch(), one panel per series or all in one panel, with the smoothing parameter of each series
in its label.
Usage
plot_batch(x, show = c("cycle", "trend"), facet = TRUE, highlight = NULL)
Arguments
x |
a result of |
show |
|
facet |
one panel per series (default |
highlight |
names of series drawn in full colour, the others faded (default |
Details
Change from version 0.1.0. The faceted plot passed linewidth twice (a warning) and ignored
highlight; both are corrected.
Value
A ggplot object.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
Examples
data(us_macro)
mb <-
mhp_batch(
X = log(as.matrix(us_macro[, c("gdp", "consumption", "investment")]))
, max_lambda = 100000
)
plot_batch(
x = mb
, show = "cycle"
, facet = TRUE
, highlight = NULL
)
Plot the HP and modified HP filters of one series
Description
plot_comparison() draws the series with the trends of the HP filter (at the conventional
\lambda of its frequency) and of the modified HP filter, and optionally the cycles; with
fmhp = TRUE the fully modified HP filter is added.
Usage
plot_comparison(
x,
frequency = c("quarterly", "annual", "monthly"),
max_lambda = 100000L,
show_cycle = FALSE,
fmhp = FALSE
)
Arguments
x |
a numeric vector or a |
frequency |
|
max_lambda |
the largest |
show_cycle |
draw the cycles too (default |
fmhp |
add the fully modified HP filter (default |
Value
A ggplot object.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
Examples
data(us_macro)
plot_comparison(
x = log(us_macro$gdp)
, frequency = "quarterly"
, max_lambda = 100000
, show_cycle = TRUE
, fmhp = TRUE
)
Print a filter result
Description
print() of a result of hp_filter(), mhp_filter() or
fmhp_filter() (with as_dt = FALSE) shows the smoothing parameter, the criterion and summaries
of the cycle, as in version 0.1.0, and the sources of the method.
Usage
## S3 method for class 'mhp'
print(x, ...)
Arguments
x |
a result of |
... |
further arguments ( |
Value
x, invisibly.
Author(s)
Muhammad Yaseen (myaseen208@gmail.com)
Examples
data(us_macro)
m <-
mhp_filter(
x = log(us_macro$gdp)
, max_lambda = 100000
, as_dt = FALSE
, log_scale = FALSE
, criterion = c("approximate", "exact")
)
print(x = m)
United States real GDP, consumption and investment, 1959 to 2009 (quarterly)
Description
Quarterly real gross domestic product, real personal consumption expenditures and real gross private domestic investment of the United States from the first quarter of 1959 to the third quarter of 2009: the three series (income, consumption and investment) of the empirical analysis of Hanif, Iqbal and Choudhary (2017), for one country.
Usage
us_macro
Format
A data frame with 203 rows and 5 columns:
yearyear, 1959 to 2009.
quarterquarter, 1 to 4.
gdpreal gross domestic product (billions of chained 2005 US dollars, seasonally adjusted annual rate).
consumptionreal personal consumption expenditures (same units).
investmentreal gross private domestic investment (same units).
Source
Federal Reserve Economic Data (FRED), Federal Reserve Bank of St. Louis, accessed 15 December 2009, as
compiled in the data set macrodata of the Python library statsmodels (public domain).
References
Hanif, M. N., Iqbal, J. and Choudhary, M. A. (2017). Fully modified HP filter. SBP Working Paper Series, No. 88, State Bank of Pakistan.
Examples
data(us_macro)
head(us_macro)
gdp <- ts(data = us_macro$gdp, start = c(1959, 1), frequency = 4)
plot(log(gdp))