# hpfilter: An R Implementation of the One- and Two-Sided Hodrick-Prescott Filter

## The hpfilter package

hpfilter is a package that implements the one-sided and two-sided versions of the Hodrick-Prescott filter in R.

The two-sided implementation uses sparse matrices to enhance the efficiency of calculations when using large datasets. Its traditional use has been in macroeconomics, to smooth out the time series of variables such as the GDP. The one-sided version is based on the Kalman filter. An important use of the one-sided HP filter is for the calculation of the credit gap, according to the Basel III methodology for setting the Countercyclical Capital Buffer (CCyB) guide.

#### The Hodrick-Prescott Filter

The Hodrick-Prescott filter is a technique commonly used to smooth macroeconomic data such as the GDP. It consists in separating short-term, cyclical movements in the data from the long-term trend. Although the HP filter has received numerous critiques, recent studies show that alternative methods do not necessarily perform better. Furthermore, the Basel committee, an international body responsible for setting international guidelines for prudential regulation, has recommended the usage of the one-sided HP filter for calculations pertaining to the analysis of financial cycles.

#### Short mathematical overview

Filtering techniques, such as the HP filter are based on the concept of time series decomposition. This means that an original series $$y$$ is separated into its trend and cyclical components, with the remainder of the variability being classified as noise (or the error term $$ε_t$$).

$$y_t = ytrend_t + ycycle_t + \varepsilon_t$$

where:

$$t = [0, T]$$

$$T$$ - the total number of observations

$$ytrend_t$$ - the trend component

$$ycycle_t$$ - the cyclical component

$$\varepsilon_t$$ - the error term.

The HP filter finds a trend series that solves the minimization problem shown in the equation below:

$$\min\limits_{ytrend} ( \sum\limits_{t=1}^T(y_t-ytrend_t)^2+\lambda*\sum\limits_{t=2}^{T-1}[(ytrend_{t+1}-ytrend_{t})-(ytrend_{t}-ytrend_{t-1})]^2)$$

From the first-order conditions, we derive the following expression to be solved:

$$A*ytrend=y$$

where:

$A = \begin{bmatrix}1+\lambda &-2*\lambda &\lambda &0&\cdots&\cdots&\cdots&\cdots&0\\-2*\lambda&1+5*\lambda&-4*\lambda&\lambda&0&\cdots&\cdots&\cdots&0\\\lambda&-4*\lambda&1+6*\lambda&-4*\lambda&\lambda&0&\cdots&\cdots&0\\0 &\lambda &-4*\lambda & 1+6*\lambda & -4*\lambda &\lambda &0 &\cdots&0 \\\vdots&&&&&&&&\vdots\\0&\cdots&\cdots&0 &\lambda &-4*\lambda &1+6*\lambda &-4*\lambda &\lambda\\0&\cdots&\cdots&\cdots&0 & \lambda & -4*\lambda & 1+5*\lambda & -2*\lambda\\0&\cdots&\cdots&\cdots&\cdots&0 & \lambda & -2*\lambda & 1+\lambda\end{bmatrix}$

$$y$$ - the vector containing the data to be processed

$$\lambda$$ - the smoothing parameter.