In this post I present a R function that implements James D. Hamilton's alternative to the Hodrick-Prescott Filter as described in his article "Why You Should Never Use the Hodrick Prescott Filter", forthcoming in the Review of Economics and Statistics. In the paper, Hamilton demonstrates how HP filtering creates artificial correlation between variables and suggests filtering using the residuals of the following regression:
$$ y_{t+h} = \beta_0 + \sum_{l=1}^p \beta_l y_{t+1-l} + \nu_{t+h}, $$
$y_{t+h}$ are the elements of $y$ that can be predicted $h$ periods ahead using its previous $l$ observations. This corresponds to the trend after fluctuations have disappeared after $h$ periods. $h$ should therefore be chosen to be 2 years where we assume macroeconomic shocks to be worn off. $l$ is recommended to include 1 year of data to remove possible seasonal components from the trend. I highly recommend reading Hamilton's blog post on the topic.
I implement this filter in the following R function based on the matlab code accompanying Hamilton's paper.
Saturday, September 23, 2017
Tuesday, September 12, 2017
A Function to Retrieve Time Series by Variable Number from CanSim (Statistics Canada)
In this post, I want to make a function available that allows you to download a time series from Statistics Canada directly into R. The function is a wrapper for the get_cansim_vector function from the 'cansim' package. It determines the frequency of a series and converts it into a time series.
All CanSim variables start with a "v". To find this vector name, you need to change the view of a table you find on the Statistics Canada website by clicking 'Add/Remove Data' => 'Customize Layout' and then tick the box 'Display Vector identifier and coordinate'
Below is the function that will do the trick. The function works with daily, weekly, monthly, quarterly and yearly data. If the series does not have one of these frequencies, the data is still returned, but not properly converted into a time series.
Now we can call the function retrieving the variable from CanSim.
Let me know if you have any comments or suggestions.
All CanSim variables start with a "v". To find this vector name, you need to change the view of a table you find on the Statistics Canada website by clicking 'Add/Remove Data' => 'Customize Layout' and then tick the box 'Display Vector identifier and coordinate'
Below is the function that will do the trick. The function works with daily, weekly, monthly, quarterly and yearly data. If the series does not have one of these frequencies, the data is still returned, but not properly converted into a time series.
Now we can call the function retrieving the variable from CanSim.
Let me know if you have any comments or suggestions.
- this post was updated 2020-11-16 -
Subscribe to:
Comments (Atom)