<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Justin Eloriaga on Medium]]></title>
        <description><![CDATA[Stories by Justin Eloriaga on Medium]]></description>
        <link>https://medium.com/@justin.eloriaga?source=rss-d96cd0c6d923------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NBYUVVCva_meSkZBo-Kb8A.png</url>
            <title>Stories by Justin Eloriaga on Medium</title>
            <link>https://medium.com/@justin.eloriaga?source=rss-d96cd0c6d923------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:02:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@justin.eloriaga/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Long Run Linkages: A Briefer on the Johansen Cointegration Methodology]]></title>
            <link>https://medium.com/data-science/long-run-linkages-a-briefer-on-the-johansen-cointegration-methodology-6744ee253012?source=rss-d96cd0c6d923------2</link>
            <guid isPermaLink="false">https://medium.com/p/6744ee253012</guid>
            <category><![CDATA[cointegration]]></category>
            <category><![CDATA[vector-error-correction]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[long-run-linkage]]></category>
            <dc:creator><![CDATA[Justin Eloriaga]]></dc:creator>
            <pubDate>Thu, 08 Oct 2020 02:57:24 GMT</pubDate>
            <atom:updated>2020-10-08T02:57:24.256Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can economic variables have a long-run relationship? Yes!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcW9zVbsL1SZ_E6Bcdwt5g.png" /></figure><h4>Motivation behind Cointegration</h4><p>In Economics, there are numerous variables that may appear non-stationary on the outset but when a linear combination of these non-stationary series is made, the linear combination may be described as stationary. While most economists think that Cointegration is some deep theoretical construct, the definition is actually the first sentence of this article. Theoretically, it need not be motivated by any form of theory. However, economists believe that some underlying long run trend or steady state may be pulling on these variables to comove together. Just like a man walking his dog on the park with a leash tied to its neck, they will always move together even if the dog gets distracted by the big flower on the lefthand side of the bench or another dog barking in the corner.</p><h4>Johansen’s Methodology</h4><p>In the world of econometrics, the most popular methodology is based on Soren Johansen’s cointegration test.</p><p>Johansen’s methodology is based on the idea that estimating the rank of gives us information about pi whether there is cointegration and the number of these cointegrating relationships. By definition, the rank of pi is the maximum number of independent vectors within this matrix. If we have three endogenous variables, we can only have three independent vectors and no more than that. The rank could be zero or at most three or anywhere in that range. That is, the rank cannot exceed the number of endogenous variables in the system.</p><p>If the rank of pi is equal to zero, then it is said that there is no cointegration. This implies that pi = 0 and you can see this in the equation. If you substituted that in the equation, then all the error correction terms would disappear, hence the system collapses to a simple VAR in differences. If the rank of is equal to the number of endogenous variables which we refer to as a full rank, then it suggests that all variables are I(0) or the variables are all stationary. So in that case, we cannot talk about cointegration between non-stationary variables as the variables are already stationary. Hence, you can just run a VAR in levels. If the rank of is strictly between zero and the number of endogenous variables, 0 &lt; rank(pi) &lt; n or less than a full rank, then there are r number of independent cointegrating relationships where r = rank(pi)</p><p>There are two types of tests in the Johansen methodology. The first is the trace statistic for each rank r . In the case of our model with three endogenous variables, r being 0, 1, or 2. The null hypothesis of this statistic is that the rank is at most r versus the alternative hypothesis that the rank is strictly greater than this r . The second is the maximum eigenvalue statistic for each rank r . The null hypothesis is that the rank is equal to rank(pi) versus the alternative hypothesis is that the rank is rank(pi) + 1.</p><h4>Example in R</h4><p>The time has come to provide an actual example testing for cointegration in R. To do this, we need to use the “urca” package which contains the ca.jo command to implement the test. To start of, we load the packages required and load the dataset “VECM_LectureNotes.csv using the read_csv() command. The dataset and code can be found here: <a href="https://drive.google.com/drive/folders/1QHUwS83GAUOVnxnoi-OZ6-shmTwo8mdB?usp=sharing">https://drive.google.com/drive/folders/1QHUwS83GAUOVnxnoi-OZ6-shmTwo8mdB?usp=sharing</a></p><pre>library(urca)<br>library(forecast)<br>library(tidyverse)</pre><pre>data &lt;- read_csv(file.choose())</pre><pre>head(data)</pre><p>We then declare our time series variables using the ts() command. We note that the series starts in Q1 of 2001 until Q1 of 2020. This is obviously quarterly data so we set the frequency to four.</p><pre>GDP &lt;- ts(data$lnGDP, start = c(2003,1,31), frequency = 4)<br>CPI &lt;- ts(data$lnCPI, start = c(2003,1,31), frequency = 4)<br>M3 &lt;- ts(data$lnM3, start = c(2003,1,31), frequency = 4)</pre><p>After declaring the series as a ts object, we will then need to bind the variable into a singular system.To do this, we use the cbind() command. We store the said system into an object, in this case dset</p><pre>dset &lt;- cbind(GDP,CPI,M3)</pre><p>After which, we would need to select the optimal lag order. Now recall that in a VECM (or the presumption of cointegration), the optimal lag order to use is p -1. To determine the optimal number of lags, we use the VARselect() command.</p><pre>lagselect &lt;- VARselect(dset, lag.max = 7, type = &quot;const&quot;)<br>lagselect$selection</pre><p>Since 5 came up in the Hannan Quinn and the Final Prediction error, we choose to use 4 lags. 4 lags is expected given that the frequency of the data is quarterly. Now that we have our lag selection done, we can move on to specifying the test. As we mentioned, there are two variants of the Johansen test. These are the maximum eigenvalue and the trace statistic approach. Conveniently, the ca.jo() command allows us to specify these with ease.</p><p>We start off with the trace statistic approach. Again, the ca.jo() command implores the Johansen cointegration methodology on our system (dset). We use the “trace” statistic approach specified as the type in this case. Next, we specify that our specification has a constant (ecdet = “const”) and that we are using 4 lags.</p><pre>ctest1t &lt;- ca.jo(dset, type = &quot;trace&quot;, ecdet = &quot;const&quot;, K = 4)<br>summary(ctest1t)</pre><p>If you ran the test properly, you should see the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*dzxEnvfhxe2J9ILKM2YD_g.png" /><figcaption>Johansen Cointegration Test Result</figcaption></figure><p>In the table, you should see 4 columns. The test column contains the test statistics, while the three other columns contain the critical values at a 10 percent, 5 percent, and a 1 percent level. For this case, as standard practice, we often use the 5 percent critical value as reference. The r in the table represents the rank and we know that this is some indication of the number of cointegrating relationships. When r = 0, the test stat 87.77 &gt; 22. This means that we reject the null hypothesis which suggests that r &gt; 0. As such, there is some cointegration present. When r &lt;1, 21.64 &gt; 15.67. This again means that we reject the null hypothesis which suggests that r &gt; 1. Lastly, when r &lt; 2, we fail to reject the null hypothesis because 7.89 &lt; 9.24. Therefore, we conclude that there are at most 2 cointegrating relationships present.</p><p>We can also run the test using the maximum eigenvalue variant using the commands below.</p><pre>ctest1e &lt;- ca.jo(dset, type = &quot;eigen&quot;, ecdet = &quot;const&quot;, K = 4)<br>summary(ctest1e)</pre><p>As we can see, we have similar results as with the trace approach. Overall, we can conclude that there are at least two cointegrating relationships present. By now, you will have connected the dots that these two relationships are likely prices and the money supply and prices and GDP. We will get into that later on once we formally estimate a VECM.</p><p>For a more illustrative explanation, check out my YouTube video linked below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVjMLj7crVkw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVjMLj7crVkw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVjMLj7crVkw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/325214a2a37498a6d7b5e003eeea1ddc/href">https://medium.com/media/325214a2a37498a6d7b5e003eeea1ddc/href</a></iframe><h3>References</h3><p>[1] Brooks, C. <em>Introductory econometrics for finance</em>.(2019) Cambridge university press.</p><p>[2] Hamilton, J. Time series econometrics. (1994) <em>Princeton U. Press, Princeton</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6744ee253012" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/long-run-linkages-a-briefer-on-the-johansen-cointegration-methodology-6744ee253012">Long Run Linkages: A Briefer on the Johansen Cointegration Methodology</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching for the Best Forecasting Model: A Comparison of Different Univariate Forecasting Models]]></title>
            <link>https://medium.com/data-science/f-forecasting-5d23341462eb?source=rss-d96cd0c6d923------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d23341462eb</guid>
            <category><![CDATA[univariate-forecasting]]></category>
            <category><![CDATA[inflation-targeting]]></category>
            <category><![CDATA[sarima]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[econometrics]]></category>
            <dc:creator><![CDATA[Justin Eloriaga]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 01:45:41 GMT</pubDate>
            <atom:updated>2020-06-22T18:20:34.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>The easiest, most comprehensive guide to univariate forecasting using AR, MA, ARIMA, and SARIMA.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*iedphvSqGgK21sfC-iA_oQ.png" /></figure><p>Forecasting may be a daunting challenge, especially to those with only a few or no backrgound in statistics. But I think it is much easier that people think it is. In this article, I will go through the basic univariate forecasting models and forecast a variable with relative ease.</p><h3>The Basic Models</h3><p>There are two basic models in univariate forecasting. The first is the autoregressive model which makes use of past values of the forecast variable and the moving average model which uses past values of a white noise error term.</p><p>The <strong>autoregressive model</strong> looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*9Q4JI7SfkCotI9TCeq5O4Q.png" /><figcaption>Autoregressive Model</figcaption></figure><p>Notice that the model just uses the past (lagged) values of the forecast variable (y). We use <em>p</em> number of lags, <em>p </em>being determined by some tests.</p><p>The <strong>moving average model</strong> looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*edSB5MwIZqTGf5taET3PYA.png" /><figcaption>Moving Average Model</figcaption></figure><p>Like the AR, the MA uses past values but instead of the forecast variable, it uses error terms. We use <em>q</em> number of lags, <em>q</em> being determined by some tests.</p><p>We can combine both the autoregressive and moving average models in a model called the ARMA. However, it is often the case that our forecast variable is non-stationary. This means that the series often contains and upward or downward trend. To alleviate this, we can difference the series in order to eliminate those upward or downward movements to stationarize the series. In doing so, we generate the ARIMA model or Autoregressive Integrated Moving Average. Some time series variables may have seasonality like sales or revenue which often spike up during holiday months. To accommodate this, we have a generalized variant of the ARIMA called the SARIMA which incorporates seasonal lags as well.</p><p>The <strong>ARIMA</strong> Model looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*PrF7lTeDq2f6nOargQCWHg.png" /><figcaption>ARIMA Model in Lag Operator Notation</figcaption></figure><p>In this model, we difference the series <em>d number of times </em>until it becomes stationary<em>. </em>The phi and theta components represent the AR and MA models, respectively.</p><p>The <strong>SARIMA</strong> Model looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*5181u1BlSFFsnPUYQ00Osw.png" /><figcaption>SARIMA Model in Lag Operator Notation</figcaption></figure><p>This is merely a generalization of the ARIMA but adds seasonal differences, seasonal moving average lags, and seasonal autoregressive lags.</p><h3>Preliminaries</h3><p>Our goal is to forecast the next month’s inflation rate. What you should have is the comma-separated values file (.csv) of the Monthly Inflation Rate of the Philippines from January 2000 until April 2020. The file name is InflationRateLecture.csv. For the full series, you can download it from the Bangko Sentral ng Pilipinas Key Statistical indicators page. You should also have a copy of R and RStudio installed on your Mac or PC. If this is your first time using R, fear not, just merely follow the codes below and you should be fine.</p><p>The first step is to install the necessary packages. For this example, we would need to install the required packages. These are the following: tidyverse for general data manipulation and urca, forecast, TSstudio, and tseries for the necessary forecasting commands. Feel free to explore the various functions you can get out of these.</p><p>Generate a new script so that you can keep track of things. The first order of business is installing the required packages. We can do that in the tools tab and finding the packages manually, or you can just run the commands that follow. Note that this may take some time to install depending on your internet connection.</p><pre>install.packages(&quot;tidyverse&quot;)<br>install.packages(&quot;urca&quot;) <br>install.packages(&quot;forecast&quot;) <br>install.packages(&quot;tseries&quot;) <br>install.packages(&quot;TSstudio&quot;)</pre><p>After installation, you must now tell R that you are about to use these packages. We do this by invoking the library() function. Consider this like taking a book from a library you want to borrow and use for a specific study session.</p><pre>library(tidyverse)<br>library(urca)<br>library(forecast)<br>library(tseries) <br>library(TSstudio)</pre><p>After you run all of these commands, you should be ready to run all necessary commands afterward. If in case you close your R session in the middle of forecasting, merely use the library commands once again to reload the packages. No need to reinstall (unless an update to a package is available).</p><h4>Loading the Dataset</h4><p>A simple way to load the dataset is using the file.choose() function which opens up a dialogue box similar to what we are accustomed to when opening files. It is important that we store the dataset in an object so we can refer to it later. First, we load the dataset and store it in an object. For this tutorial, I’ll name the object as “inflation” but you can name it anything you want. The codes and dataset can be found here</p><p><a href="https://drive.google.com/drive/folders/11RZI8p-qCvwLAmdro93FnslQLxCO39Ef?usp=sharing">https://drive.google.com/drive/folders/11RZI8p-qCvwLAmdro93FnslQLxCO39Ef?usp=sharing</a></p><pre>inflation &lt;- read_csv(file.choose())</pre><p>The read_csv is part of the readr package in R inside tidyverse. This is used to read a csv file and to be able to load it in R. You should notice that a dialogue box should appear prompting you to choose the file. Be sure to pick InflationRateLecture.csv.</p><pre>head(inflation)<br>nrow(inflation)</pre><p>Running the head(inflation) command lists the first 6 rows of the dataset. You should see that the inflation rate in January 2000 is 5.5, February 2000 is 5.6, and so on. The nrow(inflation) gives the total number of rows in the dataset. This suggests that there are 244 time periods (months) in the dataset. You can also view the dataset by looking at the Environment Tab and clicking the grid beside inflation.</p><h4>Declaring a Time Series Object</h4><p>As it stands, the dataset we loaded is a frame. To be able to forecast, we need a series. If you look at the dataset, we are only interested in forecasting the “Rate” variable that is in there. As such, we need to transform that “Rate” variable into a series.</p><pre>inf &lt;- ts(inflation$Rate, start = c(2000,1,5), frequency = 12)</pre><p>We are creating a new object called “inf” which is the series we will use. The ts command creates that object. The first argument in the command is the variable. The $ tells R that we want to get the Rate variable from the dataset inflation. Afterward, we specify the start date which is January 5, 2000. R can automatically detect the end after this. Lastly, we specify the frequency of the series. Since we are dealing with monthly data, the frequency would be 12. If it were quarterly, frequency is 4, weekly would be 52, and bi-annual would be 2.</p><h4>Graphing the Time Series</h4><p>It is important to visualize our series. We can use the autoplot command to do this.</p><pre>autoplot(inf) + ggtitle(&quot;Inflation Rate (Philippines), January 2000 to April 2020&quot;) + labs(x = &quot;Time&quot;, y = &quot;Inflation Rate&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*F_3fMhkdEleL_nTH3rwz-Q.png" /><figcaption>Plot of Inflation Rate</figcaption></figure><p>The command plots the series “inf” with the corresponding title “Inflation Rate (Philippines), January 2000 to April 2020” where the x-axis is labeled Time and the y-axis is labeled Inflation Rate. We use the ggtitle and the labs option for those specifications. If you did it correctly, you should have a graph that looks something like the figure above.We can see the inflationary spike during the Global Financial Crisis, the Taper Tantrum, and the recent TRAIN 1 package that was passed.</p><h3>Forecasting Building Blocks</h3><p>We now move on to generating the ACF and PACF graph and determining whether the series is non-stationary.</p><p>Let us first generate the ACF and the PACF of the inflation rate. Again, the ACF and the ACF can tell us a lot about the properties of the series. Usually, it gives some indication as to the underlying process of the series, whether it is an AR, an MA or an ARMA. Furthermore, we will see what the ACF and PACF of the differenced value of inflation should we deem the series non-stationary.</p><pre>ggAcf(inf) + ggtitle(&quot;ACF of Inflation&quot;)<br>ggPacf(inf) + ggtitle(&quot;PACF of Inflation&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*r3cHL_o_UleZFOOIU-MFyA.png" /><figcaption>ACF and PACF (Levels)</figcaption></figure><p>The ACF in the figure is geometrically decaying while the PACF registers an immediate cutoff. If we recall our last lecture on the ACFand PACF, this is consistent with an AR process. While it is not definitive, this gives us a clue of what the underlying process might be. In the ACF, notice that the first until eleventh lag is statistically significant (beyond the blue confidence band). We can also see that some partial autocorrelations are significant such as the first, second, and fourteenth.</p><h4>Differencing the Series</h4><p>One way to alleviate non-stationarity is by differencing the series. To do this, we use the diff() command.</p><pre>dinf &lt;- diff(inf)<br>ggAcf(dinf) + ggtitle(&quot;ACF of Inflation (Differenced)&quot;) <br>ggPacf(dinf) + ggtitle(&quot;PACF of Inflation (Differenced)&quot;)</pre><p>The first command utilizes the diff() function which differences the series and creates an object “dinf” which is the differenced value of inflation. By default, it differences once but we can set it to difference twice or whatever number of times specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*tWVNecNqaKb73A4kPOR_ZA.png" /><figcaption>ACF and PACF (Differenced)</figcaption></figure><p>Similar to the levels, we can see that the ACF is geometrically decaying while an immediate cutoff is seen in the PACF. This is more evidence in support of an AR process. However, notice that not many lags are significant. This is some signal that the series has been “stationary” so to speak which forces it to display properties of covariance stationarity. We will explore more into this as we go along.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*W3FHEaIBYsWbpyWlCzGgFQ.png" /><figcaption>Level vs. Differenced Inflation</figcaption></figure><p>Comparing the level values and the differenced values of inflation yield some interesting results. First, there is evidence of non-stationarity using a simple graphical look. However, we can’t be too sure until we conduct formal statistical testing. Secondly, notice that there are still wild spikes (outliers) in the differenced series. These may be indicators for structural breaks which we would need to account for should they be present.</p><h4>Decomposition of the Time Series</h4><p>It is also important to see a proper decomposition of the time series we have. These components are the trend, seasonality, and random components in the series. Fortunately, there are commands in R that graph this automatically for us.</p><pre>ts_decompose(inf, type = &quot;additive&quot;, showline = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*5_E611satTNw5tIDN2H2Iw.png" /><figcaption>Decomposition of the Series</figcaption></figure><p>The ts_decompose command in the library TSstudio gives us a good visualization of the components of the series. This command will segment the series into the observed, trend, seasonal, and random components of the series. Notice that there is some observed seasonality present, likely every August or September. The reason for which I will leave for you to figure out. The decompose command is in TSstudio is far more interactive allowing you to hover your cursor around the graph (generated by plot.ly, a fun graphics library) and dig into the series. We will be using this more as we go along.</p><h3>Tests for Non-stationarity</h3><p>We will use three most popular tests in testing for non-stationarity. These are the Augmented Dickey-Fuller, the Phillips Perron, and the KPSS test. Bear in mind that the ADF and PP tests are unit root tests. As such, their null hypothesis is non-stationarity while their alternative is stationary. Conversely, the KPSS test is a stationarity test in which its null hypothesis is stationarity while its alternative hypothesis is non-stationarity.</p><h4>Augmented Dickey-Fuller Test</h4><p>The command to do the ADF test is adf.test() in R. We will use this test on the series using both the alternative hypothesis of stationarity. We will run this on both the raw and differenced series.</p><pre>adf.test(inf) <br>adf.test(inf, k = 1)<br>adf.test(inf, k = 2)<br>adf.test(dinf)</pre><p>Notice that when we ran the first line, there was a prompt suggesting that the series was stationary. The same is true for when we tested the fourth line. While inflation’s differenced variable is certainly stationary, the value of the level may be very deceiving. As we had said earlier, the limitation of the ADF test is that you have to specify the lag order. These tests (the first and third) were conducted in the sixth lag. If we use a more realistic lag say 1 or 2, the series was determined to be non-stationary.</p><h4>Phillips-Perron Test</h4><p>For the Phillips Perron test, we use the pp.test() command. Unlike the ADF test, we no longer need to specify the lag order and is more general.</p><pre>pp.test(inf)<br>pp.test(dinf)</pre><p>The results of the PP test are fairly conclusive. We see that at levels, the series is non-stationary as we fail to reject the null hypothesis. Once it is differenced, the series is stationary. As such, when we start building a forecasting model, we would need to difference inflation in order to stationarize it.</p><h4><strong>Kwiatkowski-Phillips-Schmidt-Shin Test</strong></h4><p>Lastly, we turn to the KPSS Test. Again, bear in mind that the null hypothesis of this test is stationarity and the alternative is non-stationarity. The command for the KPSS test is kpss.test(). We can specify an option called null to be “trend” or “level” or both. For this case, let’s just leave it at the default which considers both.</p><pre>kpss.test(inf)<br>kpss.test(dinf)</pre><p>As expected, we find that the level series is not stationary. Curiously, the test also finds the differenced series is non-stationary. Still, we can refer as well to the results of the ADF and the PP tests as a backup for our claim that the differenced series is stationary.</p><h3>Forecasting Proper</h3><p>Let us now move on to the forecasting proper. First, let us forecast in-sample before we do an out of sample forecast. As we mentioned in the first section, the reason for forecasting in-sample is to see the quality of the generated model and for us to compare different forecasting models and their estimates against actual realized values. We will use the forecast quality indicators discussed in the last chapter. Finally, towards the end, we will forecast inflation for the next year using the best forecasting model we determined.</p><h4>Splitting the Dataset into Training and Testing Sets</h4><p>Firstly, let’s divide the dataset into two samples, a training sample, and a testing sample. The training sample is the available data we have to forecast. The testing sample is data that is already realized (i.e. we already know the series values) but we holdout to test the quality of forecasting models. While before, this step used to be a pain, with R, it’s a breeze. We use the ts_split command to do this.</p><pre>split_inf &lt;- ts_split(inf, sample.out = 12)</pre><pre>training &lt;- split_inf$train <br>testing &lt;- split_inf$test</pre><pre>length(training)<br>length(testing)</pre><p>We create an object called split_inf using the ts_split function which is essentially inf but partitioned into two. The object inf is divided into two parts where the testing set is given by the command sample.out. We set the sample.out equal to 12 which translates to 12 months or a year. Hence, we want our testing (validation) period to be equal to a year. After this, we create two objects (training and testing) which creates two separate series. Using the length command, we can determine how many periods there are in each of the generated series. You will notice that the training dataset has 232 periods while the testing dataset has 12 periods (the same as the number specified by the sample.out option).</p><h4>Diagnosing the Training Set</h4><p>It is important to have at least some idea of what model to implement. To do this, we need to try and diagnose the training dataset we have to see if we can come up with suggestions as to which model may fit the series. To do this, we implore the use of the arima_diag() command.</p><pre>arima_diag(training)</pre><p>Running this yields us the figure to follow. Since this was created using plot.ly, it is quite interactive. We can see that it shows us the values of the training dataset as well as the associated ACF and PACF. It also shows us a graph of the differenced training series. What we can see is that the ACF is geometrically declining and an immediate cutoff is seen in the PACF. This is similar to the pattern we expect from an AR model. To determine a guess of the number of lags to use, notice that in the PACF, the first two lags are still significant. After the second lag, the majority of the remaining lags are insignificant. For now, let us peg our guess at two autoregressive lags. Notice also that in the PACF and ACF, there are red data points. These red data points indicate the potential for a seasonal lag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*ZzJKuG85M7VCdosywpcpgw.png" /><figcaption>ARIMA Diagnostic Plot</figcaption></figure><h4>Building the Forecast Model</h4><p>Let us try to forecast three models with three varying specifications. The three models we will try to use are</p><p>· An ARIMA(2,1,1)</p><p>· A SARIMA(2,1,1)(1,0,0)</p><p>· The model determined most fit using the auto.arima() function</p><p>For the first model, we will try to use 2 autoregressive lags since this is what the PACF is indicating. We will difference the series once because we know that at levels, the series is non-stationary as seen in the results of the ADF, PP, and KPSS tests. We guess that we have 1 moving average lag. For the second model, we will use the same specification as the first except that we add a seasonal autoregressive lag. Lastly, for the third model, we use the built-in auto.arima() function in R to take the guesswork out of choosing which lag specification is best.</p><p>Let us move to Model 1. We create an object called arima211 and use the arima() command to model. The first option in the arima() command is training which is the series we will be using. The order option specifies the order of the ARIMA, in this case, we specify an ARIMA with two autoregressive lags, 1 difference to stationarize (i.e. the series is integrated of order 1), and 1 moving average lag. The autoplot() command checks whether the stability conditions have been met. This is the stationarity condition laid out in section two. Since we are dealing with the inverse roots, all inverse roots must be inside the unit circle. Lastly, the check_res commands provide diagnostics on the residuals, which we want to be white noise. Model 2 is structured the same way except that we add a seasonal order when we invoke the arima() command. In that case, we add 1 seasonal autoregressive lag. Model 3 is structured the same way except we let R decide the order using the auto.arima() command. The option seasonal = TRUE just ensures that it can choose a SARIMAmodel if it deems it the most optimal.</p><pre>#For Model 1</pre><pre>arima211 &lt;- arima(training, order = c(2,1,1))<br>autoplot(arima211)<br>check_res(arima211)</pre><pre>#For Model 2 </pre><pre>sarima2111 &lt;- arima(training, order = c(2,1,1), seasonal = list(order = c(1,0,0)))<br>autoplot(sarima2111)<br>check_res(sarima2111)</pre><pre>#For Model 3</pre><pre>auto &lt;- auto.arima(training, seasonal = TRUE)<br>auto #We obtained a SARIMA(2,1,0)(2,0,1) based on auto.arima()<br>autoplot(auto)<br>check_res(auto)</pre><p>If you did it correctly, you should be greeted with the figures to follow. Notice that for all three models, the roots are inside the unit circle, as such, the models have passed the stationarity criterion suggesting that there are no more unit roots. Looking at the residual plots, we see that the residuals are generally white noise for all the three models. We do note however that there are some lags which are marginally outside the confidence band, but certainly, model 2 and model 3 produce more white noise errors vis-a-vis model 1 which has an ACF which is quite significant at the 12th lag. This red lag is a seasonal lag which is an indication that a seasonal model is more adept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*xEmPtIdC6DwxYTmoLLxt3Q.png" /><figcaption>Inverse AR and MA Roots</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*7vTgjpfRtdetCf-Cb-nPUw.png" /><figcaption>Residual Diagnostics</figcaption></figure><h4>Generating the Forecasts and Forecast Evaluation</h4><p>Now we get to the moment of truth. Let us now generate the forecasts using each model and evaluate them against the baseline. The commands for each model are structured similarly. First, we create three objects, namely, fcast1, fcast2, and fcasta, which represent the forecasts for each model. Each object is made using the forecast() function which has two options. The first is we key in what model it will use to forecast. The second is the number of periods to forecast. Since the test dataset is 12 periods long, we set the horizon <em>h</em> to 12. Next, we use the test_forecast() command to compare the forecast against the actual value. The command generates an interactive graph and compares each forecast against the actual value while also revealing key forecast quality indicators at every data point. Lastly, thee accuracy() command generates the full average of the forecast indicators which we discussed in the last section. The first option in the accuracy() command is the forecast generated by each model is compared to the test or validation series.</p><p>We can see the graphs of the actual vs forecasting values in the figure to follow. What we notice is that it seems that Model 3 which uses the specification generated by the auto.arima() command seems best based on fit. Notice that when we generated these graphs, we can hover on each data point and it will give us.</p><pre>#For Model 1</pre><pre>fcast1 &lt;- forecast(arima211, h = 12)<br>test_forecast(actual = inf, forecast.obj = fcast1, test = testing)<br>accuracy(fcast1,testing)</pre><pre>#For Model 2</pre><pre>fcast2 &lt;- forecast(sarima2111, h = 12)<br>test_forecast(actual = inf, forecast.obj = fcast2, test = testing)<br>accuracy(fcast2,testing)</pre><pre>#For Model 3</pre><pre>fcasta &lt;- forecast(auto, h = 12)<br>test_forecast(actual = inf, forecast.obj = fcasta, test = testing)<br>accuracy(fcasta,testing)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*PClVBAwFNVAQbrq7m9S53w.png" /><figcaption>Forecast vs. Actual</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*jggHMEO3J1zSXePmhmAzjw.png" /><figcaption>Forecast Indicators</figcaption></figure><p>Further using the accuracy() command, we can see the forecast statistics comparison of each model. The forecast indicators are seen in the table to follow produced by the accuracy() command. We can see an improvement from model 1 to 2 and from model 2 to 3. This suggests that adding a season lag was vital and that the model generated by the auto.arima() seems to be the most optimal based on these indicators.</p><h3>Out of Sample Forecasting</h3><p>Now that we know what the best model is for forecasting, we shall now generate an out-of-sample forecast. In this, we don’t know the actual values of the series. We can only use whatever information we have to forecast the future. This is, essentially, the forecasting you have been looking forward to.</p><h4>Generating the Optimal Fit</h4><p>Similar to generating the model, we create an object wherein the model of choice is stored. Instead of using the training data, we use the whole series of inflation which is inf. We then test for the inverse AR and MA roots as well as the residuals.</p><pre>finalfit &lt;- auto.arima(inf, seasonal = TRUE)<br>autoplot(finalfit)<br>check_res(finalfit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*nz3Pl_bN7dM6i_ra6qwjlQ.png" /><figcaption>Final Fit Diagnostics</figcaption></figure><p>We find that all inverse roots are within the AR and MA unit circle. As such, we have satisfied the stability condition, there are no longer any unit roots. On the residual diagnostics, while there are still a few significant lags, it is generally white noise already.</p><h3>Generating the Out-of-Sample Forecast</h3><p>We now forecast using our chosen model. The commands below will generate the forecast. As inflation is usually re-forecasted, let us set a short horizon of 4 months ahead. Then, let us see its forecast for the May to August 2020 inflation rates. The summary() command lists the point forecasts and the confidence interval for the next four months.</p><pre>fcastf &lt;- forecast(inf, model = finalfit, h = 4)<br>plot_forecast(fcastf)<br>summary(fcastf)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*Jng0APCUMEOrCnHsdh3lKA.png" /><figcaption>Forecast for May to August 2020 Inflation Rate</figcaption></figure><p>We can see that the forecasted values for May (2.0 percent), June (2.1 percent), July (2.1 percent), and August (2.1 percent) are fairly consistent with the BSP’s inflation target and other forecast estimates. Notice too that as the horizon gets larger and larger, the confidence band expands along with it. Good job, you just forecasted your first key economic variable.</p><h3>Conclusion</h3><p>We have now forecasted out-of-sample and have obtained values for the next four months. We shall see if our forecasts are indeed reliable through time. Suffice to say, forecasting is a trial and error process but I hope you saw that the indicators and built-in functions were able to take the guesswork out of the process. Still, forecasting is also an art, and specifying lags and conditions based on economic structure and intuition may play a pivotal role in improving forecasts. We shall see more of this as we discuss multivariate forecasting.</p><p>For now, it is recommended that you experiment with the many tools you now have learned and see if you can come up with a model that provides even better forecast quality indicators than even the model selected using the auto.arima() function. That is certainly possible and it just goes to show that while machines have advanced so much, there is still room for art in a place riddled full of math and science. One just needs to look for the motivation to do so.</p><p>For a more hands on approach, I made videos on this very article which can be found on my YouTube Channel.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIiZ_SNBlZhw%3Fstart%3D1%26feature%3Doembed%26start%3D1&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIiZ_SNBlZhw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIiZ_SNBlZhw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d895827295d5312a10a467fd2fdbdc4/href">https://medium.com/media/1d895827295d5312a10a467fd2fdbdc4/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiIYZn2eCKdo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiIYZn2eCKdo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiIYZn2eCKdo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b5826f7f3fbdc40a2bc5855d736fe9a/href">https://medium.com/media/4b5826f7f3fbdc40a2bc5855d736fe9a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJujzVxxTxX0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJujzVxxTxX0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJujzVxxTxX0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/072a2d2da11071d56b3cc9074657db10/href">https://medium.com/media/072a2d2da11071d56b3cc9074657db10/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4upPIMvi0Lk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4upPIMvi0Lk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4upPIMvi0Lk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbd558005287ae8c071117bc2e6962c2/href">https://medium.com/media/fbd558005287ae8c071117bc2e6962c2/href</a></iframe><h3>References</h3><p>[1] Brooks, C. <em>Introductory econometrics for finance</em>.(2019) Cambridge university press.</p><p>[2] Hamilton, J. Time series econometrics. (1994) <em>Princeton U. Press, Princeton</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d23341462eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/f-forecasting-5d23341462eb">Searching for the Best Forecasting Model: A Comparison of Different Univariate Forecasting Models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive on Vector Autoregression in R]]></title>
            <link>https://medium.com/data-science/a-deep-dive-on-vector-autoregression-in-r-58767ebb3f06?source=rss-d96cd0c6d923------2</link>
            <guid isPermaLink="false">https://medium.com/p/58767ebb3f06</guid>
            <category><![CDATA[monetary-policy-analysis]]></category>
            <category><![CDATA[irf]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[vector-autoregression]]></category>
            <category><![CDATA[econometrics]]></category>
            <dc:creator><![CDATA[Justin Eloriaga]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 07:22:05 GMT</pubDate>
            <atom:updated>2020-06-21T23:31:33.886Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let the data speak! Let us purge a-priori expectations.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMAyG_r8WY2rbknpKG_pQg.png" /></figure><h3>What is a VAR?</h3><p>Christopher Sims proposed the Vector Autoregression which is a multivariate linear time series model in which the endogenous variables in the system are functions of the lagged values of all endogenous variables. This allows for a simple and flexible alternative to the traditional structural system of equations. A VAR could model macroeconomic data informatively, without imposing very strong restrictions or relationships. Essentially, it is macroeconomic modeling without much of the <em>a-priori</em> expectations getting in the way.</p><h3>Uses of VAR</h3><p>VARs are very useful especially in the field of macroeconomics. It has been used widely in simulating macroeconomic shocks to the real economy and has been used heavily in policy simulations and forecasting. This is the thrust and the main use of the Vector Autoregression. Firstly, it is a sophisticated <em>forecasting tool</em>. We will show how VARs can be much better than standard univariate forecasting models, especially in determining the long-run. The majority of empirical studies on forecasting suggest that the VAR has already eclipsed the traditional univariate forecasting models and theory-based structural equation models.</p><p>Apart from forecasting, VARs are also useful tools for <em>structural analysis</em>. We note that VARs can investigate the response to shocks. It can pinpoint sources of fluctuations that traditional univariate models fail at. Moreover, VARs can help distinguish between competing theoretical models.</p><h3>How does VAR look like</h3><p>As we have mentioned previously, the VAR is a multivariate linear time series model where the endogenous variables in the system are functions of the lagged values of all endogenous variables. Said simply, the VAR is essentially a generalization of the univariate autoregressive model. Commonly, we notate a VAR as a VAR(p) where <em>p</em> denotes the number of autoregressive lags in the system. Consider a VAR system with only two variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*CU7P_KIxA3Jzel436lX0uQ.png" /><figcaption>Bivariate VAR system</figcaption></figure><p>We can also write this in matrix form as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*OkfaSuyr-TSx7dXHcBFLQQ.png" /><figcaption>VAR in Matrix Form</figcaption></figure><p>The estimation of a VAR is an <em>Equation by Equation OLS</em>. We essentially run OLS on each equation. What we find is that estimates are consistent as only the lagged values of the endogenous variables are on the right-hand side of the equation. Moreover, estimates are also efficient in that all equations have identical regressors which minimizes the variation in each one. Doing this suggests that it is essentially equivalent to a <em>generalized least squares</em>. The assumption of no-serial correlation also holds in this regard.</p><h3>Using the Sims (1992) Framework</h3><p>We will now apply the numerous concepts learned in VAR in an actual example. In particular, we will be using a framework developed by Sims (1992) using Philippine data. In this model, we will be using four variables. These are the following:</p><p><em>Overnight Reverse Repurchase Rate (RRP)</em> which is set by the Bangko Sentral ng Pilipinas. This is, by all accounts, the main policy rate that the Philippine central bank controls.</p><p><em>M1 Money Supply</em> which can be obtained from the BSP’s website</p><p><em>CPI Inflation Rate</em> which is reported monthly by the Philippine Statistics Authority and measures the relative increase in prices based on a Laspeyres price index.</p><p><em>Industrial Production</em> which measures the value of all goods in the industrial sector.</p><p>We will first estimate a standard VAR which reflects a key economic response. It is believed in theory and by Sims that shocks to the nominal interest rate represent monetary policy shocks. A shock to the policy variable affects all other variables contemporaneously. The variable is affected by all the others within the period, and is order last. Lastly, the central bank only observes non-policy variables with a lag.</p><h3>Preliminaries</h3><p>We start again by installing the required packages and loading them using the library() command. For this part, we need to install the “vars” package which will have a host of commands necessary for us to run the VAR and SVAR and the diagnostic tests and applications to follow. We then see the plots of each variable and judge some initial conditions such as non-stationarity.</p><p>As said, we need to install the “vars” package. Use the install.packages(“vars”) command to do this. After this, we will load this package together with our standard suite of packages and libraries for us to continue on the estimation.</p><pre>install.packages(&quot;vars&quot;)<br>library(vars)<br>library(mFilter)<br>library(tseries)<br>library(TSstudio)<br>library(forecast)<br>library(tidyverse)</pre><p>After installation and loading, it is time to load our dataset. We will use the file Sample_VAR.csv which contains the data on all the variables from January 2003 until February 2020. The data is monthly and is publicly available, obtained from the BSP and PSA. We use the read_csv() command to read the dataset and the file.choose() command to open up a dialogue box for us to select our data. In this case, we place the dataset under an object named “mp”. Name it whatever you want, if you’d like. We then use the head() command to see the first few rows of the dataset to inspect if it loaded correctly. The files and code can be found here: <a href="https://drive.google.com/drive/u/0/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn">https://drive.google.com/drive/u/0/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn</a></p><pre>mp &lt;- read_csv(file.choose()) <br>head(mp)</pre><p>Next, we need to declare each variable in the dataset as a time series using the ts() command. We use the $ symbol to call a variable from the dataset. All variables start in the year 2003 with the same day and month of January 1. We set the frequency to 12 since we are dealing with monthly data.</p><pre>lnIP &lt;- ts(mp$lnIP, start = c(2003,1,1), frequency = 12)<br>M1 &lt;- ts(mp$M1, start = c(2003,1,1), frequency = 12)<br>CPI &lt;- ts(mp$CPI, start = c(2003,1,1), frequency = 12)<br>RRP &lt;- ts(mp$RRP, start = c(2003,1,1), frequency = 12)</pre><p>We can also visualize our series using the autoplot() or ts_plot() command. As before, the ts_plot() command is a more interactive version using the plot.ly package as base.</p><pre>ts_plot(lnIP)<br>ts_plot(M1)<br>ts_plot(CPI)<br>ts_plot(RRP)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frlgFOwU_fOoT4cByxSPqQ.png" /><figcaption>Time Series Plots</figcaption></figure><p>Again, it is important to assess whether the variables under study are stationary or not. As we have said, having stationary variables is of an ideal case in our VAR even if we can run it without these. As we have been accustomed to, let us use the tests we are familiar with. For simplicity, we will use the Phillips Perron so we would not need to specify the number of lags.</p><pre>pp.test(lnIP)<br>pp.test(M1)<br>pp.test(CPI)<br>pp.test(RRP)</pre><p>In the estimation above, we find that all variables are non-stationary variables. Remember that a rejection of the null hypothesis suggests the data is stationary. Nevertheless, we can still run a VAR estimation using these level data. However, you may opt to difference the data and see if that provides better results and forecasts.</p><h3>Estimation Proper</h3><p>The time has come to formally estimate our VAR. We will first need to bind our VAR variables together to create the system. After this, we will select the optimal lag order behind the VAR we will be using. We will then run an unrestricted VAR estimation and see the results. Lastly, we will run some diagnostics such as tests for autocorrelation, stability, and normality.</p><p>The first step is to build the VAR system. This is done through the cbind() command which essentially groups our time series. We will order this in the desired order that we see fit. We will store this in an object called “v1”. We will then rename the variables as the list to follow using the colnames() command.</p><pre>v1 &lt;- cbind(RRP, lnM1, CPI, lnIP)<br>colnames(v1) &lt;- cbind(&quot;RRP&quot;,&quot;M1&quot;,&quot;CPI&quot;, &quot;lnIP&quot;)</pre><p>After we bind the variables and created the VAR system, we will determine some lag order which we will use. To do this, we use VARselect() command and use the v1 object we just created. We will use a maximum lag order of 15. The command will automatically generate the preferred lag order based on the multivariate iterations of the AIC, SBIC, HQIC and the FPE.</p><pre>lagselect &lt;- VARselect(v1, lag.max = 15, type = &quot;const&quot;)<br>lagselect$selection</pre><p>Running the commands suggests that the lag order to be used is 2. In the study of Sims, he used 14 lags which may have been more adept in US data as the effects reflect greater persistence.</p><p>We will now estimate a model. We estimate the VAR using the VAR() command. The p option refers to the number of lags used. Since we determined that 2 lags is best, we set this to 2. We let it be a typical unrestricted VAR with a constant and we will specify no exogenous variables in the system. The summary() command lists down the results.</p><pre>Model1 &lt;- VAR(v1, p = 2, type = &quot;const&quot;, season = NULL, exog = NULL) </pre><pre>summary(Model1)</pre><p>We do not typically interpret the coefficients of the VAR, we typically interpret the results of the applications. You will see however that we have coefficients there for each lag and each equation in the VAR. Each equation represents an equation in the VAR system.</p><h3>Model Diagnostics</h3><p>One assumption is that the residuals should, as much as possible, be <strong>non-autocorrelated</strong>. This is again on our assumption that the residuals are white noise and thus uncorrelated with the previous periods. To do this, we run the serial.test() command. We store our results in an object Serial1.</p><pre>Serial1 &lt;- serial.test(Model1, lags.pt = 5, type = &quot;PT.asymptotic&quot;)</pre><pre>Serial1</pre><p>In this test, we see that the residuals do not show signs of autocorrelation. However, there is a chance that if we change the maximum lag order, there could be a sign of autocorrelation. As such, it is best to experiment with multiple lag orders.</p><p>Another aspect to consider is the presence of <strong>heteroscedasticity</strong>. In time series, there is what we call<em> ARCH effects </em>which are essentially clustered volatility areas in a time series. This is common is series’ such as stock prices where massive increases or decreases could be seen when an earnings call is released. In that area or window, there could be excessive volatility thereby changing the variance of the residuals, far from our assumption of constant variance. We have models to account for these which are the conditional volatility models which we will discuss in a later section.</p><pre>Arch1 &lt;- arch.test(Model1, lags.multi = 15, multivariate.only = TRUE)</pre><pre>Arch1</pre><p>Again, the results of the ARCH test signify no degree of heteroscedasticity as we fail to reject the null hypothesis. Therefore, we conclude that there are no ARCH effects in this model. However, like with the autocorrelation test, it is possible to register lag effects at subsequent lag orders.</p><p>A soft pre-requisite but a desirable one is the normality of the distribution of the residuals. To test for the normality of the residuals, we use the normality.test() command in R which brings in the Jarque-Bera test, the Kurtosis Test, and the Skewness test.</p><pre>Norm1 &lt;- normality.test(Model1, multivariate.only = TRUE)</pre><pre>Norm1</pre><p>Based on all the three results, it appears that the residuals of this particular model are not normally distributed.</p><p>The stability test is some test for the presence of structural breaks. We know that if we are unable to test for structural breaks and if there happened to be one, the whole estimation may be thrown off. Fortunately, we have a simple test for this which uses a plot of the sum of recursive residuals. If at any point in the graph, the sum goes out of the red critical bounds, then a structural break at that point was seen.</p><pre>Stability1 &lt;- stability(Model1, type = &quot;OLS-CUSUM&quot;)</pre><pre>plot(Stability1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYw-ZufF0-ar5XswgrImKA.png" /><figcaption>Stability Test</figcaption></figure><p>Based on the results of the test, there seems to be no structural breaks evident. As such, our model passes this particular test</p><h3>Policy Simulations</h3><p>We will now move on to policy simulations in a regular VAR. We will do the three main ones, which are the Granger Causality, Forecast Error Variance Decomposition, as well as the Impulse Response Functions.</p><p>We will test for an overall Granger causality testing each variable in the system against all the others. As we said, there could be a unidirectional, bidirectional, or no causality relationships between variables.</p><pre>GrangerRRP&lt;- causality(Model1, cause = &quot;RRP&quot;)<br>GrangerRRP</pre><pre>GrangerM1 &lt;- causality(Model1, cause = &quot;M1&quot;)<br>GrangerM1</pre><pre>GrangerCPI &lt;- causality(Model1, cause = &quot;CPI&quot;)<br>GrangerCPI</pre><pre>GrangerlnIP &lt;- causality(Model1, cause = &quot;lnIP&quot;)<br>GrangerlnIP</pre><p>The command used is suitable for bivariate cases but we will use it in a system of four for now. Some of you may try reducing the VARmodels to two variables to see more straightforward interpretations. To perform the Granger causality test, we use the causality() command. Based on the results, we conclude that CPI Granger causes the other variables but the converse is not seen. Maybe granular variable to variable rather than variable to group relationships would prove more significant.</p><p>We will now turn to our impulse response functions. While we can get more impulse response functions than the ones below, we will zero in on the impact of a shock in RRP to the other variables in the system</p><pre>RRPirf &lt;- irf(Model1, impulse = &quot;RRP&quot;, response = &quot;RRP&quot;, n.ahead = 20, boot = TRUE)<br>plot(RRPirf, ylab = &quot;RRP&quot;, main = &quot;RRP&#39;s shock to RRP&quot;)</pre><pre>M1irf &lt;- irf(Model1, impulse = &quot;RRP&quot;, response = &quot;M1&quot;, n.ahead = 20, boot = TRUE)<br>plot(M1irf, ylab = &quot;M1&quot;, main = &quot;RRP&#39;s shock to M1&quot;)</pre><pre>CPIirf &lt;- irf(Model1, impulse = &quot;RRP&quot;, response = &quot;CPI&quot;, n.ahead = 20, boot = TRUE)<br>plot(CPIirf, ylab = &quot;CPI&quot;, main = &quot;RRP&#39;s shock to CPI&quot;)</pre><pre>lnIPirf &lt;- irf(Model1, impulse = &quot;RRP&quot;, response = &quot;lnIP&quot;, n.ahead = 20, boot = TRUE)<br>plot(lnIPirf, ylab = &quot;lnIP&quot;, main = &quot;RRP&#39;s shock to lnIP&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAqnoBWr7vv-dx25qKldCg.png" /><figcaption>Impulse Response Functions</figcaption></figure><p>The irf() command generates the IRFs where we need to specify the model, what the impulse series will be, and what the response series will be. We can also specify the number of periods ahead to see how the impact or shock will progress over time. We then use the plot() command to graph this IRF. The results from the IRF are quite puzzling. Remember that such an increase in the RRP cannot be a reaction of the BSP to what is happening the other variables since it was ordered first. As you can see, in (a), the shock to the RRP will of course increase RRP, this would then lead to a slight fall in the money supply (b) and a fall in output (d). What we also find is that prices increase in the short run but decrease moderately thereafter. According to Christopher Sims, this is a puzzling result. The results suggest that prices go up after an RRP hike. If a monetary contraction reduces aggregate demand (lnIP) thereby lowering output, it cannot be associated with inflation. He goes on to say that the VAR could potentially be miss-specified. For instance, there could be a leading indicator for inflation to which the BSP will reach and which was wrongly omitted from the VAR. The BSP could know that inflationary pressures are about to arrive and counteract that by raising the interest rate.</p><p>If you recall basic macroeconomics, a contractionary monetary policy like raising the policy rate (interest rate) will lead to a fall in output. That fall in output should generally weigh inflation down and cause prices to decrease. However, what we see in this model is that prices have increased, for the most part, which is puzzling. Supposedly, exogenous movements of the policy interest rate in the previous estimation were not totally exogenous. In other words, the exogenous shocks were not properly identified. To solve this, Sims added commodity prices to the mix.</p><p>We now turn our attention to the forecast error variance decomposition. Again, we can trace the development of shocks in our system to explaining the forecast error variances of all the variables in the system. To do this, we use the fevd() command. Like the IRF, we can also specify the number of periods ahead. For this case, let us just zero in on RRP.</p><pre>FEVD1 &lt;- fevd(Model1, n.ahead = 10)<br>FEVD1<br>plot(FEVD1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1-in-n00UNAw3MNbTNdmA.png" /><figcaption>Forecast Error Variance Decomposition</figcaption></figure><p>We can clearly see in window (a) that the forecast error of the RRP (column 1) at short horizons is due to itself. This is the case because the RRP was placed first in the ordering and that no other shocks affect RRP contemporaneously. At longer horizons say 10 months, we can see that CPI now accounts for about 16 percent and that money supply accounts for about 2 percent respectively.</p><h3>Forecasting using VAR</h3><p>As we have said, we can also forecast using VAR. To do this, we use the predict() command and generate something called a <em>fan chart</em> which is commonly used in identifying the confidence level of forecasts igraphically. We will set the forecast horizon to 12 months ahead or a full-year forecast.</p><pre>forecast &lt;- predict(Model1, n.ahead = 12, ci = 0.95)</pre><pre>fanchart(forecast, names = &quot;RRP&quot;, main = &quot;Fanchart for RRP&quot;, xlab = &quot;Horizon&quot;, ylab = &quot;RRP&quot;)</pre><pre>fanchart(forecast, names = &quot;M1&quot;, main = &quot;Fanchart for M1&quot;, xlab = &quot;Horizon&quot;, ylab = &quot;M1&quot;)</pre><pre>fanchart(forecast, names = &quot;CPI&quot;, main = &quot;Fanchart for CPI&quot;, xlab = &quot;Horizon&quot;, ylab = &quot;CPI&quot;)</pre><pre>fanchart(forecast, names = &quot;lnIP&quot;, main = &quot;Fanchart for lnIP&quot;, xlab = &quot;Horizon&quot;, ylab = &quot;lnIP&quot;)</pre><pre>forecast</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMAyG_r8WY2rbknpKG_pQg.png" /><figcaption>Forecasts in VAR</figcaption></figure><p>The figure shows that RRP is expected to decrease slightly then increase, M1 is expected to decrease and so is IP. CPI is expected to decrease slightly in the first few months then rebound moderately. Take note that this is different from the IRFs simply because we are using VAR as a forecasting tool instead of a policy tool.</p><h3>Conclusion</h3><p>All in all, I hope with this example you can see the many use cases of the VAR methodology and why many economists continue to use it for its flexibility. Apart from just a sheer forecasting model, it has many more applications such as policy simulation, linear causality analysis, and forecast error decomposition. Before the creation of the VAR, economics pinned everything on theory and practice and believed that economic variables had to live by their code. In practice, however, we know that economic variables behave in manners that may differ from our preconceived notions. As such, setting prior expectations may have deceived us.</p><p>For a more hands-on approach, consider watching the videos I made on this topic which are uploaded on YouTube.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUYRFYWNxX4c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUYRFYWNxX4c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUYRFYWNxX4c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e4817b9be50e6d6f441bd8ae61c6a57/href">https://medium.com/media/6e4817b9be50e6d6f441bd8ae61c6a57/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqyGlB4cqZ9Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqyGlB4cqZ9Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqyGlB4cqZ9Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f77c79eb19c79c218418801d537a85dd/href">https://medium.com/media/f77c79eb19c79c218418801d537a85dd/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaX8IANxjucA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaX8IANxjucA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaX8IANxjucA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/be1bd5cddc759589fe0df40ec1873f72/href">https://medium.com/media/be1bd5cddc759589fe0df40ec1873f72/href</a></iframe><h3>References</h3><p>[1] Lütkepohl, H. <em>New introduction to multiple time series analysis</em>.(2005). Springer Science &amp; Business Media.</p><p>[2] Enders, W. <em>Applied econometric time series</em>. (2008) John Wiley &amp; Sons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58767ebb3f06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-deep-dive-on-vector-autoregression-in-r-58767ebb3f06">A Deep Dive on Vector Autoregression in R</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structural Vector Autoregression in R]]></title>
            <link>https://levelup.gitconnected.com/structural-vector-autoregression-in-r-5d6dbfc56499?source=rss-d96cd0c6d923------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d6dbfc56499</guid>
            <category><![CDATA[structural-var]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[svars]]></category>
            <category><![CDATA[monetary-policy]]></category>
            <category><![CDATA[irf]]></category>
            <dc:creator><![CDATA[Justin Eloriaga]]></dc:creator>
            <pubDate>Wed, 17 Jun 2020 02:35:25 GMT</pubDate>
            <atom:updated>2020-06-22T12:13:50.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to the Structural Vector Autoregression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TL8hAqYi0Qcwyej9xh7Bg.png" /></figure><h4>The <strong>Structural Vector Autoregression</strong> is a very flexible tool especially for the analysis of policy actions on the real economy.</h4><h3>Overview</h3><p>The structural VAR is a variation of the unrestricted VAR model which is a way to forecast multiple variables in a system. While in a regular unrestricted VAR, we allow the data to speak and act for itself, the structural VAR, on the other hand, imposes key restrictions that set conditions as to how certain variables would behave.</p><h3>Uses of a Structural VAR</h3><p>The Structural VAR is used for the two main macroeconomic policy considerations, namely, for Fiscal Policy and for Monetary Policy.</p><p><strong>For Fiscal Policy</strong>: Suppose the government is anticipating a reduction in private demand caused by a lockdown or quarantine measure. It may try to model the sequence of events which affect key variables, hence, the structure is essentially modeling the timeline of reaction. For example, suppose quarantine measures reduced private demand. The government would increase public spending thus increasing the deficit. However, the output continues to decline. Adding a structure prevents the conclusion that increasing government expenditure causes output to decline which is an erroneous conclusion. This is some conclusion you can expect in a regular unrestricted VAR.</p><p><strong>For Monetary Policy</strong>: Suppose the central bank is anticipating some increase in inflation. To curb this increase, the central bank can raise its main policy rate. However, it just so happens that inflation continues to increase. Like with Fiscal Policy, using an SVAR prevents us from having the conclusion that increasing the policy rate increases inflation, which is again erroneous. Adding a structure adds restrictions which essentially creates an a-priori timeline by which our model behaves.</p><p>We will be using a roughly similar methodology to the VAR but adding some restrictions on the values and some more conditions. These restrictions are based on economic foundations or underpinning intuition or theory. Fortunately, there is a library of commands in R for this very purpose. For our example, we will be dealing with three variables, namely, the output gap (y), the inflation rate (pi), and interest rate (RRP) which is (r).</p><h3>Preliminaries</h3><p>As always, we start by loading and installing the packages, transforming the variables to time series objects, seeing these variables graphically, and checking some general conditions. We start by loading and installing the required packages. Like always, we will load the packages using the <em>library()</em> command and install using the <em>install.packages()</em> command.</p><pre>library(urca)<br>library(vars)<br>library(tseries)<br>library(TSstudio)<br>library(forecast)<br>library(tidyverse)<br>library(svars)</pre><p>We load our dataset which is the SVAR_Philippines.csv file. This contains the data points in our study which run from Q1 2000 to Q12020. The frequency of this data is quarterly. All datapoints are available at the BSP website except for the Output Gap which was estimated by the author using a Kalman Filtering technique. The file can be found in the link below. <a href="https://drive.google.com/drive/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn?usp=sharing">https://drive.google.com/drive/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn?usp=sharing</a></p><pre>macro &lt;- read_csv(file.choose())<br>head(macro)</pre><p>After loading the dataset, we need to turn our variables into time series variables useable for our SVAR. Like always, we use thee ts() command to do this.</p><pre>y &lt;- ts(macro\$`Output Gap`, start = c(2000,1,1), frequency = 4)<br>pi &lt;- ts(macro\$CPI, start = c(2000,1,1), frequency = 4)<br>r &lt;- ts(macro\$RRP, start = c(2000,1,1), frequency = 4)</pre><p>As always, we can plot each time series using the <em>ts_plot()</em> command. It is important to visualize the series to verify the loading of the series and to get a feel for certain characteristics. You may opt to use the <em>ts_decompose()</em> command to see a better decomposition. The plots of the series are seen in the header image.</p><pre>ts_plot(y, title = &quot;Output Gap&quot;, Xtitle = &quot;Time&quot;, Ytitle = &quot;Output Gap&quot;)</pre><pre>ts_plot(pi, title = &quot;Inflation Rate&quot;, Xtitle = &quot;Time&quot;, Ytitle = &quot;Inflation Rate&quot;)</pre><pre>ts_plot(r, title = &quot;Overnight Reverse Repurchase Rate&quot;, Xtitle = &quot;Time&quot;, Ytitle = &quot;RRP&quot;)</pre><h3>Setting Restrictions in the SVAR</h3><p>We will now differentiate from the VAR by adding restrictions. We will need to build the matrix of restrictions and subsequently estimate the structural coefficients by using the recursive ordering method discussed in the last section.</p><p>We now come to a crucial part of our analysis in SVAR which is setting the value of matrix of restrictions. As we have said, this matrix is the matrix of contemporaneous shocks affecting the variables in the systems. In identifying the coefficients, we need to set restrictions and these restrictions are defined by an economic principle. In the matrix we will build, we will impose the behavior that if <em>r</em> is the policy rate, we could say that a reaction or a movement in <em>r</em> would be attributable to shocks in <em>pi</em> and <em>y</em> in the same period. We will structure the matrix such that the policy rate <em>r</em> only affects <em>pi</em> and <em>y</em> with a lag. Hence, we formulate the matrix as the form below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*HxElfIOyslLYf55veHTs1Q.png" /><figcaption>Matrix of Restrictions</figcaption></figure><p>This restriction suggests that a contemporaneous shock in <em>y</em> affects both <em>pi</em> and $r$ in the same period and the lagged values in the system. Further, <em>pi</em> shocks only affect <em>r</em> contemporaneously but not <em>y</em>. Likewise, it also affects the lagged values in the system. Lastly <em>r</em> doesn’t affect <em>y</em> and <em>pi</em> contemporaneously but affects the lagged values in the system. We first define a matrix as an object “amat” and set the conditions in the code.</p><pre>amat &lt;- diag(3)<br>amat[2,1] &lt;- NA<br>amat[3,1] &lt;- NA<br>amat[3,2] &lt;- NA<br>amat</pre><p>The <em>diag()</em> command creates a 3 x 3 identity matrix. The next three commands modify the lower triangular to have values of NA. Essentially, we are identifying the parameters which can freely take any value. Hence, after we estimate, the NA will get filled up. Meanwhile, we retain the upper triangular as zero which represents the restrictions we imposed akin to the economic intuition we pre-specified in the matrix.</p><h3>Building the Model</h3><p>After this, we will now specify the ordering we want. To reflect the economic intuition of our restriction, we have to follow the order of output gap first, followed by inflation, and lastly by the policy rate. Again, think of this Choleskey ordering as a timeline of events or a sequencing of events.</p><pre>sv &lt;- cbind(y, pi, r)<br>colnames(sv) &lt;- cbind(“OutputGap”, “Inflation”, “RRP”)</pre><p>We now move on to determining the lag ordering using the <em>VARselect() </em>command. Since this is quarterly data, we expect a lag order of around four to six.</p><pre>lagselect &lt;- VARselect(sv, lag.max = 8, type = &quot;both&quot;)<br>lagselect$selection<br>lagselect$criteria</pre><p>Based on the AIC, SBIC, HQIC, and FPE, it appears that the oprimal lag order is five lags. Hence, let us build our model to have 5 lags.</p><p>To estimate the SVAR, we first need to estimate a reduced form VAR which is why we have a VAR() estimation here. Again, we set the number of lags to 5. Afterwhich, we use the SVAR() command and set the Amat option to our amat object. Doing this should yield us our estimated SVAR restrictions matrix.</p><pre>Model1 &lt;- VAR(sv, p = 5, season = NULL, exog = NULL, type = &quot;const&quot;) </pre><pre>SVARMod1 &lt;- SVAR(Model1, Amat = amat, Bmat = NULL, hessian = TRUE, estmethod = c(&quot;scoring&quot;, &quot;direct&quot;))</pre><pre>SVARMod1</pre><p>If you did this correctly, you should see that we estimated our structural parameters to be 0.21, 0.09, and -0.11 which can be found as the estimated restrictions matrix.</p><h3>Policy Applications</h3><p>We will now move on to the applications of SVAR. It is expected that before this, you first diagnose the VAR akin to the steps we used in the last section. In this part, we will focus mainly on two main applications, which are the Impulse Response Functions and the Forecast Error Variance Decompositions.</p><p>We will zero in on how the intuition played a role in building the IRFs and seeing how the policy rate <em>r</em> would respond to shocks in the system. To run the IRF, we simply use the<em> irf()</em> command and set the impulse and responses as we wish. As there are three variables in the system, there are a total of nine (3²) possible IRFs to come by. We will zero in on three and I hope you’ll understand the reaction clearly based on the restrictions we imposed.</p><pre>SVARog &lt;- irf(SVARMod1, impulse = &quot;OutputGap&quot;, response = &quot;OutputGap&quot;)</pre><pre>plot(SVARog)</pre><pre>SVARinf &lt;- irf(SVARMod1, impulse = &quot;OutputGap&quot;, response = &quot;Inflation&quot;)</pre><pre>plot(SVARinf)</pre><pre>SVARrrp &lt;- irf(SVARMod1, impulse = &quot;Inflation&quot;, response = &quot;RRP&quot;)</pre><pre>plot(SVARrrp)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-avz-s9CQg-OTPr1a5MTUA.png" /><figcaption>Impulse Response Functions</figcaption></figure><p>The impluse responses are very intuitive. If a shock in the output gap starts the sequence, it is expected to increase the output gap. This increase in the output gap increases the inflationary gap which means that the economy is producing more than it was potentially expected to which may cause the economy to overheat. This higher than expected output gap will push inflation upward as productivity continues to increase. Since the central bank sees that output gap increases and that inflation increases, it can accommodate these by increasing the RRP which is exactly what is seen in window (c). This is typically the monetary response of a central bank and was validated by our SVAR.</p><p>We will turn to the FEVD decomposition in the SVAR. To do this, we use the <em>fevd()</em> command and set a horizon ahead. In this case, we set it to ten periods ahead. We then use the <em>plot()</em> command to plot the values which are seen in figure to follow.</p><pre>SVARfevd &lt;- fevd(SVARMod1, n.ahead = 10)<br>SVARfevd<br>plot(SVARfevd)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*e-83FOK4DrBnYtVV_6nc_w.png" /><figcaption>Forecast Error Variance Decomposition</figcaption></figure><p>If you will notice, the FEVD of Output Gap is explained purely by Output Gap. This is just because we ordered this one first. If you will see the shocks in the other variables, they reflect that majority of the forecast error variance decomposition was because we pushed that variable as the first in the order.</p><p>Overall, I hope you can see how adding a structure to the VAR which are the different restrictions we imposed was able to yield a key policy result. Therefore, I hope you are able to realize that SVARs are incredibly useful policy tools for government in conducting policy and controlling for unobservables.</p><p>For a more hands on approach, I made a YouTube video to better guide you on this concept.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhwB2TbhqgH0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhwB2TbhqgH0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhwB2TbhqgH0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4917fd5440458cdd9c28e341e5815ee8/href">https://medium.com/media/4917fd5440458cdd9c28e341e5815ee8/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d6dbfc56499" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/structural-vector-autoregression-in-r-5d6dbfc56499">Structural Vector Autoregression in R</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Bitcoin Prices using Prophet in R]]></title>
            <link>https://medium.com/analytics-vidhya/forecasting-bitcoin-prices-using-prophet-in-r-858e10cfb942?source=rss-d96cd0c6d923------2</link>
            <guid isPermaLink="false">https://medium.com/p/858e10cfb942</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[bitcoin-forecasting]]></category>
            <dc:creator><![CDATA[Justin Eloriaga]]></dc:creator>
            <pubDate>Wed, 17 Jun 2020 01:52:16 GMT</pubDate>
            <atom:updated>2020-06-19T13:39:57.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c712mB3MJnNELwQvtKEdCg.png" /><figcaption>Dynamic Forecast using Prophet</figcaption></figure><p>Forecasting can be quite daunting, especially given the knowledge required to be able to identify forecasting strategies which may involve heavy concepts with a rigorous mathematical underpinning. Fortunately, the bright devs over at Facebook developed a simple forecasting library called Prophet which makes even a forecasting newbie look like a pro. I’d like to preface this by saying that the Prophet model is not perfect, nor can it be considered best in most cases. It is usually used for models with a fair bit of seasonality, trends, and drifts. Such is the case with business sales data in which higher values may be seen during the holiday quarter or on weekends as compared to regular quarters or weekdays.</p><p>To start, we need to <strong>install the prophet library </strong>in R. This involves using the <em>install.packages()</em> command.</p><pre>install.packages(&#39;prophet&#39;)</pre><p>We then <strong>call</strong> this package for use using the <em>library()</em> command.</p><pre>library(prophet)<br>library(tidyverse)</pre><p>For this example, we will use the <em>Daily Bitcoin Adjusted Close values</em> which can be obtained in Yahoo Finance. A link to the dataset can be found here which is located in the folder called Forecasting with Prophet</p><p><a href="https://drive.google.com/drive/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn">https://drive.google.com/drive/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn</a></p><pre>bitcoin &lt;- read.csv(file.choose())<br>head(bitcoin)<br>tail(bitcoin)</pre><p>We use the <em>read.csv()</em> command to import the dataset. The <em>file.choose() </em>command opens up the dialogue box for you to be able to select the dataset. We created an object named bitcoin to store the dataset. The <em>head() </em>command brings up the first few rows while the <em>tail()</em> command shows the last few row. Note that the ds column contains dates and the y column contains the Bitcoin closing price. By convention, prophet reads the ds column as a date and the y column as the series. As such, you may need to rename columns to fit with this convention. Moreover, you may need to set the date to <em>YYYY-mm-dd</em> format as this is the format recognized by prophet.</p><pre>Model1 &lt;- prophet(bitcoin)<br>Future1 &lt;- make_future_dataframe(Model1, periods = 31)</pre><p>We will now <strong>build the model</strong>. We use the <em>prophet()</em> command to create a dynamic forecasting model. We will store this model as an object named Model1. After which, we will add 31 periods to the sample using the <em>make_future_dataframe()</em> command. This will be filled up with future forecasted values in the next step.</p><pre>Forecast1 &lt;- predict(Model1, Future1)<br>tail(Forecast1[c(&#39;ds&#39;,&#39;yhat&#39;,&#39;yhat_lower&#39;,&#39;yhat_upper&#39;)])</pre><p>We will <strong>predict</strong> the forecasted values using <em>predict()</em> and create an object Forecast1 to store these. The <em>tail</em> command will list the last few forecasted observations which contain the details on the date (ds), the forecasted value (that), and the confidence interval of the estimate.</p><pre>dyplot.prophet(Model1, Forecast1)</pre><p>We use the <em>dyplot.prophet() </em>command to <strong>graph out the forecast</strong> which yields us the figure at the start of the article. We can also adjust the span by using the slider in the bottom of the plot area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VV0fsIEmdlG33JmjjkWJDQ.png" /><figcaption>Forecasted Values</figcaption></figure><p>As we can see, there seems to be an upward trend to Bitcoin prices for the next month. You may view the specific values by hovering around the area or by printing the values in R. We can also see certain seasonality or day of the week effects by using the <em>prophet_plot_components()</em> command.</p><pre>prophet_plot_components(Model1, Forecast1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*tKY_fQhtlG024g19z2yW1A.png" /><figcaption>Decomposing the Forecast Series</figcaption></figure><p>I hope you were able to see how easy it is to forecast using the prophet function and is ideal for generating quick reports wherein a simply analysis is needed. For a more hands on approach, I made a video detailing all commands which is seen below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4784Ait88G8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4784Ait88G8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4784Ait88G8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f73a9abd029a16df0fe92fd031d954cc/href">https://medium.com/media/f73a9abd029a16df0fe92fd031d954cc/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=858e10cfb942" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/forecasting-bitcoin-prices-using-prophet-in-r-858e10cfb942">Forecasting Bitcoin Prices using Prophet in R</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>