<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/simulations-to-explore-excessive-lagged-x-variables-in-time-series-modelling/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://ellisp.github.io/blog/2017/03/12/stepwise-timeseries"> Peter's stats stuff - R</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I was once in a meeting discussing a time series modelling and forecasting challenge where it was suggested that “the beauty of regression is you just add in more variables and more lags of variables and try the combinations until you get something that fits really well”. Well, no, it doesn’t work like that; at least not in many cases with realistically small social science or public policy datasets. Today’s post looks at one particular trap – a modelling strategy that tries more lags of explanatory variables than are justified given the amount of data available.</p>
<h2>The data</h2>
<p>Imagine you have a time series <code>y</code> and two candidate explanatory variables <code>x1</code> and <code>x2</code>. We have values of <code>x1</code> and <code>x2</code> for the future – perhaps because they are genuinely known in advance, perhaps generated by independent forecasts. Let’s say there is good theoretical or subject matter reason for thinking there is a relationship between them, but it’s clearly not a simple one. It’s possible the relationship is lagged – perhaps <code>x1</code> and <code>x2</code> are leading economic indicators and <code>y</code> is the result of decisions people take based on the history of the <code>x</code>s. The job is to forecast <code>y</code> conditional on <code>X</code>, and if possible generate some insight about the structural relationship of the <code>x</code>s and <code>y</code>, and be prepared for some scenarios where <code>x1</code> or <code>x2</code> might change and we want to see the impact on <code>y</code>.</p>
<p>Here’s an example of something we might see:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0087-origdata.svg"></p>
<p>Those series were generated by me. We have 110 historical observations, and a forecast period of 12 for which there are observations for <code>x1</code> and <code>x2</code> but not <code>y</code>. Each series is in reality completely independent of the others, something I’ve done deliberately to illustrate the point I’m about to make. For those with an interest, they are all <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average">ARIMA</a>(2,1,1) models with the same parameterisation but different random sequences behind them.</p>
<h2>Basic forecasting models</h2>
<h3>Univariate</h3>
<p>A simple strategy for forecasting <code>y</code> would be to find the best ARIMA model that fits the data using Rob Hyndman’s <code>auto.arima</code> algorithm, which has been shown to perform well. We can do this with or without considering the x variables at all. If we ignore the x variables, we get a forecast that looks like this:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0087-fc1.svg"></p>
<div>
<pre><code>Series: y 
ARIMA(0,1,2)                    

Coefficients:
         ma1     ma2
      1.4250  0.4415
s.e.  0.0865  0.0867

sigma^2 estimated as 0.7736:  log likelihood=-141.77
AIC=289.54   AICc=289.77   BIC=297.62
</code></pre>
</div>
<p>In fact, because we secretly know how the data was generated, we know that this is a good model of this particular data. The <code>auto.arima</code> algorithm picked up that the data was non-stationary and needed to be differenced once before modelling; but it got the “wrong” specification of the number of auto-regressive and moving average terms to include (this <a target="_blank" rel="nofollow" href="http://ellisp.github.io/blog/2015/09/30/autoarima-success-rates">isn’t unusual</a>, nor is it necessarily a problem). By default it uses a stepwise method to identify the best combination of up to five auto-regressive parameters and five moving average parameters.</p>
<h3>Linear regression with time series error terms</h3>
<p>A second, nearly as simple method of forecasting would be to fit a <a target="_blank" rel="nofollow" href="http://robjhyndman.com/hyndsight/arimax/">linear regression with an ARIMA time series error term</a>. The <code>auto.arima</code> method will do this, and look after all the tests of non-stationarity and difference in response that are required. It gives easily interpretable coefficients for the relationship between <code>y</code> and <code>x1</code> and <code>x2</code>. Here’s what we see in our case:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0087-fc2.svg"></p>
<div>
<pre><code>Series: y 
Regression with ARIMA(0,1,2) errors 

Coefficients:
         ma1     ma2      x1       x2
      1.4202  0.4349  0.0371  -0.0364
s.e.  0.0870  0.0878  0.0867   0.0796

sigma^2 estimated as 0.785:  log likelihood=-141.59
AIC=293.18   AICc=293.77   BIC=306.64
</code></pre>
</div>
<p>Basically, the model has correctly identified there is a weak or no relationship between the <code>x</code>s and <code>y</code>. The momentum of <code>y</code> itself is the main predictor of future <code>y</code>, and this shows in the forecasts which are only marginally different from our first univariate case. Using the Akaike Information Criterion, the model with x regressors is inferior to the simpler model.</p>
<h2>More complex models</h2>
<p>A problem with above approaches is that they don’t take into account the (wrongly) suspected lagged relationship between the <code>x</code>s and <code>y</code>, other than through the current/simultaneous in time relationship. There’s an obvious solution – introduce lagged terms of <code>x1</code> and <code>x2</code> into the regression. There are a variety of ways of doing this and specialist R packages like <code>dynlm</code>, <code>dyn</code> and <code>dse</code> that I’m not going to introduce because I want things from here on to be simple and explicit. See the <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/views/TimeSeries.html">CRAN time series task view</a> for a starting point to explore further.</p>
<p>I want to focus on <strong>how problematic this can be</strong>. How many parameters in our model are we prepared to estimate, given our 110 historical data points? Frank Harrell’s advice in <em>Regression Modeling Strategies</em> is:</p>
<blockquote>
<p>“Studies in which models are validated on independent datasets have shown that in many situations a fitted regression model is likely to be reliable when the number of predictors (or <em>candidate</em> predictors if using variable selection) <em>p</em> is less than <em>m/10</em> or <em>m/20</em>, where <em>m</em> is the limiting sample size”</p>
</blockquote>
<p><em>Frank Harrell</em></p>
<p>Our “limiting sample size” is 110, and our 110 time series observations are actually worth less than 110 independent ones would be because each observation contains only marginal new information for us; knowing the value at time <em>t</em> gives us a good indication of where it will be at time <em>t+1</em>, something not the case in more independent sampling situations.</p>
<p>This suggests we should be considering five or six, or eleven at the very most, candidate variables for inclusion. Just by using <code>auto.arima</code> we’ve looked at ten parameters (five autoregression lags, and five moving average parameters), and by adding in <code>x1</code> and <code>x2</code> we’ve definitely reached our maximum. Ouch. As we’re usually not interested in individual AR and MA parameters we can perhaps get away with stretching a point, but there’s no get out of jail card here that means we can meaningfully keep adding in more explanatory variables.</p>
<p>So what happens if we proceed anyway? To check this out, I tried three strategies:</p>
<ol>
<li>Created variables for up to 20 lag periods for each of the three original variables, leaving us with 62 candidate predictors, and fit a model by ordinary least squares.</li>
<li>Take the full model from above and use stepwise selection to knock out individual variables with p values &lt; 0.05 (the conventional cut-off point for a variable being “not significant”). I had to torture R’s <code>step</code> function to do this, because quite rightly it prefers to choose models based on AIC rather than individual p-values; I wanted to mimic the p-value method for demonstration purposes.</li>
<li>Take the full model and use lasso-style shrinkage/regularisation on the 62 predictors’ coefficients.</li>
</ol>
<p>Of those methods, I think #1 and #2 are both potentially disastrous and will lead to overfitting (which means that the model will perform badly when confronted with new data ie in predicting our twelve future points). Stepwise variable selection is particularly pernicious because it can create the illusion that “significant” relationships between the variables have been found. At the end of a stepwise procedure, software can provide you with F tests, t tests and p-values but they are invalid because you have chosen the variables remaining in the model precisely because they score well on those tests. In today’s case, here is what we end up with.</p>
<div>
<pre><code>Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  0.23003    0.10375   2.217 0.029642 *  
y_d_lag_1    1.15802    0.09837  11.772  &lt; 2e-16 ***
x1_d_lag_1   0.27902    0.07908   3.528 0.000718 ***
y_d_lag_2   -1.04546    0.14885  -7.023 8.39e-10 ***
y_d_lag_3    0.78761    0.16493   4.775 8.68e-06 ***
y_d_lag_4   -0.44729    0.14928  -2.996 0.003704 ** 
x1_d_lag_4   0.24485    0.07325   3.342 0.001298 ** 
y_d_lag_5    0.33654    0.10118   3.326 0.001366 ** 
x1_d_lag_6   0.19763    0.06565   3.010 0.003555 ** 
x2_d_lag_8  -0.11246    0.05336  -2.107 0.038422 *  
x2_d_lag_16 -0.17330    0.06347  -2.731 0.007876 ** 
x1_d_lag_17  0.22910    0.07073   3.239 0.001789 ** 
x1_d_lag_18 -0.18724    0.07147  -2.620 0.010643 *  
x2_d_lag_19 -0.11310    0.05536  -2.043 0.044546 *  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.8418 on 75 degrees of freedom
Multiple R-squared:  0.7594,	Adjusted R-squared:  0.7177 
F-statistic: 18.21 on 13 and 75 DF,  p-value: &lt; 2.2e-16
</code></pre>
</div>
<p>A high R-squared, even a high “Adjusted R-squared” and many variables with p values well below the 0.05 cut-off. So (for example) the unwary analyst would conclude we have strong evidence that <code>y</code> is impacted by <code>x2</code> 16 periods ago and <code>by x1</code> 17 periods ago, but mysteriously not by anything from lags 9 through 15.</p>
<p>Remember that the true data generation process had <em>zero</em> influence from <code>x1</code> and <code>x2</code> on <code>y</code> or vice versa.</p>
<p>Working with lags in a time series situation does not give any wild cards that make stepwise selection valid. The usual problems with stepwise selection within a model building strategy apply:</p>
<ol>
<li> values are biased high</li>
<li>The usual F and  test statistics of the final model do not have the claimed distribution</li>
<li>The standard errors of coefficients are biased low and confidence intervals of effects are too narrow</li>
<li>p-values are far too small, do not have the proper meaning, and correction is very difficult</li>
<li>The coefficients of effects that remain in the model are strongly biased away from zero</li>
<li>Variable selection is made arbitrary</li>
<li>The whole process allows us to escape thinking about the problem</li>
</ol>
<p><em>From Harrell’s Regression Modeling Strategies</em>.</p>
<p>In the case of the full model, with 62 variables, the exact problems above do not apply. The p-values for example will be basically ok (and in fact in this case none of the <code>x1</code> and <code>x2</code> lags show up as significant until we start knocking out the variables one at a time). The problem is that with 64 parameters (including the intercept and variance) estimated from only 109 data points (after we have differenced the series to make them stationary), we have extremely high variance and instability in the model.</p>
<p>Shrinkage of the estimated coefficients via the <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Lasso_(statistics)">lasso</a> is one way of fixing this, and indeed the lasso is generally used precisely in this situation of excessive candidate explanatory variables when predictive power is important. We trade off some bias in the coefficients for better stability and predictive power. Using the lasso in this case reduces nearly all the <code>x</code> coefficients to zero, and lags 1 and 2 of the <code>y</code> variable staying in the model as they should.</p>
<h2>Comparison of results</h2>
<p>Here’s the actual forecasts of the five methods we’ve tried so far:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0087-results.svg"></p>
<p>What we see is that the two methods I’ve labelled “bad” give very similar results – a sharp decline. As a result of their overfitting they are both picking up structure in the <code>x</code>s that does not really impact on <code>y</code>.</p>
<p>The three “ok” methods give results that are more in tune with the secret data generating process. The most encouraging thing for me here is the success of the lasso in avoiding the pitfalls of the stepwise method. If there really is a complex lagged relationship between the <code>x</code>s and <code>y</code>, this method of looking at all 62 variables and forcing a relatively stable estimation process at least gives the analyst a sporting chance of finding it. The <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=orderedLasso">orderedLasso</a> R package – which I haven’t tried using yet – looks to take this idea further in implementing the idea of an “Ordered Lasso and Sparse Time-lagged Regression”, and I’m pretty confident is worth a look.</p>
<p><em>Final word</em> – this is an illustration rather than a comprehensive demonstration. Obviously, the thing to be done to really prove the issues would be to generate many such cases, including “real” future values of <code>y</code> for test purposes, and test the error rates of the forecasts from the different methods. I don’t particularly feel the need to do that, but maybe one day if I run out of things to do will give it a go.</p>
<h2>Code</h2>
<figure>
<pre><code data-lang="r"><span>library</span><span>(</span><span>tidyverse</span><span>)</span><span>
</span><span>library</span><span>(</span><span>scales</span><span>)</span><span>
</span><span>library</span><span>(</span><span>forecast</span><span>)</span><span>
</span><span>library</span><span>(</span><span>glmnet</span><span>)</span><span>
</span><span>library</span><span>(</span><span>forcats</span><span>)</span><span>
</span><span>library</span><span>(</span><span>directlabels</span><span>)</span><span>
</span><span>#===========generate data============
</span><span>n</span><span> </span><span>&lt;-</span><span> </span><span>110</span><span>
</span><span>h</span><span> </span><span>&lt;-</span><span> </span><span>12</span><span>
</span><span>set.seed</span><span>(</span><span>123</span><span>)</span><span>
</span><span>y</span><span> </span><span>&lt;-</span><span> </span><span>ts</span><span>(</span><span>cumsum</span><span>(</span><span>arima.sim</span><span>(</span><span>model</span><span> </span><span>=</span><span> </span><span>list</span><span>(</span><span>ar</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.5</span><span>,</span><span> </span><span>-0.2</span><span>),</span><span> </span><span>ma</span><span> </span><span>=</span><span> </span><span>0.9</span><span>),</span><span> </span><span>n</span><span> </span><span>=</span><span> </span><span>n</span><span>)</span><span> </span><span>+</span><span> </span><span>0.2</span><span>))</span><span>
</span><span>x</span><span>1</span><span> </span><span>&lt;-</span><span> </span><span>cumsum</span><span>(</span><span>arima.sim</span><span>(</span><span>model</span><span> </span><span>=</span><span> </span><span>list</span><span>(</span><span>ar</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.5</span><span>,</span><span> </span><span>-0.2</span><span>),</span><span> </span><span>ma</span><span> </span><span>=</span><span> </span><span>0.9</span><span>),</span><span> </span><span>n</span><span> </span><span>=</span><span> </span><span>n</span><span> </span><span>+</span><span> </span><span>h</span><span>)</span><span> </span><span>-</span><span> </span><span>0.2</span><span>)</span><span>
</span><span>x</span><span>2</span><span> </span><span>&lt;-</span><span> </span><span>cumsum</span><span>(</span><span>arima.sim</span><span>(</span><span>model</span><span> </span><span>=</span><span> </span><span>list</span><span>(</span><span>ar</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.5</span><span>,</span><span> </span><span>-0.2</span><span>),</span><span> </span><span>ma</span><span> </span><span>=</span><span> </span><span>0.9</span><span>),</span><span> </span><span>n</span><span> </span><span>=</span><span> </span><span>n</span><span> </span><span>+</span><span> </span><span>h</span><span>))</span><span>
</span><span>orig_data</span><span> </span><span>&lt;-</span><span> </span><span>data_frame</span><span>(</span><span>Value</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>y</span><span>,</span><span> </span><span>x</span><span>1</span><span>,</span><span> </span><span>x</span><span>2</span><span>),</span><span>
</span><span>Variable</span><span> </span><span>=</span><span> </span><span>rep</span><span>(</span><span>c</span><span>(</span><span>&quot;y&quot;</span><span>,</span><span> </span><span>&quot;x1&quot;</span><span>,</span><span> </span><span>&quot;x2&quot;</span><span>),</span><span> </span><span>times</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>n</span><span>,</span><span> </span><span>n</span><span> </span><span>+</span><span> </span><span>h</span><span>,</span><span> </span><span>n</span><span> </span><span>+</span><span> </span><span>h</span><span>)),</span><span>
</span><span>TimePeriod</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>1</span><span>:</span><span>n</span><span>,</span><span> </span><span>1</span><span>:</span><span>(</span><span>n</span><span>+</span><span>h</span><span>),</span><span> </span><span>1</span><span>:</span><span>(</span><span>n</span><span>+</span><span>h</span><span>)))</span><span> </span><span>orig_data</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>TimePeriod</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>Value</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>()</span><span> </span><span>+</span><span>
</span><span>facet_wrap</span><span>(</span><span>~</span><span>Variable</span><span>)</span><span> </span><span>+</span><span>
</span><span>ggtitle</span><span>(</span><span>&quot;Original data&quot;</span><span>,</span><span>
</span><span>&quot;Three unrelated (but that is unknown to us) univariate time series&quot;</span><span>)</span><span>
</span><span>X_full</span><span> </span><span>&lt;-</span><span> </span><span>cbind</span><span>(</span><span>x</span><span>1</span><span>,</span><span> </span><span>x</span><span>2</span><span>)</span><span>
</span><span>X_historical</span><span> </span><span>&lt;-</span><span> </span><span>X_full</span><span>[</span><span>1</span><span>:</span><span>n</span><span>,</span><span> </span><span>]</span><span>
</span><span>X_future</span><span> </span><span>&lt;-</span><span> </span><span>X_full</span><span>[</span><span>-</span><span>(</span><span>1</span><span>:</span><span>n</span><span>),</span><span> </span><span>]</span><span>
</span><span># A version that has been differenced once....
</span><span>YX_diff_lags</span><span> </span><span>&lt;-</span><span> </span><span>data_frame</span><span>(</span><span>
</span><span>y_d</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>diff</span><span>(</span><span>y</span><span>),</span><span> </span><span>rep</span><span>(</span><span>NA</span><span>,</span><span> </span><span>h</span><span>)),</span><span>
</span><span>x</span><span>1</span><span>_</span><span>d</span><span> </span><span>=</span><span> </span><span>diff</span><span>(</span><span>x</span><span>1</span><span>),</span><span>
</span><span>x</span><span>2</span><span>_</span><span>d</span><span> </span><span>=</span><span> </span><span>diff</span><span>(</span><span>x</span><span>2</span><span>))</span><span>
</span><span># And has lagged variables up to lag period of 20 for each variable:
</span><span>lagnumber</span><span> </span><span>&lt;-</span><span> </span><span>20</span><span>
</span><span>for</span><span> </span><span>(</span><span>i</span><span> </span><span>in</span><span> </span><span>1</span><span>:</span><span>lagnumber</span><span>){</span><span>
</span><span>YX_diff_lags</span><span>[,</span><span> </span><span>ncol</span><span>(</span><span>YX_diff_lags</span><span>)</span><span> </span><span>+</span><span> </span><span>1</span><span>]</span><span> </span><span>&lt;-</span><span> </span><span>lag</span><span>(</span><span>YX_diff_lags</span><span>$</span><span>y_d</span><span>,</span><span> </span><span>i</span><span>)</span><span>
</span><span>YX_diff_lags</span><span>[,</span><span> </span><span>ncol</span><span>(</span><span>YX_diff_lags</span><span>)</span><span> </span><span>+</span><span> </span><span>1</span><span>]</span><span> </span><span>&lt;-</span><span> </span><span>lag</span><span>(</span><span>YX_diff_lags</span><span>$</span><span>x</span><span>1</span><span>_</span><span>d</span><span>,</span><span> </span><span>i</span><span>)</span><span>
</span><span>YX_diff_lags</span><span>[,</span><span> </span><span>ncol</span><span>(</span><span>YX_diff_lags</span><span>)</span><span> </span><span>+</span><span> </span><span>1</span><span>]</span><span> </span><span>&lt;-</span><span> </span><span>lag</span><span>(</span><span>YX_diff_lags</span><span>$</span><span>x</span><span>2</span><span>_</span><span>d</span><span>,</span><span>i</span><span>)</span><span>
</span><span>}</span><span>
</span><span>names</span><span>(</span><span>YX_diff_lags</span><span>)[</span><span>-</span><span>(</span><span>1</span><span>:</span><span>3</span><span>)]</span><span> </span><span>&lt;-</span><span> </span><span>paste0</span><span>(</span><span>names</span><span>(</span><span>YX_diff_lags</span><span>)[</span><span>1</span><span>:</span><span>3</span><span>],</span><span> </span><span>&quot;_lag_&quot;</span><span>,</span><span> </span><span>rep</span><span>(</span><span>1</span><span>:</span><span>lagnumber</span><span>,</span><span> </span><span>times</span><span> </span><span>=</span><span> </span><span>rep</span><span>(</span><span>3</span><span>,</span><span> </span><span>lagnumber</span><span>)))</span><span>
</span><span>if</span><span>(</span><span>ncol</span><span>(</span><span>YX_diff_lags</span><span>)</span><span> </span><span>!=</span><span> </span><span>3</span><span> </span><span>+</span><span> </span><span>3</span><span> </span><span>*</span><span> </span><span>lagnumber</span><span>){</span><span>
</span><span>stop</span><span>(</span><span>&quot;Wrong number of columns; something went wrong&quot;</span><span>)</span><span>
</span><span>}</span><span>
</span><span>#===================Modelling options========
</span><span>
</span><span>#-------------univariate-----------------
</span><span>mod1</span><span> </span><span>&lt;-</span><span> </span><span>auto.arima</span><span>(</span><span>y</span><span>)</span><span>
</span><span>fc1</span><span> </span><span>&lt;-</span><span> </span><span>forecast</span><span>(</span><span>mod1</span><span>,</span><span> </span><span>h</span><span> </span><span>=</span><span> </span><span>h</span><span>)</span><span>
</span><span>autoplot</span><span>(</span><span>fc1</span><span>)</span><span>
</span><span>#------------xreg, no lags----------------
</span><span>mod2</span><span> </span><span>&lt;-</span><span> </span><span>auto.arima</span><span>(</span><span>y</span><span>,</span><span> </span><span>xreg</span><span> </span><span>=</span><span> </span><span>X_historical</span><span>)</span><span>
</span><span>fc2</span><span> </span><span>&lt;-</span><span> </span><span>forecast</span><span>(</span><span>mod2</span><span>,</span><span> </span><span>xreg</span><span> </span><span>=</span><span> </span><span>X_future</span><span>)</span><span>
</span><span>autoplot</span><span>(</span><span>fc2</span><span>)</span><span>
</span><span>#-----------xreg, lags----------------
</span><span>YX_hist</span><span> </span><span>&lt;-</span><span> </span><span>YX_diff_lags</span><span>[</span><span>complete.cases</span><span>(</span><span>YX_diff_lags</span><span>),</span><span> </span><span>]</span><span>
</span><span>mod3</span><span> </span><span>&lt;-</span><span> </span><span>lm</span><span>(</span><span>y_d</span><span> </span><span>~</span><span> </span><span>.</span><span>,</span><span> </span><span>data</span><span> </span><span>=</span><span> </span><span>YX_hist</span><span>)</span><span>
</span><span>#' Forecast from a regression model with lags one row at a time
#' Assumes the existence of: YX_diff_lags &amp; y.
#' Has to forecast one row at a time, then populate the explanatory data frame
#' with the lagged values possible after that forecast.
</span><span>onerow_forecast</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>model</span><span>){</span><span>
</span><span>prediction_data</span><span> </span><span>&lt;-</span><span> </span><span>YX_diff_lags</span><span>[</span><span>is.na</span><span>(</span><span>YX_diff_lags</span><span>$</span><span>y_d</span><span>),</span><span> </span><span>]</span><span>
</span><span>y_names</span><span> </span><span>&lt;-</span><span> </span><span>names</span><span>(</span><span>YX_diff_lags</span><span>)[</span><span>grepl</span><span>(</span><span>&quot;y_d&quot;</span><span>,</span><span> </span><span>names</span><span>(</span><span>YX_diff_lags</span><span>))]</span><span>
</span><span>for</span><span>(</span><span>i</span><span> </span><span>in</span><span> </span><span>1</span><span>:</span><span>nrow</span><span>(</span><span>prediction_data</span><span>)){</span><span>
</span><span>for</span><span>(</span><span>j</span><span> </span><span>in</span><span> </span><span>2</span><span>:</span><span>nrow</span><span>(</span><span>prediction_data</span><span>)){</span><span>
</span><span>for</span><span>(</span><span>k</span><span> </span><span>in</span><span> </span><span>2</span><span>:</span><span>length</span><span>(</span><span>y_names</span><span>)){</span><span>
</span><span>prediction_data</span><span>[</span><span>j</span><span> </span><span>,</span><span> </span><span>y_names</span><span>[</span><span>k</span><span>]]</span><span> </span><span>&lt;-</span><span> </span><span>prediction_data</span><span>[</span><span>j</span><span>-1</span><span> </span><span>,</span><span> </span><span>y_names</span><span>[</span><span>k</span><span> </span><span>-</span><span> </span><span>1</span><span>]]</span><span>
</span><span>}</span><span>
</span><span>}</span><span>
</span><span>if</span><span>(</span><span>class</span><span>(</span><span>model</span><span>)</span><span> </span><span>==</span><span> </span><span>&quot;cv.glmnet&quot;</span><span>){</span><span>
</span><span>new_y</span><span> </span><span>&lt;-</span><span> </span><span>predict</span><span>(</span><span>model</span><span>,</span><span> </span><span>newx</span><span> </span><span>=</span><span> </span><span>as.matrix</span><span>(</span><span>prediction_data</span><span>[</span><span>i</span><span>,</span><span> </span><span>-1</span><span>]))</span><span>
</span><span>}</span><span> </span><span>else</span><span> </span><span>{</span><span>
</span><span>new_y</span><span> </span><span>&lt;-</span><span> </span><span>predict</span><span>(</span><span>model</span><span>,</span><span> </span><span>newdata</span><span> </span><span>=</span><span> </span><span>prediction_data</span><span>[</span><span>i</span><span>,</span><span> </span><span>-1</span><span>])</span><span> </span><span>}</span><span>
</span><span>prediction_data</span><span>[</span><span>i</span><span> </span><span>,</span><span> </span><span>&quot;y_d&quot;</span><span>]</span><span> </span><span>&lt;-</span><span> </span><span>new_y</span><span>
</span><span>}</span><span>
</span><span># de-diff ie return to the original, non-differenced scale
</span><span> </span><span>fc_y</span><span> </span><span>&lt;-</span><span> </span><span>cumsum</span><span>(</span><span>c</span><span>(</span><span>as.numeric</span><span>(</span><span>tail</span><span>(</span><span>y</span><span>,</span><span> </span><span>1</span><span>)),</span><span> </span><span>prediction_data</span><span>$</span><span>y_d</span><span>))</span><span>
</span><span>return</span><span>(</span><span>fc_y</span><span>[</span><span>-1</span><span>])</span><span>
</span><span>}</span><span>
</span><span>fc3</span><span> </span><span>&lt;-</span><span> </span><span>onerow_forecast</span><span>(</span><span>mod3</span><span>)</span><span>
</span><span>#-------xreg, lags, stepwise----------------
# high value of k to mimic stepwise selection based on p values:
</span><span>mod4</span><span> </span><span>&lt;-</span><span> </span><span>step</span><span>(</span><span>mod3</span><span>,</span><span> </span><span>k</span><span> </span><span>=</span><span> </span><span>4.7</span><span>,</span><span> </span><span>trace</span><span> </span><span>=</span><span> </span><span>0</span><span>)</span><span>
</span><span>fc4</span><span> </span><span>&lt;-</span><span> </span><span>onerow_forecast</span><span>(</span><span>mod4</span><span>)</span><span>
</span><span>#-----------xreg, lags, lasso---------------
# Use cross-validation to determine best value of lambda, for how much
# shrinkage to force:
</span><span>mod5</span><span> </span><span>&lt;-</span><span> </span><span>cv.glmnet</span><span>(</span><span>y</span><span> </span><span>=</span><span> </span><span>YX_hist</span><span>$</span><span>y_d</span><span>,</span><span> </span><span>x</span><span> </span><span>=</span><span> </span><span>as.matrix</span><span>(</span><span>YX_hist</span><span>[</span><span> </span><span>,</span><span> </span><span>-1</span><span>]))</span><span>
</span><span>fc5</span><span> </span><span>&lt;-</span><span> </span><span>onerow_forecast</span><span>(</span><span>mod5</span><span>)</span><span> </span><span>#====================compare results==============
</span><span>p</span><span> </span><span>&lt;-</span><span> </span><span>data_frame</span><span>(</span><span>Univariate</span><span> </span><span>=</span><span> </span><span>fc1</span><span>$</span><span>mean</span><span>,</span><span> </span><span>SimpleXreg</span><span> </span><span>=</span><span> </span><span>fc2</span><span>$</span><span>mean</span><span>,</span><span> </span><span>AllLags</span><span> </span><span>=</span><span> </span><span>fc3</span><span>,</span><span> </span><span>StepLags</span><span> </span><span>=</span><span> </span><span>fc4</span><span>,</span><span> </span><span>LassoLags</span><span> </span><span>=</span><span> </span><span>fc5</span><span>,</span><span>
</span><span>TimePeriod</span><span> </span><span>=</span><span> </span><span>1</span><span>:</span><span>h</span><span> </span><span>+</span><span> </span><span>n</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>gather</span><span>(</span><span>Variable</span><span>,</span><span> </span><span>Value</span><span>,</span><span> </span><span>-</span><span>TimePeriod</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>Judge</span><span> </span><span>=</span><span> </span><span>ifelse</span><span>(</span><span>grepl</span><span>(</span><span>&quot;Lags&quot;</span><span>,</span><span> </span><span>Variable</span><span>)</span><span> </span><span>&amp;</span><span> </span><span>!</span><span>grepl</span><span>(</span><span>&quot;Lasso&quot;</span><span>,</span><span> </span><span>Variable</span><span>),</span><span>
</span><span>&quot;Bad&quot;</span><span>,</span><span> </span><span>&quot;OK&quot;</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>Variable</span><span> </span><span>=</span><span> </span><span>fct_relevel</span><span>(</span><span>Variable</span><span>,</span><span> </span><span>c</span><span>(</span><span>&quot;AllLags&quot;</span><span>,</span><span> </span><span>&quot;StepLags&quot;</span><span>)))</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>TimePeriod</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>Value</span><span>,</span><span> </span><span>colour</span><span> </span><span>=</span><span> </span><span>Variable</span><span>))</span><span> </span><span>+</span><span>
</span><span>facet_wrap</span><span>(</span><span>~</span><span>Judge</span><span>,</span><span> </span><span>ncol</span><span> </span><span>=</span><span> </span><span>1</span><span>)</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>(</span><span>size</span><span> </span><span>=</span><span> </span><span>1.2</span><span>)</span><span> </span><span>+</span><span>
</span><span>scale_colour_brewer</span><span>(</span><span>palette</span><span> </span><span>=</span><span> </span><span>&quot;Set1&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>theme</span><span>(</span><span>legend.position</span><span> </span><span>=</span><span> </span><span>&quot;right&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>(</span><span>data</span><span> </span><span>=</span><span> </span><span>filter</span><span>(</span><span>orig_data</span><span>,</span><span> </span><span>Variable</span><span> </span><span>==</span><span> </span><span>&quot;y&quot;</span><span>),</span><span> </span><span>colour</span><span> </span><span>=</span><span> </span><span>&quot;black&quot;</span><span>,</span><span> </span><span>linetype</span><span> </span><span>=</span><span> </span><span>3</span><span>)</span><span> </span><span>+</span><span>
</span><span>xlim</span><span>(</span><span>c</span><span>(</span><span>0</span><span>,</span><span> </span><span>130</span><span>))</span><span> </span><span>+</span><span>
</span><span>annotate</span><span>(</span><span>&quot;text&quot;</span><span>,</span><span> </span><span>x</span><span> </span><span>=</span><span> </span><span>25</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>15</span><span>,</span><span> </span><span>label</span><span> </span><span>=</span><span> </span><span>&quot;Historical data&quot;</span><span>,</span><span> </span><span>colour</span><span> </span><span>=</span><span> </span><span>&quot;grey40&quot;</span><span>,</span><span> </span><span>family</span><span> </span><span>=</span><span> </span><span>&quot;myfont&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>ggtitle</span><span>(</span><span>&quot;Excessive inclusion of lagged explanatory variables leads to overfitting&quot;</span><span>,</span><span>
</span><span>&quot;Regularization by lasso, or using a simpler model in the first place, gives much better results.&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>caption</span><span> </span><span>=</span><span> </span><span>&quot;Simulations from forecasting one time series based on two unrelated time series.&quot;</span><span>)</span><span>
</span><span>direct.label</span><span>(</span><span>p</span><span>)</span><span>
</span></code></pre>
</figure>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://ellisp.github.io/blog/2017/03/12/stepwise-timeseries"> Peter's stats stuff - R</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/r23mhm5iHHc"></a></div>