<?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 David Starkey on Medium]]></title>
        <description><![CDATA[Stories by David Starkey on Medium]]></description>
        <link>https://medium.com/@david.starkey?source=rss-11255d58d72b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EeLbzvEHSGzizvjg.jpg</url>
            <title>Stories by David Starkey on Medium</title>
            <link>https://medium.com/@david.starkey?source=rss-11255d58d72b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:04:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@david.starkey/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[An introduction to time series forecasting]]></title>
            <link>https://medium.com/vortechsa/an-introduction-to-time-series-forecasting-fa642420d240?source=rss-11255d58d72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa642420d240</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[oil-and-gas]]></category>
            <dc:creator><![CDATA[David Starkey]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 09:03:12 GMT</pubDate>
            <atom:updated>2019-09-27T09:03:12.046Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*nWYa6oMt4PANdUdzD9U_Zg.png" /></figure><h3>You can do a lot with a linear model</h3><p>It’s all about time series modelling and forecasting here at Vortexa! We are often faced with situations involving historic time series data on some interesting quantity in the energy market and want to forecast how that number will evolve into the future. In this post we will:</p><p><strong>1) </strong>Review the general features of a time series, and build our own toy/mock time series dataset.</p><p><strong>2)</strong> Discuss regularised and non-regularised linear models as a tool for forecasting a time series, and introduce the concept of overfitting.</p><p><strong>3)</strong> Perform a forecast, and test the robustness of each of our regularised and non-regularised models against overfitting.</p><p>If you have some introduction to statistics and Python coding, then please read on to develop a toy time series data set and build a simple linear forecasting model!</p><h3>What is a time series?</h3><p>A time series is a sample of measurements of some interesting quantity taken repeatedly over a sustained period (the <a href="https://www.statista.com/statistics/584914/monthly-rainfall-in-uk/">monthly average rainfall data</a> for London from 1998 up to the present is a time series). To forecast a time series is to predict what its value will be at some point in the future. We can code our own toy time series model to practice our modelling and forecasts.</p><pre>#numpy is great for array and mathematical operations<br>import numpy as np</pre><pre>#customize the time series features <br>#(we will discuss periodic and trend features soon)<br>N = 1000 #sample size approx 3 year daily samples<br>trend_weight = 0.5<br>period = 180<br>period_weight = 12<br>background_level = 50<br>additional_features_weights = [0.3,0.3]</pre><pre>#generate the true time series data<br>t = np.arange(N)<br>y = background_level + 0.5*t + 12.*np.sin(2*np.pi*t/180.)</pre><pre>#include the additional features <br>#(we use random variations to simulate ‘additional features’)<br>additional_features = []<br>for w in additional_features_weights:<br> af = np.random.randn(N)<br> additional_features.append(af)<br> y = y + w*af</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCge2kzMFMHfWUAJOUxfEQ.png" /><figcaption>Our toy time series data!</figcaption></figure><p>The toy time series data above illustrates a simplified form of a typical forecasting problem. It exhibits features common to many time series data sets in general.</p><p><strong>Seasonality:</strong> There is an apparent cyclic pattern to the behaviour that any model should consider. In our model, we have a 6-month cycle.</p><p><strong>Trend:</strong> The time series grows slowly over time. This is a linear trend in our model but could be more gradual or steeper growth (or decline).</p><p><strong>Additional Variability:</strong> These are the day-to-day variations on top of the seasonality that complete the model.</p><p>The additional sources of variability are often the most important and difficult to understand. They are very situation dependent. In astrophysics for example (my humble beginnings) we often find that super massive black holes at the centres of galaxies flare up in X-ray emission as they feed on passing stars. A day or so later, an optical flare will follow it. In this case, the X-ray time series is a source of additional variability that could be used as a feature to predict the optical time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95CdXIW2VsI5Ooh93_Ky_A.jpeg" /><figcaption><a href="https://wallpaperaccess.com/supermassive-black-hole">Super massive black hole</a></figcaption></figure><p>When modelling a real-world time series, we will likely have many possible features to consider (from all three categories above and more). In general, we also won’t know how strongly each of these features (if at all) affects the time series. We therefore need to build mathematical models that recover the best possible combinations and strengths of many potential candidate features in order to make a reliable forecast. To understand how to do this, let&#39;s look at the case of linear models.</p><h3>Linear Models</h3><p>Linear models can be used to encode each unknown feature we want to test as a separate time series <strong><em>X</em></strong>, sampled at time <strong><em>i</em></strong>. The linear model sees this algebraically as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*84KCJxFpCzZE9Qc9QcGa6A.png" /></figure><p>where each feature time series has a weight, <strong><em>W</em></strong>, that quantifies its contribution to the model. The job of a linear model is to recover the correct value of these weights for each of the true features, and dampen the weights of any features unrelated to the model. Features are generally coded as a 2D matrix of <strong><em>N</em></strong> samples by <strong><em>K</em></strong> features. We can encode several periodic (using sine and cosine basis functions) and trend (polynomial) features below.</p><pre>&#39;&#39;&#39;Specify trend features<br>In general trends can be modelled as polynomials that change smoothly with time. Alinear trend has order 1, <br>but we can in principle add more of these to model <br>more complex variability<br>&#39;&#39;&#39;<br>trend_features = 1<br>Ntrends = trend_features + 1</pre><pre>&#39;&#39;&#39; Specify periodic features<br>Here we specify which periods to test in our model. <br>In a real world problem we likely wont know exactly <br>which features to include and will want to test several.<br>&#39;&#39;&#39;<br>#we have a 6-month, 1-year and 30-day period here<br>periodic_features = [180,365,30]<br>Nperiodic = len(periodic_features)*2</pre><pre>&#39;&#39;&#39;make the feature matrix&#39;&#39;&#39;<br>features = np.zeros((N,Ntrends+Nperiodic))<br>#add polynomial trend freatures<br>for i in range(Ntrends):<br>    features[:,i] = np.arange(N)**i<br>#add periodic features<br>idp = 0<br>for i in range(Ntrends, Ntrends + Nperiodic,2):<br>    features[:, i] = np.sin(2*np.pi*t/periodic_features[idp])<br>    features[:, i+1] = np.cos(2*np.pi*t/periodic_features[idp])<br>    idp += 1</pre><h3>Overfitting</h3><p>A potential problem when trying to build any linear model (not only with time series data) is knowing when to stop adding features. Failure to do this results in overfitting: where the model will perfectly fit the training sample but then fail when blind tested on a new validation sample. There are many ways to mitigate this problem. One should, first and foremost, take care to do some exploratory data analysis when facing multi-dimensional data. It is a good idea only to include features that are well correlated with the forecast time series, or where there is some physical intuition that the feature should be important (i.e if we are trying to model a persons’ weight then their height is likely to be important). A few other ways to counter overfitting,</p><p><strong>Information Criteria:</strong> Uses <a href="https://medium.com/@analyttica/akaike-information-criterion-aic-7a4b58bce206">Akaike Information Criterion</a> (AIC) or <a href="https://medium.com/@analyttica/what-is-bayesian-information-criterion-bic-b3396a894be6">Bayesian Information Criterion</a> (BIC) to penalise large numbers of features.</p><p><strong>Dimensionality reduction:</strong> Using Principle Component Analysis (PCA) for example (here is a great use of PCA <a href="https://medium.com/vortechsa/turning-a-repetitive-business-task-into-a-self-improving-process-929c6b9a52dc">https://medium.com/vortechsa/turning-a-repetitive-business-task-into-a-self-improving-process-929c6b9a52dc</a> ).</p><p><strong>Piecewise component selection:</strong> Iteratively add components into the model based on which yields the most improved cross validation accuracy. Stop when the improvement plateaus.</p><p><strong>Apply </strong><a href="https://medium.com/datadriveninvestor/the-art-of-regularization-caca8de7614e"><strong>regularisation</strong></a><strong>:</strong> We will focus on this option for the remainder of our discussion.</p><p>Let&#39;s introduce a few linear models below and see how adding regularisation to a linear model can make it more robust against overfitting.</p><p><strong>1: General Linear Model</strong></p><p>All of our linear models below work by optimising the feature weights so that some linear combination of these features matches the time series with the smallest possible error. This error can be quantified into a loss function. All of our models differ only in the exact form of this loss function. In a General Linear Model (GLM), this loss function takes the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*ugPEfO0b1AHOdNbkzWOyVQ.png" /></figure><p>This is the bread and butter loss function and known as ‘ordinary least-squares’. It tries to minimise the difference between the predicted and actual time series. A custom-designed GLM is provided in the appendix for anyone who doesn’t trust sci-kit learn and is curious how to go about coding this. In general, when building custom prediction models, good coding practice is to build the library into a class with <em>.fit</em> and <em>.predict</em> functions to make it as general as possible (assuming you are coding in Python).</p><p><strong>2: Lasso Regularised Regression</strong></p><p>To reduce overfitting, and ensure that our model is a general as possible when fitting new data, we can use a technique called <a href="https://medium.com/datadriveninvestor/the-art-of-regularization-caca8de7614e">regularisation</a>. This makes a small alteration to our loss function so that it not only minimises the least-squares-sum, but also penalize extraneous features by minimising the sum of the absolute size of the weights. One common form of regularisation is known as ‘lasso’. This modifies the loss functions to the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*eMTckq3F2ANOL5ZGTfXjdQ.png" /></figure><p>The term on the left is concerned with fitting the time series well, and the right term penalises the overfitting. The relative importance of these two effects is controlled by the value of <strong><em>α</em></strong>, which is often optimised using <a href="https://medium.com/datadriveninvestor/k-fold-cross-validation-6b8518070833">cross validation</a>. The example at the end of this post optionally includes another form of regularisation called ridge (this is similar to lasso but penalises the sum-of-square weights rather than the sum-of-absolute weights). We will stick with our comparison between GLM’s and lasso for the remainder of the post but feel free to experiment with the sample appendix code to get a better intuition for how these models are coded and how they work in practice.</p><h3>Simulating overfitting: A model comparison</h3><p>We can see how regularisation aims to prevent overfitting in theory. Now let&#39;s see how this works in practice by simulating some noisy features into our feature matrix.</p><pre>#specify the number of noise features<br>number_of_noisy_features = 180</pre><pre>noisy_features = np.zeros((N,number_of_noisy_features))<br>#add noisy random features<br>for i in range(number_of_noisy_features):<br> noisy_features[:,i] = np.random.randn(N)</pre><pre>#include these into our feature matrix<br>features = np.hstack([features,noisy_features])</pre><p>The <em>features</em> matrix now contains the true features describing the time series, but also includes some fake ‘noisy features’ to confuse the model. We can continue to add noisy features to see how overfitting our GLM and lasso models affects their performance.</p><h3>Model fitting and performance testing</h3><p>We can separate the samples into a train and test set to validate the performances and quantify these using the root mean square error (RMSE). This measures the average offset between the blind forecast and the true time series,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*NM0PsyfyPFow_x1eTmK9BA.png" /></figure><p>The snippet below shows how to do a naive splitting into a train and test sample and fit our GLM (we can replace with Lasso by un-commenting where indicated)</p><pre># we use the sklearn model here but this in practice works for anything. <br># See the appendix for a custom-built linear mdoel using ridge regularisation.<br>Ntrain = 150<br>import sklearn.linear_model as LM<br>model = LM.LinearRegression()<br>#to test the lasso model, use<br>#model = LM.Lasso()<br>model.fit(features[:Ntrain,:],y[:Ntrain])<br>ypred = model.predict(features[Ntrain:,:])<br>rmse = np.sqrt(np.sum((ypred — y[Ntrain:])**2)/len(ypred))</pre><p>Let’s now test our linear models on two cases.</p><p><strong>Case 1: Few nuisance features</strong></p><p>Here we feed all the descriptive features into our model along with only a few nuisance features (i.e we have a good understanding of the underlying variables in the system). We also have many more samples than features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eh1QLWHXuqrbtuX9wf-Crw.png" /><figcaption>Forecast with only a few noisy features</figcaption></figure><p>The RMSE for this forecast is practically zero. Overfitting is not a problem here.</p><p><strong>Case 2: Many nuisance features approaching the sample size</strong></p><p>In Case 2 we have included many noisy features in our model. We stress again the need for exploratory data analysis to screen out such poorly-correlated features from a real world forecasting situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVWZg8p7vYM8SW3sw0vxGQ.png" /><figcaption>forecast models polluted with noisy features</figcaption></figure><p>We see now a stark difference between the GLM and Lasso models. Let&#39;s compare the RMSE in both of these cases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*B_iGcblRlUT_hCfGE8RIxg.png" /></figure><p>In both the GLM and regularised lasso models, the errors are greater than in Case 1. The good news is that the lasso model does a much better job of suppressing the weights of the same nuisance features that plague the standard GLM with larger errors.</p><h3>Take home message</h3><p>That&#39;s it folks. This quick tour reviews the features of a typical time series and how to use linear models to go about fitting one. We also touched on the problem of over fitting when adding too many features into our model, and suggested a few techniques to mitigate this problem with an emphasis on regularisation.</p><p>In general, we see that in cases where we have few features relative to our sample size, and have confidence that the features do indeed accurately describe the process involved, regularisation can be unnecessary and a standard GLM will do. If we are more uncertain about whether our features have any predictive power, or have few samples in our data, some level of regularisation may be required. One big caveat here is that we have assumed that features used to forecast our time series are known arbitrarily far into the future. This is only generally true for the periodic and trend features in our time series model and we often need to include more model-specific features to forecast the more detailed day-to-day variations. The feature-fitting stage is also often only the first step in building more powerful time series forecasting models.</p><p>A few closing thoughts. The first stage in any model-fitting (time series or otherwise) should always be a careful exploratory data analysis of the features involved. This can weed many nuisance features out of our model right away. Nonetheless, a good regularised linear model is a powerful tool for many time series forecasting problems and is something to try out early in the model fitting process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa642420d240" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/an-introduction-to-time-series-forecasting-fa642420d240">An introduction to time series forecasting</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>