<?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 Yashveer Singh Sohi on Medium]]></title>
        <description><![CDATA[Stories by Yashveer Singh Sohi on Medium]]></description>
        <link>https://medium.com/@yashveersinghsohi?source=rss-2361823749f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e3RLlXICEcg0Ym7goFUr-A.jpeg</url>
            <title>Stories by Yashveer Singh Sohi on Medium</title>
            <link>https://medium.com/@yashveersinghsohi?source=rss-2361823749f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:32:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashveersinghsohi/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[Statistical Forecasting for Time Series Data Part 6: Forecasting Non-Stationary Time Series using…]]></title>
            <link>https://pub.towardsai.net/statistical-forecasting-for-time-series-data-part-6-forecasting-non-stationary-time-series-using-9acc28c39db9?source=rss-2361823749f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9acc28c39db9</guid>
            <category><![CDATA[statistical-modeling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[arima]]></category>
            <dc:creator><![CDATA[Yashveer Singh Sohi]]></dc:creator>
            <pubDate>Fri, 25 Dec 2020 13:02:41 GMT</pubDate>
            <atom:updated>2020-12-25T13:02:41.094Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-visualization">Data Visualization</a></h4><h3>Statistical Forecasting for Time Series Data Part 6: Forecasting Non-Stationary Time Series using ARIMA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L_hsV4S74YvoqIZ6" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this series of articles, the S&amp;P 500 Market Index is analyzed using popular Statistical Model: <strong>SARIMA </strong>(Seasonal Autoregressive Integrated Moving Average), and <strong>GARCH </strong>(Generalized AutoRegressive Conditional Heteroskedasticity).</p><p>In the first part, the series was scrapped from the yfinance API in python. It was cleaned and used to derive the <strong>S&amp;P 500 Returns</strong> (percent change in successive prices) and <strong>Volatility</strong> (magnitude of returns). In the second part, a number of time series exploration techniques were used to derive insights from the data about characteristics like trend, seasonality, stationarity, etc. With these insights, in the 3rd and 4th part the SARIMA and GARCH class of models were introduced. In the 5th part, the 2 models (SARIMA and GARCH) were combined to generate meaningful forecasts and derive accurate insights on future data. Links to all these parts are at the end of this article.</p><p>In this last part, the technique used to model Non-Stationary data using the SARIMA class of models are covered. The code used in this article is from <strong>Prices Models/ARMA Model for SPX Prices.ipynb</strong> notebook in this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a></p><h3>Table of Contents</h3><ol><li>Importing Data</li><li>Train-Test Split</li><li>Stationarity of S&amp;P 500 Prices</li><li>Converting S&amp;P 500 Prices to a Stationary Series</li><li>Modeling the Transformed Series</li><li>Predicting S&amp;P 500 Prices using ARMA Model</li><li>Evaluating the Predictions</li><li>Conclusions</li><li>Links to other parts of this series</li><li>References</li></ol><h3>Importing Data</h3><p>Here we import the dataset that was scrapped and preprocessed in part 1 of this series. Refer part 1 to get the data ready, or download the <strong>data.csv</strong> file from this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href">https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Hs8ScyWxMhgqIkXjJIyQFQ.png" /><figcaption>Output for the previous code cell showing the first 5 rows of the dataset</figcaption></figure><p>Since this is same code used in the previous parts of this series, the individual lines are not explained in detail here for brevity.</p><h3>Train-Test Split</h3><p>Like before, we now split the data into train test sets. Here all the observations on and from 2019–01–01 form the test set, and all the observations before that is the train set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href">https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*3tDWhR-cwVwh5dheM28IEg.png" /><figcaption>Output of previous code cell showing the shape of training and testing sets</figcaption></figure><h3>Stationarity of S&amp;P 500 Prices</h3><p>Before fitting any of the models from the ARIMA family, the stationarity of the input series should be checked. This is because in a stationary series the underlying process creating the data (the one ARIMA tries to model) will not change in the future. Hence the model will have a reasonable chance of success with stationary data.</p><p>To check whether a series is stationary or not, the following 3 ways are used:</p><ul><li>Check whether the data has no apparent trend (summary statistics do not change with time) using a line plot.</li><li>Check the correlation of the plot with lagged versions of itself using the ACF and PACF plot.</li><li>Check the results of the ADF (Augmented Dickey Fuller) Test. The Null Hypothesis states that the series is Non-Stationary. If the p-value returned is greater than all the critical levels, then the Null Hypothesis can not be rejected, and the series is not stationary. (A more in-depth description was provided in part2 of this series.)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/209c1fa9995edd97518612ceba518701/href">https://medium.com/media/209c1fa9995edd97518612ceba518701/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*Vb7Ckg5BXiLIt_AlvHBCMQ.png" /><figcaption>Correlation plots, Line Plot and ADF Test results for S&amp;P 500 Prices</figcaption></figure><p>The correlation plots, and the line plots indicate a clear trend in the series. Additionally, the p-value of the ADF test is greater than all the critical levels, and hence the series is non-stationary.</p><h3>Converting S&amp;P 500 Prices to a Stationary Series</h3><p>There are many techniques used to convert a non-stationary series to a stationary one. The following 2 are probably the most common ones:</p><ul><li><strong>Differencing:</strong> Here the series is differenced with a lagged version of itself. The trend component of the series is usually removed in this transformation.</li><li><strong>Log Transform:</strong> Here the log of the series is calculated. The series is reduced in scale and the variations are damped in this transformation.</li></ul><p>In this case, another common approach is used, which is to combine the above 2 approaches: <strong>Log-Differenced Transform</strong>. In this, first, the log of the series is calculated, and then the series is differenced with a lagged version of itself (here, lag is of 1 time period).</p><p>The mathematical formulation of this approach is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*mG4uMN7vd08YGLefpYNspw.png" /><figcaption>Mathematical Formulation of the transformation described above</figcaption></figure><p>The code to do this is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/065e393306ed02641b171763882702a3/href">https://medium.com/media/065e393306ed02641b171763882702a3/href</a></iframe><p>The stationarity of this new series can be checked in the same way as it was done for the original series. The train_df[“spx”] series is to be replaced by the train_df[“spx_log_diff”] series. The rest of the code can be the same as the one in the <strong>Stationarity of S&amp;P 500 Prices</strong> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*rcQrB854FQD6A8gEOw2w3w.png" /><figcaption>Correlation plots, Line Plot and ADF Test results for Transformed S&amp;P 500 Prices</figcaption></figure><p>The correlation plots and the line plot indicate that the series is stationary (devoid of any obvious trend). The p-value of the ADF test gives further proof that the series is stationary.</p><h3>Modeling The Transformed Series</h3><p>Since the series is stationary, we can use the non-integrated variants of ARIMA models: AR, MA or ARMA. In this case, ARMA is chosen. The parameters of ARMA are denoted by <strong>ARMA(p, q)</strong>:</p><ul><li><strong>p:</strong> Controls the effect of past lags (estimated by counting the significant lags in <strong>PACF</strong> plot)</li><li><strong>q:</strong> Controls the effect of past residuals (estimated by counting the significant lags in <strong>ACF</strong> plot)</li></ul><p>Looking at the ACF and PACF plots from the previous section, the initial estimates for these parameters can be: p=1 or p=2, and, q=1 or q=2 . Let’s consider the simplest of models: <strong>ARMA(1, 1)</strong>.</p><p>The following code cell is used to build a ARMA(1, 1) model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b447378bba5828f46f3714fbe0281ae/href">https://medium.com/media/3b447378bba5828f46f3714fbe0281ae/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*S9r1FlN0dVpC8do8BUoWlQ.png" /><figcaption>Summary Table for the ARMA(1, 1) model trained above.</figcaption></figure><p>The SARIMAX() function is used to define the ARMA(1, 1) model by passing the transformed S&amp;P 500 Prices series and the appropriate order as the arguments. The model is trained using the fit() method on the model definition. The summary table is displayed by using the summary() method on the fitted model.</p><p>The <strong>P&lt;|Z| </strong>column of the summary table shows that all the coefficients of this model are significant. Next, this model is used to generate predictions for the transformed series, and then for the original prices series.</p><h3>Predicting S&amp;P 500 Prices using ARMA Model</h3><p>For predicting the S&amp;P 500 Prices, the ARMA(1, 1) model build previously will be used to forecast the values for the Transformed (Log-Differenced) S&amp;P 500 Prices. Then the forecasted values (and confidence intervals) are reverse transformed to obtain the required values for the S&amp;P 500 Prices.</p><p>Referring the transformation equation mentioned above, we can derive the reverse transformation using the following mathematical equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*IiSGV9qagWAmD6JIGee_bg.png" /><figcaption>Inverse Transformation for the Log-Differencing transformation done on S&amp;P 500 Prices</figcaption></figure><p>The code to derive the predictions for S&amp;P 500 Prices is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0853e56b14028e19362b28bb0fed74d/href">https://medium.com/media/b0853e56b14028e19362b28bb0fed74d/href</a></iframe><ul><li>Firstly, a dataframe ( pred_df ) is defined that stores all the important series needed to derive the predictions for S&amp;P 500 Prices.</li><li>Next, the spx series and a lagged version of this series is stored in the dataframe. The lag is of 1 time period. These 2 series represent the y(t) and y(t-1) series in the formula shown above.</li><li>Now, the model predictions are generated using the predict() method with the start and end dates specified on the fitted model. Also, the confidence intervals for these predictions are generated using the conf_int() method on the output of the get_forecast() function. These series represent the y_new(t) series and the confidence intervals for this series in the formula above.</li><li>The exponent function is used on these predictions and their confidence intervals so as to generate the exp(y_new(t)) series from the formula above.</li><li>Finally the lagged spx values ( y(t-1) ) and exp(y_new(t)) series generated previously are multiplied to get the desired predictions: y(t) .</li></ul><h3>Evaluating the Predictions</h3><p>There are 2 ways in which the predictions generated previously are evaluated:</p><ul><li>Line plots of predictions along with the actual values</li><li>Calculating the Root Mean Squared Error (RMSE) Metric</li></ul><p>Code to generate the line plots and the RMSE metric is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9baf6a8fb0f854744f4cd12ebcf71ec9/href">https://medium.com/media/9baf6a8fb0f854744f4cd12ebcf71ec9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*vaETHaFCHFpH3l5R5w47rQ.png" /><figcaption>Plot of S&amp;P 500 Predictions vs Actuals generated by ARMA(1, 1) Model</figcaption></figure><p>First the RMSE metric is calculated using the mean_squared_error() function from sklearn.metrics . Then the Predictions (In Blue) are plotted against the Actual S&amp;P 500 Prices (In Red), along with the Confidence Intervals (In Green).</p><h3>Conclusion</h3><p>In this series of articles, the S&amp;P 500 Market Index was analysed and modeled using Statistical Time Series Forecasting Models like SARIMA and GARCH. This series first covered ways to obtain such data, and, explore it for better understanding. Next, a couple of statistical models are introduced and applied on this data. Using these models we were able to predict future values and the margin of error associated with these predictions.</p><h3>Links to other parts of this series</h3><ul><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-1-data-preparation-and-preprocessing-b52f26f6213c">Statistical Modeling of Time Series Data Part 1: Preprocessing</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-2-exploratory-data-analysis-5c3aaedc04b7">Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-3-forecasting-stationary-time-series-using-sarima-f0ff1284bebb">Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-of-time-series-data-part-4-forecasting-volatility-using-garch-1e9ff832f7e5">Statistical Modeling of Time Series Data Part 4: Forecasting Volatility using GARCH</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-5-arma-garch-model-for-time-series-forecasting-98beeedcfba8">Statistical Modeling of Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting.</a></li><li>Statistical Modeling of Time Series Data Part 6: Forecasting Non — Stationary Time Series using ARMA</li></ul><h3>References</h3><p>[1] <a href="https://365datascience.com/courses/time-series-analysis-in-python/">365DataScience</a> Course on Time Series Analysis</p><p>[2] <a href="https://machinelearningmastery.com/time-series-forecasting/">machinelearningmastery</a> blogs on Time Series Analysis</p><p>[3] <a href="https://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity">Wikipedia</a> article on GARCH</p><p>[4] <a href="https://www.youtube.com/channel/UCUcpVoi5KkJmnE3bvEhHR0Q">ritvikmath</a> YouTube videos on the GARCH Model.</p><p>[5] <a href="https://www.youtube.com/watch?v=JntA9XaTebs">Tamara Louie: Applying Statistical Modeling &amp; Machine Learning to Perform Time-Series Forecasting</a></p><p>[6] <a href="https://otexts.com/fpp2/">Forecasting: Principles and Practice</a> by Rob J Hyndman and George Athanasopoulos</p><p>[7] <a href="https://www.analyticsvidhya.com/blog/2018/09/non-stationary-time-series-python/">A Gentle Introduction to Handling a Non-Stationary Time Series in Python</a> from Analytics Vidhya</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9acc28c39db9" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/statistical-forecasting-for-time-series-data-part-6-forecasting-non-stationary-time-series-using-9acc28c39db9">Statistical Forecasting for Time Series Data Part 6: Forecasting Non-Stationary Time Series using…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Forecasting for Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting]]></title>
            <link>https://pub.towardsai.net/statistical-forecasting-for-time-series-data-part-5-arma-garch-model-for-time-series-forecasting-98beeedcfba8?source=rss-2361823749f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/98beeedcfba8</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[garch]]></category>
            <category><![CDATA[arima]]></category>
            <dc:creator><![CDATA[Yashveer Singh Sohi]]></dc:creator>
            <pubDate>Thu, 24 Dec 2020 13:02:36 GMT</pubDate>
            <atom:updated>2020-12-24T13:02:36.296Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-visualization">Data Visualization</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y6j2EdSa6TLHu_bW" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In these series of articles, the S&amp;P 500 Market Index is analyzed using popular Statistical Model: <strong>SARIMA </strong>(Seasonal Autoregressive Integrated Moving Average), and <strong>GARCH </strong>(Generalized AutoRegressive Conditional Heteroskedasticity).</p><p>In the first part, the series was scrapped from the yfinance API in python. It was cleaned and used to derive the <strong>S&amp;P 500 Returns</strong> (percent change in successive prices) and <strong>Volatility</strong> (magnitude of returns). In the second part, a number of time series exploration techniques were used to derive insights from the data about characteristics like trend, seasonality, stationarity, etc. With these insights, in the 3rd and 4th part the SARIMA and GARCH class of models were explored. The Links to all these parts are at the bottom of this article.</p><p>In this part, the 2 models introduced previously (SARIMA and GARCH) are combined to build predictions and effective confidence intervals for S&amp;P 500 Returns. The code used in this article is from <strong>Returns Models/ARMA-GARCH for SPX Returns.ipynb</strong> notebook in this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a></p><h3>Table of Contents</h3><ol><li>Importing Data</li><li>Train-Test Split</li><li>Parameter Estimation for ARMA</li><li>Fitting ARMA Model on Returns</li><li>ARMA Model Residuals</li><li>GARCH Parameter Estimation</li><li>GARCH Model on ARMA Residuals</li><li>Predictions of ARMA + GARCH model</li><li>Conclusions</li><li>Links to other parts of this series</li><li>References</li></ol><h3>Importing Data</h3><p>Here we import the dataset that was scrapped and preprocessed in part 1 of this series. Refer part 1 to get the data ready (linked at the end), or download the <strong>data.csv</strong> file from this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href">https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Hs8ScyWxMhgqIkXjJIyQFQ.png" /><figcaption>Output for the previous code cell showing the first 5 rows of the dataset</figcaption></figure><p>Since this is same code used in the previous parts of this series, the individual lines are not explained in detail here for brevity.</p><h3>Train-Test Split</h3><p>We now split the data into train and test sets. Here all the observations on and from 2019–01–01 form the test set, and all the observations before that is the train set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href">https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*3tDWhR-cwVwh5dheM28IEg.png" /><figcaption>The output of previous code cell showing the shape of training and testing sets</figcaption></figure><h3>Parameter Estimation for ARMA Model</h3><p>ARMA model is a subset of the ARIMA model, discussed previously in this series. It has 2 parameters represented as: ARMA(p, q). Like ARIMA,</p><ul><li>The number of significant lags in <strong>PACF</strong> plot indicates the order of <strong>p </strong>(which controls the effect of past values on present value).</li><li>The number of significant lags in the <strong>ACF</strong> plot indicates the order of <strong>q </strong>(<strong> </strong>which controls the effect of past residuals on the current value).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64cf54fc493921f8c15c11372bfbaed0/href">https://medium.com/media/64cf54fc493921f8c15c11372bfbaed0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*y9I3w9dh84R5rCvu7eYMcA.png" /><figcaption>ACF and PACF plots for S&amp;P 500 Returns</figcaption></figure><p>The plot_acf() and plot_pacf() functions from the statsmodels.graphics.tsaplots library are used to plot the ACF and PACF plots for S&amp;P 500 Returns. On examining the plots, it is clear that the first 2 lags are significant in both the plots. After these, the significance level shuts off abruptly and then spikes up again. Thus, to keep the model simple, it is reasonable to set the initial parameters as:</p><ul><li>p = 1, or p = 2</li><li>q = 1, or q = 2</li></ul><h3>Fitting ARMA Model on Returns</h3><p>Let’s build the ARMA(1, 1) model on S&amp;P 500 Returns.</p><p><strong>Note:</strong> Before Fitting a model from the SARIMA class of models, one needs to check whether the input series used to fit the model is stationary. For a stationary time series the summary statistics do not change significantly over time. This means that the underlying process creating the data is the same as time passes on. It is intuitive to expect that one can only model a series if the underlying process generating the series remain the same in the future. The stationarity of this series spx_ret is tested in previous parts (part2 and part3) of this series using the adfuller() test from statsmodels.tsa.stattools .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cbc28b734d5f58ca4ae6f3d97171ae4/href">https://medium.com/media/8cbc28b734d5f58ca4ae6f3d97171ae4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*7EWn1HlYE4TW1w-wp-fd4Q.png" /><figcaption>Output of the previous code cell showing the summary table for ARMA(1, 1) on S&amp;P 500 Returns</figcaption></figure><p>The SARIMAX() function in the statsmodels.tsa.statespace.sarimax library is used to fit any subset of the SARIMAX family of models. The series, spx_ret , and the order, order = (1, 0, 1) , are passed in the function to get the ARMA(1, 1) model definition. The fit() method on the model is used to train the model definition. The summary() method on the fitted model results prints the summary table of the model as shown the image.</p><p>The summary table shows that all the coefficients of the model are significant.</p><h3>ARMA Model Predictions and Confidence Intervals</h3><p>In this section we use the ARMA(1, 1) model to forecast the Returns for the Test set. Furthermore, the same model is used to generate the confidence intervals.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/272e1cb4c6c961eba5e7fb1f3915a5d5/href">https://medium.com/media/272e1cb4c6c961eba5e7fb1f3915a5d5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*kMUnxhx5z2cD7XWTaTH2QA.png" /><figcaption>ARMA(1, 1) model Predictions(In red) and Confidence Intervals(In green) plotted against Actual Returns(In blue)</figcaption></figure><p>The get_forecast() method is used to build a forecasts object that can later be used to derive the confidence intervals using the conf_int() function. The predict() function is used to get the predictions for the test set. The <strong>RMSE</strong> (Root Mean Squared Error) metric is used to calculate the accuracy of the predictions with respect to the actual returns in the test set. The predictions and the confidence intervals are then plotted against the actual returns from the test set to visually confirm the accuracy of the model.</p><p>On inspecting the plot (shown in the image), the predictions are in some cases spot on, and in some cases they are wrong by huge margins. The confidence intervals do nothing to indicate how the predictions will perform in different time periods of the test set. In some cases the confidence intervals seem too conservative, and the returns overshoot the boundaries. In other cases, the confidence intervals are not nearly conservative enough.</p><p>To address this issue, in the next section we will analyse the residuals of the model and try to predict when the ARMA predictions will be off by a small margin and when will they be off by a large margin.</p><h3>ARMA Model Residuals</h3><p>In this section we plot the residuals of the model and explore some of its properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a09e04798b97469ffd195473f14d71b/href">https://medium.com/media/7a09e04798b97469ffd195473f14d71b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*8y0gepsmki9ce6TF01VmEw.png" /><figcaption>Plot of the Residuals of ARMA(1, 1) on S&amp;P 500 Returns</figcaption></figure><p>The residuals generated by the ARMA(1, 1) model can be accessed by using the resid attribute of the fitted model. On examining the plot, it is clear that the residuals show the phenomenon of volatility clustering. This means that if the series shows high volatility (high variance) at a particular time step, then it will show high volatility in nearby time steps as well, and vice versa. In periods around 2004, 2008 (periods of high volatility), and the periods in between(periods of low volatility), this phenomenon is clearly observed.</p><p>Series that show such volatility clustering can be successfully modeled using the GARCH model(as seen in part 4 linked at the end). In the next section we start estimating the parameters needed to fit the GARCH model on the residuals of ARMA(1, 1) model.</p><h3>GARCH Parameter Estimation</h3><p>The GARCH model, has 2 parameters represented as: GARCH(p, q). These parameters are estimated by counting the number of significant lags in the PACF plot. The code to generate such a plot is not shown as it is very similar to the PACF plot code above. Only tweaks needed are in the data passed. In this case the series passed will be model_results.resid .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*aDXBc96Y9PFEYi5ibQ2F1w.png" /><figcaption>PACF for ARMA(1, 1) Residuals</figcaption></figure><p>The plot shows that there are no significant lags in the residuals. Thus we will fit various GARCH models: GARCH(1, 1), GARCH(1, 2), GARCH(2, 1), GARCH(2, 2), etc. till we get a model with significant coefficients and best accuracy.</p><h3>GARCH Model on ARMA Residuals</h3><p>As mentioned in the previous section, the PACF plot did not offer any insight for starting parameters. In such case, various models should be fit in order to find one that has significant coefficients and best accuracy. This ensures that we have the simplest possible model with the best possible accuracy.</p><p>After fitting a few such model, the GARCH(2, 2) satisfied this criteria in my case. Feel free to try out various models locally and choose your preferred model. Let us see the code to fit the GARCH(2, 2) model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/339fcfdad62e57f56581cca9e5c990dd/href">https://medium.com/media/339fcfdad62e57f56581cca9e5c990dd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*Faj_hRetyxGDhM5-pAEqFQ.png" /><figcaption>Summary Table for the GARCH(2, 2) Model</figcaption></figure><p>Before fitting the model, a new dataframe is prepared. This dataframe consists of all the time steps in the original dataset (before train-test split). The training time steps are occupied by the Residuals from the ARMA(1, 1) model. These are actually used for training the GARCH model. The testing periods are occupied by the actual returns observed one time step previously. This is tantamount to saying that the model will forecast tomorrow’s volatility in returns using the returns observed today.</p><p>The arch_model() function in arch library is used to define a GARCH model. The fit() function is used to train the model defined. The last_obs argument is used to identify from what time step should the model start predicting. The summary() function prints out the summary table as shown in the image. The summary table shows all coefficients of the model are significant.</p><h3>Predictions of ARMA+GARCH model</h3><p>In this section we use the GARCH(2, 2) model fitted on residuals of ARMA(1, 1) to predict the volatility of the residuals in the test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daab7d23988aca6f4856bad6b54cec5e/href">https://medium.com/media/daab7d23988aca6f4856bad6b54cec5e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*3gJi98lVJaq8dT3XHDk2gw.png" /><figcaption>Predictions(In Red) + Confidence Intervals(In Green) for the S&amp;P 500 returns(In Blue) using ARMA+GARCH model</figcaption></figure><p>The forecast() method is used on the fitted model: resid_model_results . This outputs an ARCHModelForecast object that contains the predictions for the mean model, and the volatility model. Next, the residual_variance attribute is called to get the predictions for volatility. The predictions from the volatility model are subtracted (and added) to the predictions from the ARMA model stored in the arma_predictions_df to get the lower (and upper) confidence interval(s) of the model.</p><p>Next, the predictions (from ARMA(1, 1)) and the confidence intervals (from GARCH(2, 2)) are plotted against the actual S&amp;P 500 Returns. On examining the plot, it is clear that when the returns are stable, and when the predictions are close to actual returns, the confidence intervals reflect this by being close. Same is true for when the Returns are unstable and the predictions are far from the Returns. In this case too the confidence intervals adjust and become far apart.</p><h3>Conclusions</h3><p>Thus, using the combination of ARMA and GARCH models we are able to build much more meaningful forecasts. Looking at the forecasts and confidence intervals we can understand the ballpark figure for future returns and also the stability in the market. In the next and final article in this series, we will look at how to use the SARIMA family of model for Non-Stationary data: S&amp;P 500 Prices.</p><h3>Links to other parts of this series</h3><ul><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-1-data-preparation-and-preprocessing-b52f26f6213c">Statistical Modeling of Time Series Data Part 1: Preprocessing</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-2-exploratory-data-analysis-5c3aaedc04b7">Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-3-forecasting-stationary-time-series-using-sarima-f0ff1284bebb">Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-of-time-series-data-part-4-forecasting-volatility-using-garch-1e9ff832f7e5">Statistical Modeling of Time Series Data Part 4: Forecasting Volatility using GARCH</a></li><li>Statistical Modeling of Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting.</li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-6-forecasting-non-stationary-time-series-using-9acc28c39db9">Statistical Modeling of Time Series Data Part 6: Forecasting Non — Stationary Time Series using ARMA</a></li></ul><h3>References</h3><p>[1] <a href="https://365datascience.com/courses/time-series-analysis-in-python/">365DataScience</a> Course on Time Series Analysis</p><p>[2] <a href="https://machinelearningmastery.com/time-series-forecasting/">machinelearningmastery</a> blogs on Time Series Analysis</p><p>[3] <a href="https://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity">Wikipedia</a> article on GARCH</p><p>[4] <a href="https://www.youtube.com/channel/UCUcpVoi5KkJmnE3bvEhHR0Q">ritvikmath</a> YouTube videos on the GARCH Model.</p><p>[5] <a href="https://www.youtube.com/watch?v=JntA9XaTebs">Tamara Louie: Applying Statistical Modeling &amp; Machine Learning to Perform Time-Series Forecasting</a></p><p>[6] <a href="https://otexts.com/fpp2/">Forecasting: Principles and Practice</a> by Rob J Hyndman and George Athanasopoulos</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98beeedcfba8" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/statistical-forecasting-for-time-series-data-part-5-arma-garch-model-for-time-series-forecasting-98beeedcfba8">Statistical Forecasting for Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Forecasting of Time Series Data Part 4: Forecasting Volatility using GARCH]]></title>
            <link>https://pub.towardsai.net/statistical-forecasting-of-time-series-data-part-4-forecasting-volatility-using-garch-1e9ff832f7e5?source=rss-2361823749f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e9ff832f7e5</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[garch]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yashveer Singh Sohi]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 13:02:22 GMT</pubDate>
            <atom:updated>2020-12-23T13:02:22.151Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-visualization">Data Visualization</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uTVb536sFhivyGGV" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this series of articles, the S&amp;P 500 Market Index is analyzed using popular Statistical Model: <strong>SARIMA </strong>(Seasonal Autoregressive Integrated Moving Average), and <strong>GARCH </strong>(Generalized AutoRegressive Conditional Heteroskedasticity).</p><p>In the first part, the series was scrapped from the yfinance API in python. It was cleaned and used to derive the S&amp;P 500 Returns (percent change in successive prices) and Volatility (magnitude of returns). In the second part, a number of time series exploration techniques were used to derive insights from the data about characteristics like trend, seasonality, stationarity, etc. With these insights, in the 3rd part, the SARIMA class of models was explored.</p><p>In this article, the GARCH model is built to model the volatility in S&amp;P 500 Returns. The code used in this article is from <strong>Volatility Models/GARCH for SPX Volatility.ipynb</strong> notebook in this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a></p><h3>Table of Contents</h3><ol><li>Importing Data</li><li>Train-Test Split</li><li>GARCH Model</li><li>Volatility of S&amp;P 500 Returns</li><li>Parameter Estimation for GARCH</li><li>Fitting GARCH on S&amp;P 500 Returns</li><li>Predicting Volatility</li><li>Evaluating the Performance</li><li>Conclusion</li><li>Links to other parts of this series</li><li>References</li></ol><h3>Importing Data</h3><p>Here we import the dataset that was scrapped and preprocessed in part 1 of this series. Refer part 1 to get the data ready, or download the <strong>data.csv</strong> file from this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href">https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Hs8ScyWxMhgqIkXjJIyQFQ.png" /><figcaption>Output for the previous code cell showing the first 5 rows of the dataset</figcaption></figure><p>Since this is same code used in the previous parts of this series, the individual lines are not explained in detail here for brevity.</p><h3>Train-Test Split</h3><p>We now split the data into train and test sets. Here all the observations on and from 2019–01–01 form the test set, and all the observations before that is the train set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href">https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*3tDWhR-cwVwh5dheM28IEg.png" /><figcaption>Output of previous code cell showing the shape of training and testing sets</figcaption></figure><h3>GARCH Model</h3><p>GARCH stands for <strong>Generalized Auto-Regressive Conditional Heteroskedasticity. </strong>Conditional Heteroskedasticity is tantamount to conditional variance (or conditional volatility) in the time series. GARCH model uses the concept of volatility clustering to model the volatility of a series. <strong>Volatility Clustering</strong> essentially means that the volatility today, depends on the volatility at recent time steps. A GARCH model is specified using 2 parameters: <strong>GARCH(p, q)</strong>. The GARCH model is formulated as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*D32PMJthugZGO4frX2HlFw.png" /><figcaption>Mathematical formulation of how GARCH models Volatility</figcaption></figure><p>The above equation shows how GARCH models Volatility. The squared volatility at some time step is represented as the linear combination of some constant, a group of past residual terms, and a group of past volatility terms. The parameters <strong>p, and q </strong>are used to control the number of these lagged residual, and volatility terms in the above equation respectively.</p><h3>Volatility of S&amp;P 500 Returns</h3><p>In this article, the Volatility of S&amp;P 500 Returns is modeled using GARCH. In order to test whether the volatility predicted matches the volatility of returns in future, we calculate the magnitude of S&amp;P 500 Returns and have stored it in the series spx_vol .</p><p>Thus, the model is fit on spx_ret series, and the predicted volatility is compared with spx_vol .</p><h3>Parameter Estimation for GARCH</h3><p>The PACF (Partial Auto-Correlation Function) plot is used to get an initial estimate of the parameters: p and q of the GARCH model. The number of significant lags in this plot is used as the initial parameters. Then the model summary table (displayed after fitting the model) is used to understand which coefficients in the model are significant. Based on this, the model is fine tuned.</p><p>Now, the PACF plot for S&amp;P 500 Returns is generated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f070b148f3ea135592f654a138e55117/href">https://medium.com/media/f070b148f3ea135592f654a138e55117/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*7fYPWSvAhAVyb5hfvespig.png" /><figcaption>PACF plot of S&amp;P 500 Returns</figcaption></figure><p>Using the plot_pacf() function in statsmodels.graphics.tsaplots package, the PACF plot is generated for the spx_ret series. On examining the plot, the first 2 lags are significant. Therefore, the GARCH(2, 2) model is suitable for an initial starting point.</p><h3>Fitting GARCH on S&amp;P 500 Returns</h3><p>Now, a GARCH(2, 2) model is fit on the S&amp;P 500 Returns series.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e34611368e829645db92e492931d6d9b/href">https://medium.com/media/e34611368e829645db92e492931d6d9b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*HqQmOwVETvKnMbakg64ICw.png" /><figcaption>Summary Table of the GARCH(2, 2) Model fitted on S&amp;P 500 Returns</figcaption></figure><p>The arch_model() function in the arch package is used to implement the GARCH model. The Implementation mentioned here is inspired from the one mentioned in the official documentation <a href="https://arch.readthedocs.io/en/latest/univariate/univariate_volatility_forecasting.html#Fixed-Window-Forecasting">here</a>. Before fitting the model, a new dataframe is prepared. This dataframe consists of all the time steps in the original dataset (before train-test split). The training time steps are occupied by the Returns of S&amp;P 500. These are actually used for training the GARCH model. The testing periods are occupied by the Returns observed one time step previously. This is tantamount to saying that the model will forecast tomorrow’s volatility in returns using the returns observed today.</p><p>Using the arch_model() method, the model is defined. The function takes in the dataset mentioned above as input, and the parameters: p=2, and q=2 . The vol= “GARCH” argument specifies that the model to be used is GARCH. The model definition is stored in the variable model and the fit() method is called on it to train the model. The last_obs argument is used to ensure that the model is trained on train data only. The fitted model is stored in model_results variable, and the summary of this is displayed by calling the summary() on the fitted model.</p><p>The first few lines before the summary table in the output image shows the fitting information as displayed after each iteration by the fit() function. The update_freq=5 argument in the fit() function limits this information to be displayed after every 5 iterations. Next, in the summary table there are 3 sections: <strong>Constant Mean — GARCH Model Results, Mean Model, </strong>and<strong> Volatility Model. </strong>In the section for Volatility Model, the <strong>P&lt;|Z| </strong>column clearly indicates that all the coefficients are significant at the 5% confidence level.</p><h3>Predicting Volatility</h3><p>Here the fitted model is used to forecast the volatility of S&amp;P 500 Returns in the test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08920620cac66dd9081a01ad7178151e/href">https://medium.com/media/08920620cac66dd9081a01ad7178151e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*ML-fUrCmIi2fXZeNUUayOA.png" /><figcaption>Plot showing the Volatility predicted by the model against the assumed volatility (magnitude of the returns) of the S&amp;P 500 Returns time series.</figcaption></figure><p>The forecast() method is used on the fitted model: model_results . This outputs an ARCHModelForecast object that contains the predictions for the mean model, and the volatility model. Next, the residual_variance attribute is called to get the predictions for volatility. The predictions are stored in a dataframe with the same number of periods as in data . All the periods on which the model is trained has NaN values in them, and only the periods for which the model should generate forecasts are actually populated. In this case, all the periods of the test set has real valued numbers, and the ones of the train set has NaN’s. The predictions are then plotted against the volatility (magnitude of returns) calculated heuristically.</p><h3>Evaluating the Performance</h3><p>The image above shows that whenever the predicted volatility of the model spikes violently, the magnitude of returns (heuristically calculated volatility) also fluctuates greatly. On the other hand, when the predicted volatility is stable, then the magnitude of returns are also relatively stable. Thus our model is clearly able to identify periods of high and low volatility in S&amp;P 500 Returns.</p><p>The primary purpose of this model is to identify periods where the market is stable and periods where the market is volatile, and the model is successful in capturing this information. Thus, there is no reason to evaluate the model on error metrics like <strong>RMSE</strong> (Root Mean Squared Error)</p><h3>Conclusion</h3><p>In this article, the volatility in S&amp;P 500 Returns was analysed and predicted using the GARCH model. In the next article, first, an ARIMA model will be used to fit the S&amp;P 500 Returns. Then, a GARCH model will be used to model the residuals of ARIMA. This will allow us to generate much more reliable confidence intervals than the ones generated by the ARIMA model alone.</p><h3>Links to other parts of this series</h3><ul><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-1-data-preparation-and-preprocessing-b52f26f6213c">Statistical Modeling of Time Series Data Part 1: Preprocessing</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-2-exploratory-data-analysis-5c3aaedc04b7">Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-3-forecasting-stationary-time-series-using-sarima-f0ff1284bebb">Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA</a></li><li>Statistical Modeling of Time Series Data Part 4: Forecasting Volatility using GARCH</li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-5-arma-garch-model-for-time-series-forecasting-98beeedcfba8">Statistical Modeling of Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting.</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-6-forecasting-non-stationary-time-series-using-9acc28c39db9">Statistical Modeling of Time Series Data Part 6: Forecasting Non — Stationary Time Series using ARMA</a></li></ul><h3>References</h3><p>[1] <a href="https://365datascience.com/courses/time-series-analysis-in-python/">365DataScience</a> Course on Time Series Analysis</p><p>[2] <a href="https://machinelearningmastery.com/time-series-forecasting/">machinelearningmastery</a> blogs on Time Series Analysis</p><p>[3] <a href="https://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity">Wikipedia</a> article on GARCH</p><p>[4] <a href="https://www.youtube.com/channel/UCUcpVoi5KkJmnE3bvEhHR0Q">ritvikmath</a> YouTube videos on the GARCH Model.</p><p>[5] <a href="https://arch.readthedocs.io/en/latest/univariate/univariate_volatility_forecasting.html#Fixed-Window-Forecasting">arch</a> documentation for forecasting using GARCH model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e9ff832f7e5" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/statistical-forecasting-of-time-series-data-part-4-forecasting-volatility-using-garch-1e9ff832f7e5">Statistical Forecasting of Time Series Data Part 4: Forecasting Volatility using GARCH</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA]]></title>
            <link>https://pub.towardsai.net/statistical-modeling-of-time-series-data-part-3-forecasting-stationary-time-series-using-sarima-f0ff1284bebb?source=rss-2361823749f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ff1284bebb</guid>
            <category><![CDATA[statistical-modeling]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yashveer Singh Sohi]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 13:02:27 GMT</pubDate>
            <atom:updated>2020-12-22T13:02:27.962Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-visualization">Data Visualization</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dCIxqI6VsoJIne6G" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In these series of articles, the S&amp;P 500 Market Index is analysed using popular Statistical Model: <strong>SARIMA </strong>(Seasonal Autoregressive Integrated Moving Average), and <strong>GARCH </strong>(Generalized AutoRegressive Conditional Heteroskedasticity).</p><p>In the first part, the series was scrapped from the yfinance API in python. It was cleaned and used to derive the S&amp;P 500 Returns (percent change in successive prices) and Volatility (magnitude of returns). In the second part, a number of time series exploration techniques were used to derive insights from the data about characteristics like trend, seasonality, stationarity, etc. With these insights, in this article, models from the SARIMA class of models are built for forecasting Market Returns.</p><p>The code used in this article is from <strong>Returns Models/SARIMA for SPX Returns.ipynb</strong> notebook in this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a></p><h3>Table of Contents</h3><ol><li>Importing Data</li><li>Train-Test Split</li><li>A word on Stationarity</li><li>Stationarity of S&amp;P 500 Returns</li><li>Non Seasonal Models (ARIMA)</li><li>Parameter Selection for ARIMA Models</li><li>Fitting ARIMA(1, 0, 1)</li><li>Seasonal Models (SARIMA)</li><li>Parameter Selection for ARIMA Models</li><li>Fitting SARIMA(1, 0, 1)(1, 0, 1, 5)</li><li>Forecasting Using ARIMA and SARIMA</li><li>Confidence Intervals</li><li>Conclusion</li><li>Links to other parts of this series</li><li>References</li></ol><h3>Importing Data</h3><p>Here we import the dataset that was scrapped and preprocessed in part 1 of this series. Refer part 1 to get the data ready, or download the <strong>data.csv</strong> file from this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href">https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Hs8ScyWxMhgqIkXjJIyQFQ.png" /><figcaption>Output for the previous code cell showing the first 5 rows of the dataset</figcaption></figure><p>Since this is same code used in the previous parts of this series, the individual lines are not explained in detail here for brevity.</p><h3>Train-Test Split</h3><p>We now split the data into train and test sets. Here all the observations on and from 2019–01–01 form the test set, and all the observations before that is the train set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href">https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*3tDWhR-cwVwh5dheM28IEg.png" /><figcaption>Output of previous code cell showing the shape of training and testing sets</figcaption></figure><h3>A word on Stationarity</h3><p>Stationarity, in the context of time series analysis, means that the statistical properties of a series (mean, variance, etc.) remain fairly constant over time. While fitting statistical models, stationarity in a series is highly desirable. This is due to the face that, if a series is non-stationary, then its distribution will change over time. So, the distribution of data used to train models will be different than the distribution of data for which forecast needs to be generated. Therefore, the quality of forecasts will most likely be poor.</p><p>To check for stationarity, we use the <strong>ADF (Augmented-Dickey Fuller)</strong> Test. It has the following 2 hypothesis:</p><ul><li>Null Hypothesis (<strong>H0</strong>): Series has a unit root, or it is <strong>not stationary</strong>.</li><li>Alternate Hypothesis (<strong>H1</strong>): Series has no unit root, or it is <strong>stationary</strong>.</li></ul><p>The ADF test outputs the test statistic along with the p-value of the statistic. If the p-value of the statistic is less than the confidence levels: 1% (0.01), 5% (0.05) or 10% (0.10) ) then we can reject the Null Hypothesis and call the series stationary.</p><h3>Stationarity of S&amp;P 500 Returns</h3><p>Let us use the adfuller() from statsmodels.tsa.stattools package in python to check the stationarity of the series used in this article: S&amp;P 500 Returns ( spx_ret ).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a57e3ce821720fd53eda22478d492fd/href">https://medium.com/media/4a57e3ce821720fd53eda22478d492fd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*rEO4xfhKGMPdUB6gZllUjg.png" /><figcaption>Output of the previous code cell showing the results of ADF test on S&amp;P 500 returns</figcaption></figure><p>Since, the p-value (2nd value in the tuple returned by the adfuller() function) is much less than any of the confidence levels, we can conclude that the series is stationary. Thus, we can use this series to build models, and use these models to forecast for our test set.</p><h3>Non Seasonal Models : ARIMA</h3><p>The non seasonal SARIMA model: ARIMA is an acronym for <strong>Auto-Regressive Integrated Moving Average Model</strong>. This model is a collection of 3 components:</p><ul><li><strong>AR (Auto-Regressive Component): </strong>This component of the ARIMA model is used to capture the dependence of current observation with past observations. The parameter of ARIMA models that control this component is denoted as <strong>p.</strong></li><li><strong>I (Integrated)</strong>: This component of the ARIMA model is used to denote the number of times the series needs to be differenced with lagged versions of itself. Ideally this operation of differencing should be carried out till the series is stationary. The parameter of ARIMA models that control this component is denoted as <strong>d.</strong></li><li><strong>MA (Moving Average)</strong>: This component of the ARIMA model is used to capture the effect of past residuals on the value of the current observation. The parameter of ARIMA models that control this component is denoted as <strong>q.</strong></li></ul><p>An ARIMA models is usually specified as follows: <strong>ARIMA(p, d, q)</strong>. The parameters p, d, and q represent the AR, I and MA components of the model as described above.</p><h3><strong>Parameter Selection</strong> for ARIMA Models</h3><p>The following rules are general guidelines that are commonly followed while choosing initial parameters for the ARIMA models.</p><ul><li><strong>p (AR Component)</strong>: The number of significant lags in the <strong>PACF</strong> plot of the series is a good stating point for AR component.</li><li><strong>d (I Component)</strong>: If the series is not stationary and needs to be differenced a certain number of times to remove trend and stationarity, then the number of times this operation is done becomes the order of the Integrated Component.</li><li><strong>q (MA Component)</strong>: The number of significant lags in the <strong>ACF</strong> plot of the series is a good stating point for AR component.</li></ul><p>Let’s start the model building process by first plotting the ACF and PACF plots for S&amp;P 500 Returns. With these graphs we will estimate the optimal parameters for the ARIMA model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64cf54fc493921f8c15c11372bfbaed0/href">https://medium.com/media/64cf54fc493921f8c15c11372bfbaed0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*y9I3w9dh84R5rCvu7eYMcA.png" /><figcaption>Output of the previous code cell showing the ACF (left) and PACF (right) plots for S&amp;P 500 Returns</figcaption></figure><p>The plot_acf() and plot_pacf() functions are used from the statsmodels.graphics.tsaplots package in python to plot the ACF and PACF plots. The zero = False argument in these functions is used to make sure that the zero-th lag is not plotted. This lag is the input series itself and thus, it will always be perfectly correlated. Hence, including it will not give any new insights. The lags = 40 argument is used to plot ACF and PACF plots for 40 lags in the past.</p><p><strong>Note:</strong> The input series for the plot_acf() and plot_pacf() functions should be free of any Null values.</p><p>The output shows that for both ACF and PACF plots, the first 2 lags seem significant. The significance levels drop significantly after the first 2 lags and spikes back up from 5th lag onward. Thus, a reasonable starting point for the ARIMA parameters is:</p><ul><li>p = 1 or p = 2 (from PACF plot)</li><li>d = 0 (the series was already stationary as proved by the ADF test)</li><li>q = 1 or q = 2 (from ACF plot)</li></ul><p>Thus we have a choice between the following models: ARIMA(1, 0, 1), ARIMA(1, 0, 2), ARIMA(2, 0, 1), and ARIMA(2, 0, 2). Just to keep things simple, the ARIMA(1, 0, 1) is built in this series. Since, there is no Integrated component here, we can also call this model ARMA(1, 1).</p><h3><strong>Fitting ARIMA(1, 0, 1)</strong></h3><p>Now we will fit an ARIMA(1, 0, 1) model for S&amp;P 500 returns. After fitting the model, we will plot the ACF and PACF plots of the residuals of this model. If the model is good then the residuals will be similar to random noise (or white noise). This means that a good model will yield residuals that are unpredictable and have no underlying patterns. In terms of ACF and PACF plots, there should be no significant lags for the residuals of a good ARIMA model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc95751562113387da09e7b2fa231780/href">https://medium.com/media/bc95751562113387da09e7b2fa231780/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*sWS8gq13z4Rz5P-KEEafdg.jpeg" /><figcaption>Summary table generated after fitting ARIMA(1, 0, 1) Model on S&amp;P 500 Returns.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*J6X_94O9HHhs94VOp_8_ng.png" /><figcaption>ACF and PACF plots for the residuals of ARIMA(1, 0, 1) model used above.</figcaption></figure><p>The SARIMAX() function from statsmodels.tsa.statespace.sarimax package in python is used to build the ARIMA(1, 0, 1) model. The training series is passed as the first argument to SARIMAX() function. The next argument is order . This is a tuple representing the (p, d, q) order of the model. In this case the tuple was (1, 0, 1) . The model is defined and stored in the variable model . The fit() method is called on this variable and the fitted model is stored in the variable model_results . The summary() method is called on the model_results variable and is used to display the summary table. Next, the resid method is called on model_results variable to get the residuals. The ACF and PACF plots for the model_results.resid series is then generated.</p><p><strong>Summary Table:</strong> In the summary table, there are 3 distinct sections (shown in the image above). The first 2 sections are marked in the image. The second column of <strong>section I</strong> contains some useful metrics that are used to compare different ARIMA models. As a general rule of thumb, the model with <strong>higher Log Likelihood</strong> or <strong>lower IC (AIC, BIC or HQIC)</strong> is <strong>better, </strong>and vice versa. <strong>Section II</strong> of the summary table gives information about the different coefficients of the AR, and MA components, and the constants used in the model. The <strong>coef </strong>column contains the actual value of the coefficients, and the <strong>P&gt;|Z| </strong>column contains the confidence levels. This column indicates whether the coefficients are significant. If the confidence level is set at 5%, then the significant coefficients will have value <strong>&lt;0.05 </strong>in this column. Therefore, in this case, all the coefficients are clearly significant.</p><p><strong>Residuals: </strong>If a model is performing well, then the residuals or errors made by the model must not have any underlying pattern in them. If that is the case then the model fails to capture all the information in the data. Thus, a successful model should result in residuals that have no patterns, or the residuals generated in such a case should resemble white noise. This can be checked by making sure that there are no significant lags in the ACF and PACF plots of the residuals. The ACF and PACF plots of the residuals of this model, as seen in the image above, have almost no significant lags. Hence, this model captures all the information reasonably well.</p><h3>Seasonal Model: SARIMA</h3><p>The ARIMA model explored above cannot effectively capture the seasonal patterns in the series. For this, we use the SARIMA class of models. SARIMA stands for <strong>Seasonal Auto-Regressive Integrated Moving Average</strong> model. A SARIMA models is specified as follows: <strong>SARIMA(p, d, q)(P, D, Q, m)</strong></p><p><strong>Non-Seasonal Parameters:</strong></p><ul><li><strong>p (AR component)</strong>: Same as the AR component in ARIMA.</li><li><strong>d (I component)</strong>: Same as the I component in ARIMA. Denotes the number of times successive differencing operation is performed to make the series stationary.</li><li><strong>q (MA component)</strong>: Same as the MA component in ARIMA.</li></ul><p><strong>Seasonal Parameters:</strong></p><ul><li><strong>m (Seasonal Period)</strong>: This denotes the number of periods in the series after which a seasonal pattern is repeated. It is common to see this parameter<strong> </strong>also denoted by the letter <strong>s.</strong></li><li><strong>P (Seasonal AR component)</strong>: This parameter captures the effect of past lags on current observations. Unlike <strong>p</strong>, the past lags are separated from the current lag by multiples of <strong>m</strong> lags. For eg, if <strong>m</strong>=12, and <strong>P</strong>=2, then the current observation is estimated using observations from the 12th lag and 24th lag.</li><li><strong>D (Seasonal I component)</strong>: This is the number of times seasonal differences need to be calculated in order to make the series stationary. Unlike <strong>d</strong>, where the differencing was done with successive observations (1st lagged series), here the differencing is done between the series and <strong>m</strong>th lagged series.</li><li><strong>Q (Seasonal MA Component)</strong>: This parameter captures the effect of past residuals on current observations. Unlike <strong>q</strong>, the past lags are separated from the current lag by multiples of <strong>m</strong> lags. For eg, if <strong>m</strong>=12, and <strong>Q</strong>=2, then the current observation is estimated using residuals from the 12th lag and 24th lag.</li></ul><h3>Parameter Estimation of SARIMA Models</h3><p>The parameters of the SARIMA(p, d, q)(P, D, Q, m) are estimated using the following general guidelines:</p><ul><li><strong>p</strong>: Plot the <strong>PACF</strong> plot for the series and count the number of significant lags.</li><li><strong>d</strong>: The number of successive differencing operations needed to convert the series to stationary.</li><li><strong>q</strong>: Plot the <strong>ACF</strong> plot for the series and count the number of significant lags.</li><li><strong>m</strong>: The number of lags after which some seasonal pattern is observed.</li><li><strong>P</strong>: Plot the <strong>PACF </strong>plot again, and observe the number of significant lags separated by multiples of <strong>m.</strong></li><li><strong>D</strong>: The number of seasonal differences needed to convert the series to stationary.</li><li><strong>Q</strong>: Plot the <strong>ACF </strong>plot again, and observe the number of significant lags separated by multiples of <strong>m.</strong></li></ul><p>We have already made the ACF and PACF plots for the S&amp;P 500 Returns series. For ease of access, the same image of the plots is displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*y9I3w9dh84R5rCvu7eYMcA.png" /><figcaption>ACF and PACF Plots for S&amp;P 500 Returns</figcaption></figure><p><strong>Parameter Estimation:</strong></p><ul><li><strong>p = 1, or p = 2</strong> : First 2 lags of PACF are significant.</li><li><strong>d = 0</strong> : No successive differencing was performed in the S&amp;P 500 Returns series.</li><li><strong>q = 1, or q = 2</strong> : First 2 lags of ACF are significant.</li><li><strong>m = 5</strong> : The observations are observed on business days (5 days a week) and there was presence of a seasonal pattern in the decomposition of the series done in part 2 of this series.</li><li><strong>P = 1</strong> : 5th lag is significant in PACF plot.</li><li><strong>D = 0</strong> : There was no seasonal differencing performed here.</li><li><strong>Q = 1, or Q = 2</strong> : 5th and 10th lags are significant in ACF plot.</li></ul><p>Using a permutation of all the parameters above we can have 8 different models:</p><ul><li>SARIMA(1, 0, 1)(1, 0, 1, 5)</li><li>SARIMA(1, 0, 1)(1, 0, 2, 5)</li><li>SARIMA(1, 0, 2)(1, 0, 1, 5)</li><li>SARIMA(1, 0, 2)(1, 0, 2, 5)</li><li>SARIMA(2, 0, 1)(1, 0, 1, 5)</li><li>SARIMA(2, 0, 1)(1, 0, 2, 5)</li><li>SARIMA(2, 0, 2)(1, 0, 1, 5)</li><li>SARIMA(2, 0, 2)(1, 0, 2, 5)</li></ul><p>Like ARIMA, lets use the simplest one, which is SARIMA(1, 0, 1)(1, 0, 1, 5)</p><h3>Fitting SARIMA(1, 0, 1)(1, 0, 1, 5)</h3><p>Very similar to fitting the ARIMA(1, 0, 1) model, we will now fit a SARIMA(1, 0, 1)(1, 0, 1, 5) model to S&amp;P 500 Returns. Then using the ACF and PACF plots on the residuals the models performance will be evaluated. If the model is able to capture the information in the data then the residuals should resemble white noise. In other words, the ACF and PACF plots of the residuals should result in no significant lags.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b7e0f0457f781392be95148cddda6cd/href">https://medium.com/media/2b7e0f0457f781392be95148cddda6cd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*qzfbTXUBbIkideRarwykKw.png" /><figcaption>Summary table for the SARIMA(1, 0, 1)(1, 0, 1, 5) Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*F5dbHGnSJuHIEO1zQgyfHA.png" /><figcaption>ACF and PACF plots for residuals of SARIMA(1, 0, 1)(1, 0, 1, 5)</figcaption></figure><p>The code used to fit the SARIMA model is almost the same as the one used for ARIMA model. The only difference is the addition of the seasonal_order parameter in the SARIMAX() function. Like ARIMA, here also a SARIMA model is fitted to the S&amp;P 500 Returns series, the summary table is printed out, and the ACF and PACF plots for the residuals are constructed.</p><p>The summary table shows that all the coefficients are significant and, the residuals resemble white noise based on the ACF and PACF plots. Thus the model performs well in capturing all the information in the series.</p><h3>Forecasting using ARIMA and SARIMA</h3><p>Let us now forecast the S&amp;P 500 Returns using the models that we trained in the previous sections.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a38c52c13cd5acd91cd77def3bfaf1/href">https://medium.com/media/32a38c52c13cd5acd91cd77def3bfaf1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*qrCUm_XnprR63GN2AvAXSQ.png" /><figcaption>Forecasts generated by ARIMA and SARIMA models plotted against actual observations</figcaption></figure><p>The predict() method is called on the fitted models to generate a series of predictions between the time interval specified by the start and the end parameters of the function. Once we have the predictions, the mean_squared_error() function, from sklearn.metrics, is used to generate the <strong>MSE</strong> (Mean Squared Error) score for the predictions. sqrt() , A simple square root function from numpy , is then used to generate the <strong>RMSE</strong> (Root Mean Squared Error) score for the predictions. The predictions are then plotted against the actual observations in the test set to see the performance of the model.</p><p>The image above shows that the ARIMA model slightly outperforms the SARIMA model for S&amp;P 500 Returns based on the RMSE score. However, the Log Likelihood, AIC etc. indicate that the SARIMA model outperforms the ARIMA model. The RMSE is calculated over predictions in the test set. On the other hand, the AIC is calculated over the train set. Thus if the priority is to model the train set well, then the model with lower AIC should be preferred, and if the model should perform well on the test set, then RMSE will have greater importance. In this case, we want better predictions, and hence, we will choose the model that performs the best on the test set. Therefore, the final model chosen for S&amp;P 500 Returns is ARIMA(1, 0, 1).</p><h3>Confidence Intervals</h3><p>Confidence Intervals give an idea about the margin of error that could be associated with the predictions. They offer unique insights about when, and to what extent are the predictions stable. That is why they are important while making business decisions based on the forecasts. Now let’s generate confidence intervals for the ARIMA(1, 0, 1) model from above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bebe8ef7769d119d82b243720d661ae/href">https://medium.com/media/2bebe8ef7769d119d82b243720d661ae/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*Rg6qc3npFP8drLsr4MnP2w.png" /><figcaption>Output of the previous code cell showing the first few rows of the forecasts_df, and the plot of forecasts, and confidence intervals against the actual observations</figcaption></figure><p>First we use the get_forecast() function on the fitted model: model_results , and store the output in the variable forecasts . The function takes in an integer number of periods for which the forecasts need to be generated. In this case, we specify the number of periods in the test set as the argument. Next, the conf_int() function is called on the forecasts object. This function takes in argument alpha which controls the confidence level. alpha = 0.05 indicates that we have 95% confidence in observing the predictions between the intervals shown in green in the image. We then generate the predictions from the model using the predict() method as before. The first few rows of the forecasts_df is displayed for better visualization of the data. Finally, the forecasts, and confidence intervals are plotted against the actual values of the S&amp;P 500 Returns.</p><h3>Conclusions</h3><p>In this article we looked at the SARIMA class of models. We used these models to fit S&amp;P 500 Returns series. Then we used these models to get confidence intervals for our predictions. However, the confidence intervals generated were constant and did not offer any significant insight on our model’s predictions.</p><p>In the image above, it is clear that there are regions where the model had reasonably accurate predictions and there were regions where the predictions were off by a bigger margin. The confidence intervals should reflect these changes in prediction accuracy. To do this, we will use a <strong>GARCH</strong> model on top of the ARIMA model from this article. So the next article will first introduce the GARCH model, and the one after that covers ARIMA+GARCH model to fit S&amp;P 500 Returns.</p><h3>Links to other parts of this series</h3><ul><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-1-data-preparation-and-preprocessing-b52f26f6213c">Statistical Modeling of Time Series Data Part 1: Preprocessing</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-2-exploratory-data-analysis-5c3aaedc04b7">Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis</a></li><li>Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA</li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-of-time-series-data-part-4-forecasting-volatility-using-garch-1e9ff832f7e5">Statistical Modeling of Time Series Data Part 4: Forecasting Volatility using GARCH</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-5-arma-garch-model-for-time-series-forecasting-98beeedcfba8">Statistical Modeling of Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting.</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-6-forecasting-non-stationary-time-series-using-9acc28c39db9">Statistical Modeling of Time Series Data Part 6: Forecasting Non — Stationary Time Series using ARMA</a></li></ul><h3>References</h3><p>[1] <a href="https://365datascience.com/courses/time-series-analysis-in-python/">365DataScience</a> Course on Time Series Analysis</p><p>[2] <a href="https://machinelearningmastery.com/time-series-forecasting/">machinelearningmastery</a> blogs on Time Series Analysis</p><p>[3] <a href="https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average">Wikipedia</a> articles on SARIMA class of models</p><p>[4] <a href="https://www.youtube.com/watch?v=JntA9XaTebs">Tamara Louie: Applying Statistical Modeling &amp; Machine Learning to Perform Time-Series Forecasting</a></p><p>[5] <a href="https://otexts.com/fpp2/">Forecasting: Principles and Practice</a> by Rob J Hyndman and George Athanasopoulos</p><p>[6] <a href="https://www.analyticsvidhya.com/blog/2018/09/non-stationary-time-series-python/">A Gentle Introduction to Handling a Non-Stationary Time Series in Python</a> from Analytics Vidhya</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ff1284bebb" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/statistical-modeling-of-time-series-data-part-3-forecasting-stationary-time-series-using-sarima-f0ff1284bebb">Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis]]></title>
            <link>https://pub.towardsai.net/statistical-modeling-of-time-series-data-part-2-exploratory-data-analysis-5c3aaedc04b7?source=rss-2361823749f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3aaedc04b7</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Yashveer Singh Sohi]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 13:02:33 GMT</pubDate>
            <atom:updated>2020-12-21T13:02:33.386Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-visualization">Data Visualization</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_b8ILLqf7AHy_Vce" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this series of articles, the S&amp;P 500 Market Index is analyzed using popular Statistical Model: <strong>SARIMA </strong>(Seasonal Autoregressive Integrated Moving Average) and <strong>GARCH </strong>(Generalized AutoRegressive Conditional Heteroskedasticity).</p><p>In the first part, the data used in this series of articles, S&amp;P 500 Prices (referred to as spx interchangeably), was scrapped from yfinance API. The series captures each business day from 1994–01–06 to 2020–08–30. It was cleaned and used to derive two other series used to study the market: S&amp;P 500 Returns (Percent Change in prices between successive observations) and S&amp;P 500 Volatility (Magnitude of Returns).</p><p>In this second part, the preprocessed time series is visualized and explored to understand any trends, repeating patterns, and/or other characteristics that could later be used to model the series and forecast the future values (covered in subsequent sections). The code used in this article is from <strong>Visualization and EDA.ipynb </strong>notebook in this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a>.</p><h3>Table of Contents</h3><ol><li>Importing Data</li><li>Preliminary Line Plots</li><li>Splitting Time Series Data into Train-Test sets</li><li>Exploring Yearly Trends using Box Plots</li><li>Distribution of Data</li><li>Data Decomposition (Additive and Multiplicative)</li><li>Smoothing the Time Series (Moving Averages)</li><li>Correlation Plots (ACF and PACF)</li><li>Stationarity Check</li><li>Conclusion</li><li>Links to other parts of this series</li><li>References</li></ol><h3>Importing Data</h3><p>Before starting the exploration, first, let’s import the preprocessed data from the last part. The data was scraped from yfinance API in python. It contained the S&amp;P 500 stock price data from 1994–01–06 to 2020–08–30 . The data was then cleaned (filling of missing value) and used to create 2 new series: Returns and Volatility. Thus the final dataset has the following 3 columns: spx (S&amp;P 500 Prices), spx_ret (S&amp;P 500 Returns) and spx_vol (S&amp;P 500 Volatility). Refer to part 1 to get the data ready, or download the <strong>data.csv</strong> file from this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href">https://medium.com/media/700bcc1ce5d188851dc14f292716d9ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Hs8ScyWxMhgqIkXjJIyQFQ.png" /><figcaption>Output for the previous code cell showing the first 5 rows of the dataset</figcaption></figure><p>First, we import all the standard libraries used for almost any analysis using python. The sns.set() function just adds a theme to the plots made by matplotlib.pyplot . Excluding it will only result in a few styling changes.</p><p>The read_csv() function takes in the file-path as the argument (“data.csv” in this case) and stores the result is a pandas DataFrame. Since the Date column is stored as anobject data type (or string), The to_datetime() function in pandas is used to convert the dates to datetime format. Once this is done, we can set the dates of this dataframe as its index using the set_index() function. This would make indexing and slice much more intuitive. The inplace = True argument instructs pandas to perform this operation on the same dataframe and not on a copied version of the dataframe. Without this argument, the changes will not be reflected in the original data dataframe. And finally, the data.head() function just displays the first 5 rows of the dataframe (as shown in the image above).</p><h3>Preliminary Line Plots</h3><p>Simple Line plots are a great way to visualize the trend of the series over time. Generally, for line plots (and other plots in this article), the x-axis represents time, and the y-axis represents the series.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/865c561fb2cb36828633567a15481768/href">https://medium.com/media/865c561fb2cb36828633567a15481768/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*mbu5bM77AT_rhvSKDsq4dA.png" /><figcaption>Output for the previous code cell showing all the line plots for S&amp;P 500 Prices, Returns, and Volatility</figcaption></figure><p>plt.rcParams[“figure.figsize”] is used to set the size of the figure. It expects a tuple with the length and height of the figure as follows: (length, height). plt.subplots() is used to build multiple plots within a figure. The figure container is stored in the first output of this function (fig in this case), and the position of the plots stored in the second output (ax in this case). The argument (1, 3) specifies that there are 3 subplots in one row. The 3 subplots can be accessed by indexing the ax variable. Thus, ax[0].plot() it will plot the series specified in the plot() method in the first subplot and similarly for ax[1] and ax[2] . The set_title() function allows us to set a title to a subplot. The legend() function enables us to show the labels in the plot. The text in the label is mentioned in the plot() function as the label argument. And finally, the plt.show() displays the output free of any additional Jupyter Notebook text. Without this, there might be some text visible just before the plot in a Jupyter Notebook like environment.</p><p>These plots indicate that the S&amp;P 500 Prices have generally been increasing since 1994, with 2 major dips near 2004 and 2008. The Returns are fairly centered around 0 and show high aberrations around 2004 and 2008. Similarly, the Volatility also shows that the market was rather unstable during these 2 periods. A period of higher volatility (magnitude of returns) shows the presence of an unstable market during that period.</p><h3>Splitting Time Series Data into Train-Test sets</h3><p>After the preliminary plots built in the previous section, it’s best that we split the data into training and testing sets. This is because, in most real-world forecasting problems, we will not have access to future observations. Thus, in order to simulate a real-world problem, we should explore only a segment of our data and use these findings to build models to predict the remainder of the data. So before moving forward with any exploration, let’s first split the data into <strong>Training</strong> and <strong>Testing</strong> sets.</p><p>The training set will be used to build the model. The model will then be used to forecast/predict values in the testing data set, and the actual observations in the testing set will be used to evaluate the model&#39;s performance. Once the model reaches a desired level of accuracy, it is used to forecast unseen data (i.e., data outside the train and test sets).</p><p><strong>Note:</strong> Since we are using the testing set to evaluate and fine-tune our models, the better and more precise term for this set would be <strong>Cross-Validation Set. </strong>And the unseen data (for time periods after the ones observed in the data) for which the forecasts need to be generated would be referred to as the testing set. However, in this series of articles, the goal is to build models and see their fit on training and cross-validation sets only. Thus, for simplicity, the terms training and testing sets are used.</p><p>Now we need to choose how to divide the data we have into training and testing sets. In other problems of Data Science like classification, or regression, usually, we split the data into an 80–20 (80% for training and 20 % for testing) split, and this is done by randomly shuffling the data. However, in time series analysis, if we shuffle the data, we remove the time dependence of the data. Thus, the preferred approach is to split the data at some point in time. In this case, we split the data into 2 parts: Everything before 2019–01–01 is the train set, and every observation after this date is the test set. So, we build our models on data till 2019–01–01and try to predict the data observed since 2019–01–01.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href">https://medium.com/media/11740302b8e44b550cc9d91211c2f8d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*3tDWhR-cwVwh5dheM28IEg.png" /><figcaption>The output of the previous code cell showing the shape of training and testing sets</figcaption></figure><p>The data before 2019–01–01 is accessed using the loc indexing operator on the data dataframe. So, the code data.loc[:“2018–12–31”] just extracts all the columns of data from the starting index to the index labeled “2018–12–31” And the code data.loc[“2019–01–01”:] extracts all the columns from the index labeled “2019–01–01” to the last index. The train_df and test_df store the training and testing sets, respectively. By printing the shape of these 2 data frames, it can be seen that we have 6518 observations in our training set and 174 observations in the test set.</p><p>Subsequently, all exploration is done on the train set: train_df</p><h3>Exploring Yearly Trends using Box Plots</h3><p>According to <a href="https://en.wikipedia.org/wiki/Box_plot">Wikipedia</a>:</p><blockquote>In descriptive statistics, a <strong>box plot</strong> or <strong>boxplot</strong> is a method for graphically depicting groups of numerical data through their quartiles.</blockquote><p>Let’s understand this definition by actually looking at a boxplot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*utIxgPsEHTGLDfE3GBWq8A.png" /><figcaption>An Example of a Box Plot</figcaption></figure><p>A box plot is characterized by 5 horizontal lines labeled as <strong>A</strong>, <strong>B</strong>, <strong>C</strong>, <strong>D,</strong> and <strong>E </strong>in the plot above.</p><ul><li><strong>A: </strong>This line represents the maximum value of the dataset (excluding the outliers)</li><li><strong>B: </strong>This line represents the 3rd Quartile or 75th percentile. This is the median of the upper half of the dataset</li><li><strong>C: </strong>This line represents the 2nd Quartile or 50th percentile of the dataset. In other words, this is the median of the complete dataset</li><li><strong>D: </strong>This line represents the 1st Quartile or 25th percentile. This is the median of the lower half of the dataset</li><li><strong>E: </strong>This line represents the minimum value of the dataset (excluding the outliers)</li><li>The outliers of the data are plotted as points above and below the maximum and minimum line (<strong>A</strong> and <strong>E,</strong> respectively)</li></ul><p>So, a boxplot neatly summarizes the distribution of the data along with its outliers. Let’s build boxplots for spx, spx_ret and spx_vol for each year in our training dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1145baf5bb93a0b828eea5b46e07967/href">https://medium.com/media/a1145baf5bb93a0b828eea5b46e07967/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*mJdtDBXK_YwDAP7YAcooEg.png" /><figcaption>Yearly Box Plots for S&amp;P 500 Prices</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*aeKQtlOHi-eJB8c3wuuciw.png" /><figcaption>Yearly Box Plots for S&amp;P 500 Returns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*DXIirBv8EA2v-y9yThH2ig.png" /><figcaption>Yearly Box Plots for S&amp;P 500 Volatility</figcaption></figure><p>First, we add a new column to our dataset that stores the year at which the corresponding row of observations were recorded. This is done using the year attribute of the datetime objects that define the index of train_df . The column of years is stored in a column named Year in the train_df . Then we set up 3 subplots, one below the other, and plot the boxplots for spx spx_ret And spx_vol in them. The boxplot() function of pandas is used to make these plots. The function takes in the column that is used to plot the data in the column argument and the column used to group the data to be plotted in the by argument. So, in this case, we are splitting the data by the year (using by = “Year”) and then plotting separate box plots for each year available in the training dataset.</p><p>The presence of a wider boxplot indicates that the values observed that year were widely dispersed. Similarly, the presence of the high number of outliers also shows that in that year, the data had major fluctuations. Based on these, it’s not difficult to identify the years with higher degrees of fluctuations/instability in the market (such as years around 2004 and 2008)</p><h3>Distribution of Data</h3><p>In this section, we try to understand the distribution of the S&amp;P 500 Prices, Returns, and Volatility using <strong>Density Curves</strong> and <strong>Histograms. </strong>The distribution of the data will indicate the range of values that occur more frequently than others, but it will eliminate the factor of time. Thus we will be unable to tell when we encounter a certain value in our dataset just by looking at the distribution plots.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd3c133dc1a928440f1955b389bd89ec/href">https://medium.com/media/bd3c133dc1a928440f1955b389bd89ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*DJsbfxfxYmy_3K9yMCVq_Q.png" /><figcaption>Density Plot for S&amp;P 500 Prices</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*-sPwCdBhLpy5Lu4jBkRwJA.png" /><figcaption>Density Plot for S&amp;P 500 Returns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*peDVPxd0yYQWuWhK0GKUDQ.png" /><figcaption>Density Plot for S&amp;P 500 Volatility</figcaption></figure><p>As with all the plots before, first, we set the size of the figure and define the subplots. Then, we use the distplot() function of seaborn to plot a density curve on top of a histogram for the series passed into the function. Then we set the title for each subplot (using set_title()) and display them (using plt.show()).</p><p>The distribution of S&amp;P 500 Prices look vaguely Normal, with some big spikes along the trailing edge. However, the distribution of S&amp;P 500 Returns looks completely Normal with almost 0 mean. Lastly, since the volatility is never negative and is simply the magnitude of the returns, the distribution of S&amp;P Volatility is heavily right-skewed (long right tail) Normal distribution.</p><h3>Data Decomposition (Additive and Multiplicative)</h3><p>Data decomposition is the process of breaking the time series into 3 components: <strong>Trend</strong>, <strong>Seasonality,</strong> and <strong>Noise</strong>. Doing so gives us insights into repeating patterns in our data that could be used during model building. In python, the statsmodels library is used to do this decomposition. The library provides support for 2 types of decomposition: <strong>Additive</strong> and <strong>Multiplicative.</strong></p><p>In Additive Decomposition, the series is represented as the <strong>sum </strong>of Trend, Seasonality, and Noise, and in Multiplicative Decomposition, the series is represented as the <strong>product</strong> of these 3 components.</p><p>Mathematically, the 2 types of decomposition would be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*CpZAH4WllMK9onziWquM4A.png" /><figcaption>Additive Decomposition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*H8ANs-galVfzQgs6SsLufA.png" /><figcaption>Multiplicative Decomposition</figcaption></figure><p>Let us now look at how to perform this in python. Specifically, the following section will be used to perform additive decomposition on the S&amp;P 500 Prices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f56b284f2324b39dd06108c58843800c/href">https://medium.com/media/f56b284f2324b39dd06108c58843800c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Dh3sbdnFbNd2q-X-6O4iQQ.png" /><figcaption>The output of the previous code cell showing the additive decomposition of S&amp;P 500 Prices.</figcaption></figure><p>First, we import the seasonal_decompose() method from statsmodels.tsa.seasonal package. This function requires us to pass in the time series as the argument. Then, we need to set the model attribute to “additive” to decompose the series into additive components. The output of this function is stored in the result variable, which is simply plotted using the plot() function. This will plot 4 graphs: First is the series itself. The second is the Trend. The next is the Seasonal Component, and the last plot is the Noise.</p><p>In the above plot, the Seasonal Component seems odd. So lets examine it further. Instead of plotting the full seasonal component of the series, lets plot only the first 20 values of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e346cad507e15a9c71037a6b2482e2e/href">https://medium.com/media/8e346cad507e15a9c71037a6b2482e2e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*GPp9yR4_iDx_OUwmX3P4Wg.png" /><figcaption>Output for the previous code cell showing the Seasonal Component of S&amp;P 500 Prices</figcaption></figure><p>The marker = “o” parameter is used to plot the values and mark each observation separately for greater clarity. By using result.seasonal we can access the seasonal component of the decomposed data. The other components can be similarly accessed using result.trend (for the trend) and result.resid (for the noise or residuals).</p><p>The plot clearly shows a repeating cycle every 5 periods. This is fairly logical as our data is stock price data. We observe and collect stock price data on every business day of the week. This means that the data was weekly seasonality, with the week being a business week (5 days a week). However on closer inspection the values are very very negligible (as seen from the scale of the y-axis). So, using a seasonality of 5 periods in our models might not produce great results.</p><p>In order to keep this article short, decomposing other 2 series: spx_ret and spx_vol are not shown here. Also multiplicative decomposition is not shown, but can be plotted using the code in the comments above.</p><h3>Smoothing the Time Series (Moving Averages)</h3><p>Smoothing is a technique used to reduce the erratic fluctuations or spikes in a time series. This is done in order to dampen the effect of noise on the series. A common method to smooth out the time series is by using <strong>Moving Averages. </strong>In this method, the average over a given number of periods (also called as <strong>Window</strong> ) is calculated for each time step in the series. For a time step, a window of size n can be defined in 2 ways:</p><ul><li>The current time step could be at the end of the window. i.e. n-1 past lags and 1 current time step make up the window of size n.</li><li>The current time step could be at the center of the window. i.e. about half of n-1 lags are past lags, the remaining are future lags, and the current time step is at the center.</li></ul><p><strong>Note:</strong> In this example we are using the first approach of selecting a window. So, if the window size is 3, then for the first 2 values we do not have enough lags to calculate the moving average. Thus, for a window of size n, the first n-1 lags of the series will result in null values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ffbe6af37a01fde84feadda98d565a8/href">https://medium.com/media/5ffbe6af37a01fde84feadda98d565a8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*8xmfaHghaiPE_XJPIlTCog.png" /><figcaption>Output for the previous code cell showing the Moving Average (Window = 360 periods) plots for S&amp;P 500 Prices, Returns and Volatility</figcaption></figure><p>As always, we start with setting the size of the figure, and defining the subplots. This time however, we set the sharex argument to True , which allows the subplots to have a common x-axis. In the first row we plot the actual S&amp;P 500 Prices and the smoothed version. The smoothing is done by using the rolling() method on the spx series with a window size of 360 set using window=360 parameter. On calling the mean() function on the rolling(window = 360) function, we get the desired moving average. Similar functions are used in the next 2 rows to get the plots for the spx_ret, and spx_vol series.</p><p>On inspecting the results, we can clearly see the trends in the 3 series. Both Prices and Returns show sharp dips around the years of 2004 and 2008. The Volatility increases during these 2 time periods. All this points to the presence of an unstable market during the aforementioned time periods. S&amp;P 500 Prices have a clear upward trend except the 2 dips. Returns and Volatility are somewhat constant barring the exception of the years around 2004 and 2008.</p><p>By altering the window parameter in the rolling() function, we can build such plots for other window sizes too.</p><h3>Correlation Plots (ACF and PACF)</h3><p>Models that are used to forecast a time series utilize the past values of the series itself to forecast the future. Thus it is important for analysts to know how dependent the series is with past versions (or lagged versions) of itself. The dependence between 2 series can be judged by calculating the <strong>Correlation</strong> between the 2 series. However, in this case, the 2 series are essentially the same. One is a lagged version of the other. Therefore the correlation calculated in such a case is known as <strong>Auto-Correlation.</strong></p><p>There are 2 types of correlation plots used frequently to understand the dependence of the time series with itself. These are <strong>ACF</strong> (Auto-Correlation Function) and <strong>PACF</strong> (Partial Auto-Correlation Function) plots.</p><p>We have discussed what Auto-Correlation is. Let us now understand Partial Auto-Correlation. According to the book <a href="https://amzn.to/2XYS8DD">Introductory Time Series with R</a>,</p><blockquote>The partial autocorrelation at lag k is the correlation that results after removing the effect of any correlations due to the terms at shorter lags.</blockquote><p>Lets understand this with an example. Lets assume that we observed a certain value of S&amp;P 500 Prices on a certain Wednesday. This value would depend on the values observed a few days before (say Tuesday and Monday). So, the dependence between the prices at Wednesday with those at Tuesday and Monday is measured by Auto-Correlation. However, we know that like Wednesday, even Tuesday’s price depends on Monday’s price. Thus, when we estimate the Auto-Correlation between prices on Wednesday and Monday, we are estimating 2 types of correlation: One which is direct (between Wednesday and Monday), and the other which is indirect (between Wednesday and Tuesday, and between Tuesday and Monday). With Partial Auto-Correlation, we remove such indirect effects and estimate the direct dependence only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9793618fc2e08fe784089ab5791e97db/href">https://medium.com/media/9793618fc2e08fe784089ab5791e97db/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*RKYazTycBXJdxugdVCKtCQ.png" /><figcaption>Output for the previous code cell showing the ACF and PACF plots for S&amp;P 500 Prices, Returns and Volatility</figcaption></figure><p>Firstly, we import the package statsmodels.graphics.tsaplots that contains the functions plot_acf() and plot_pacf() used for plotting the ACF and PACF plots for a particular time series. Like other plots in this article, we define the figure size and the subplots (with shared x-axis). Then in the first and second columns of the figure we plot the ACF and PACF of the 3 sereis (spx, spx_ret and spx_vol ) respectively. Both plot_acf() and plot_pacf() take in the time series for with the plots are to be made as their argument. Additionally,plot_acf() (or plot_pacf()) function take in the lags parameter that indicates till how many lags should the function compute the ACF (or PACF). In this case, lags=40 indicate that the function should compute ACF (or PACF) till 40 lags in the history. The zero parameter in plot_acf() (or plot_pacf()) is a boolean parameter that indicates whether the ACF (or PACF) of the series should be computed with a non lagged version of itself. Mathematically this will always be 1 as any series is perfectly correlated with itself. Thus plotting it does not provide any additional information as such.</p><p><strong>Note:</strong> No null values should be present in the series that are passed as the inputs to the plot_acf() and the plot_pacf() functions.</p><p>The blue bands near the x-axis in the plot denotes the significance levels. The lags which are above this band are deemed significant. These plots give an idea as to how the data is dependent on lagged versions of itself. This information will be crucial while building models for these series.</p><h3>Stationarity Check</h3><p>According to the book <a href="https://otexts.com/fpp2/">Forecasting: Principles and Practice</a> by Rob J Hyndman and George Athanasopoulos,</p><blockquote>A stationary time series is one whose properties do not depend on the time at which the series is observed. Thus, time series with trends, or with seasonality, are not stationary — the trend and seasonality will affect the value of the time series at different times. On the other hand, a white noise series is stationary — it does not matter when you observe it, it should look much the same at any point in time.</blockquote><p>Here,<strong> properties </strong>mean statistical properties like <strong>mean, variance, </strong>etc. While building statistical models to forecast a given time series, it is important to ensure that the series given as input is stationary. This is because, only in a stationary series, we can be sure of the fact that the underlying distribution of the data will not change in future. If however, we use a non-stationary series, we can never be sure about the underlying distribution. Hence, the model will assume that the distribution of the data will remain constant for the forecasting period, and since in a non-stationary series, there is no guarantee for this, the predictions in this case are likely to be poor.</p><p>There are a number of ways to test a given series for stationarity. In this article, we look at the following 3:</p><ul><li><strong>Visual Inspection:</strong> We plot the series and inspect whether the series has any obvious trend or seasonal cycles.</li><li><strong>Plotting Summary Statistics:</strong> We plot the summary statistics (mean and variance) of the data over different periods in time.</li><li><strong>Statistical Tests:</strong> The conclusions derived from the above 2 methods are qualitative rather than quantitative. So, to get a more reliable quantitative estimate, a powerful statistical test called as <strong>ADF</strong> (Augmented-Dickey Fuller) Test is used.</li></ul><p><strong>Visual Inspection: </strong>For this we use the preliminary plots that we made in the start of this article here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/865c561fb2cb36828633567a15481768/href">https://medium.com/media/865c561fb2cb36828633567a15481768/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*mbu5bM77AT_rhvSKDsq4dA.png" /><figcaption>Output for the above code cell showing the line plots for S&amp;P 500 Prices, Returns and Volatility</figcaption></figure><p>The explanation for the code is given in the Preliminary Line Plots section of this article. From the output, it is clear that S&amp;P 500 Prices are non-stationary. This is because, the spx series has a very clear trend that is upward most of the time (except for the years around 2004 and 2008). On the other hand, S&amp;P 500 Returns and Volatility do not seem to show any strong upward or downward trend. spx_ret and spx_vol does contain some sharp spikes, but they do not appear in periodic cycles. Let us use another approach to determine their stationarity.</p><p><strong>Plotting Summary Statistics: </strong>In this method we will divide the 3 series: spx, spx_ret and spx_vol year-wise and plot these to see if the summary statistics change over the years.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b97e9ab50b477f42d9b3f1d8c45f7e5/href">https://medium.com/media/2b97e9ab50b477f42d9b3f1d8c45f7e5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*jCxugVEFJWzX6Zm8tMDGSA.png" /><figcaption>Output for the previous code cell showing the yearly mean and variance for S&amp;P 500 Prices, Returns and Volatility</figcaption></figure><p>The groupby() function is used on the train_df to perform group the 3 series based on the year. In order to extract the year from the index of train_df we simply use train_df.index.year and pass it to the by argument in groupby() function. The mean() and var() functions are used on the output of the groupby() to get the dataframes containing the mean and variance of the 3 series for each year. We then plot the line plots for mean and variance for the 3 series: spx , spx_ret and spx_vol by first setting the size of the figure, then defining the number of subplots (and that they shave shared x-axis using sharex = True), and then filling each subplot with the plot of the appropriate series.</p><p>Like before, the yearly means of S&amp;P 500 Prices, show strong trends. The yearly means of S&amp;P 500 Returns and Volatility show some spikes but the magnitude of these spikes are very small as compared to the series itself. So these can be considered as constant. The yearly variances of S&amp;P 500 Prices are not constant and hence spx is a non-stationary series. And similar to the yearly means, the yearly variances of S&amp;P 500 Returns and Volatility show spikes but with low magnitude and hence these 2 series: spx_ret and spx_vol do seem stationary. However, in order to get a more concrete (or more quantitative) proof of stationarity, usually statistical tests are used.</p><p><strong>Statistical Tests (ADF): </strong>Here we use the popular <strong>Augmented-Dickey Fuller (ADF)</strong> Test to check the stationarity of a series. The test has the following 2 hypothesis:</p><ul><li>Null Hypothesis (<strong>H0</strong>): Series has a unit root, or it is <strong>not stationary</strong>.</li><li>Alternate Hypothesis (<strong>H1</strong>): Series has no unit root, or it is <strong>stationary</strong>.</li></ul><p>The concept of unit root is explained very well in <a href="https://www.analyticsvidhya.com/blog/2018/09/non-stationary-time-series-python/">this blog post from Analytics Vidhya</a>. The ADF test outputs the test statistic along with the p-value of the statistic. If the p-value of the statistic is less than the confidence levels: 1% (0.01), 5% (0.05) or 10% (0.10) ) then we can reject the Null Hypothesis and call the series stationary.</p><p>Let us check the stationarity of the 3 series using the ADF test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4060349c7ac63d5bbead8ca274a32825/href">https://medium.com/media/4060349c7ac63d5bbead8ca274a32825/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*losVbJJS2RNhPtyT1dFRHA.png" /><figcaption>Output of the previous code cell showing the ADF test results of S&amp;P 500 Prices</figcaption></figure><p>First we import the adfuller() function from statsmodels.tsa.stattools package. Then we pass the series on which the ADF test is supposed to be performed as the input parameter to the adfuller() test. In the above cell, we pass in the train_df[“spx”] series as the input. The output above shows the results of the ADF Test on spx series. The first value is the test statistic, the second one is the p-value. The next 2 are the number of lags used and the number of observations used. The next dictionary is the statistic values at the 3 confidence levels. As seen in this case, the p-value of the statistic (~0.8 or 80%) is greater than all the 3 confidence intervals. Hence we cannot reject the Null Hypothesis. Therefore, the spx series is non-stationary.</p><p>In order to perform this test on the other 2 series, un-comment the respective lines in the code cell above. Note that the series passed as input to the adfuller() function should be free of any null values. Therefore, for spx_ret and spx_vol, we exclude the first observation before passing the series. The 2 images below show the outputs for ADF test on S&amp;P 500 Returns and Volatility respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*rEO4xfhKGMPdUB6gZllUjg.png" /><figcaption>ADF Test results on S&amp;P 500 Returns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*9SP99J60UMqbBrPVkRPclw.png" /><figcaption>ADF Test results on S&amp;P 500 Volatility</figcaption></figure><p>For both these series, the p-value (2nd value in the respective images) are very close to zero, and much less than the 3 confidence levels mentioned. Thus for these 2 series we can reject the Null Hypothesis. Hence according to the ADF test, S&amp;P 500 Returns and S&amp;P 500 Volatility are both stationary.</p><h3>Conclusions</h3><p>The exhaustive exploration of the 3 series ( spx, spx_ret, and spx_vol ) has revealed some important characteristics of the data. The following points summarize the main insights derived in this article:</p><ul><li><strong>Trend:</strong> spx has a general upward trend, except for the 2 time periods surrounding 2004 and 2008 . On the other hand, spx_ret and spx_vol , have constant trend.</li><li><strong>Seasonality:</strong> On decomposing the data and on plotting the correlation functions, it seems that the data might have a seasonality of 5-periods. This also makes sense according to general intuition that stock market data is observed in the business days. (i.e. 5 days of the week). In other words, a weekly seasonality might be present in our data. This should be explored while building statistical models.</li><li><strong>Stationarity: </strong>The spx series is not stationary. This means that additional preprocessing needs to be performed before the series could be used for model building and subsequent forecasting. spx_ret and spx_vol are both stationary and, hence, they can be used directly for modeling.</li></ul><p>In the following parts of this series various statistical models will be built to forecast the 3 series.</p><h3>Links to other parts of this series</h3><ul><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-1-data-preparation-and-preprocessing-b52f26f6213c">Statistical Modeling of Time Series Data Part 1: Preprocessing</a></li><li>Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis</li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-3-forecasting-stationary-time-series-using-sarima-f0ff1284bebb">Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-of-time-series-data-part-4-forecasting-volatility-using-garch-1e9ff832f7e5">Statistical Modeling of Time Series Data Part 4: Forecasting Volatility using GARCH</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-5-arma-garch-model-for-time-series-forecasting-98beeedcfba8">Statistical Modeling of Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting.</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-6-forecasting-non-stationary-time-series-using-9acc28c39db9">Statistical Modeling of Time Series Data Part 6: Forecasting Non — Stationary Time Series using ARMA</a></li></ul><h3>References</h3><p>[1] <a href="https://365datascience.com/courses/time-series-analysis-in-python/">365DataScience</a> Course on Time Series Analysis</p><p>[2] <a href="https://machinelearningmastery.com/time-series-forecasting/">machinelearningmastery</a> blogs on Time Series Analysis</p><p>[3] <a href="https://en.wikipedia.org/wiki/Box_plot">Wikipedia</a> article on Box Plots</p><p>[4] <a href="https://amzn.to/2XYS8DD">Introductory Time Series with R</a></p><p>[5] <a href="https://www.youtube.com/watch?v=JntA9XaTebs">Tamara Louie: Applying Statistical Modeling &amp; Machine Learning to Perform Time-Series Forecasting</a></p><p>[6] <a href="https://otexts.com/fpp2/">Forecasting: Principles and Practice</a> by Rob J Hyndman and George Athanasopoulos</p><p>[7] <a href="https://www.analyticsvidhya.com/blog/2018/09/non-stationary-time-series-python/">A Gentle Introduction to Handling a Non-Stationary Time Series in Python</a> from Analytics Vidhya</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3aaedc04b7" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/statistical-modeling-of-time-series-data-part-2-exploratory-data-analysis-5c3aaedc04b7">Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Modeling of Time Series Data Part 1 : Data Preparation and Preprocessing]]></title>
            <link>https://pub.towardsai.net/statistical-modeling-of-time-series-data-part-1-data-preparation-and-preprocessing-b52f26f6213c?source=rss-2361823749f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b52f26f6213c</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yashveer Singh Sohi]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 01:02:54 GMT</pubDate>
            <atom:updated>2020-12-21T01:02:54.190Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-visualization">Data Visualization</a></h4><h3>Statistical Modeling of Time Series Data Part 1: Data Preparation and Preprocessing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WDhowNQzrdnWBfrY" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this series of articles, the S&amp;P 500 Market Index is analyzed using popular Statistical Model: <strong>SARIMA </strong>(Seasonal Autoregressive Integrated Moving Average) and <strong>GARCH </strong>(Generalized AutoRegressive Conditional Heteroskedasticity).</p><p>In this first part, the time series is scrapped, pre-processed, and used to build additional series that can indicate the stability and profitability of the market. The code used in this article is from <strong>Preprocessing.ipynb </strong>notebook in this <a href="https://github.com/yashveersinghsohi/Statistical_Modeling_for_Time_Series_Forecasting">repository</a>.</p><h3>Table of Contents</h3><ol><li>A Brief Introduction to Time Series Data</li><li>Downloading the Data from Yahoo Finance</li><li>Extracting Relevant Series</li><li>Handling Missing Data</li><li>Deriving S&amp;P Returns and Volatility</li><li>Conclusion</li><li>Links to other parts of this series</li><li>References</li></ol><h3>A Brief Introduction to Time Series Data</h3><p>A series is said to be <strong>Time Series </strong>if the data points are observed in regular intervals of time. Some examples of time series could be Birth rates over the years, pollutant levels (such as NO2, SO2, etc.) for each day, daily closing prices for a market index (such as S&amp;P 500), etc.</p><p>In time series analysis, we use models that can uncover and exploit the dependence of the data with past versions of itself. In the case of the S&amp;P 500 prices, these models tried to use the correlation between today’s price and the price a few days ago or a few weeks ago to predict what the future prices will be.</p><h3>Downloading the Data from Yahoo Finance</h3><p>Yahoo Finance is one of the most popular sites used to download stock price data. With the python library yfinance in <a href="https://pypi.org/project/yfinance/">pyp</a>l, it is very easy to access and download stock price data for any time interval with only a few lines of code.</p><p>For this series of articles, the S&amp;P 500 stock price from 1994–01–06 (6th January 1994) to 2019–08–30 (30th August 2019) is downloaded via the yfinance API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/381bca262485a5c6bfef06f56631c3fc/href">https://medium.com/media/381bca262485a5c6bfef06f56631c3fc/href</a></iframe><p>In the above code cell, 2 standard libraries of python used in almost all data analysis projects: pandas and numpy are imported. Next to the plotting libraries of python: matplotlib.pyplot and seaborn are imported. The line sns.set() just applies a seaborn wrapper over all subsequent plots. Not including this line will have no effect on the outputs apart from some changes in styling.</p><p>Next, the yfinance library is imported. To download this, follow the instructions <a href="https://pypi.org/project/yfinance/">here</a>. The download function of yfinance takes in the following arguments: tickers (a unique identifier for each time series at Yahoo Finance), interval (The time period between successive data points, which is 1 day or “1d” in this case), and, the start and end dates of the series. The data is then stored in a pandas dataframe (raw_data in this case).</p><p>The first few (shown using raw_data.head() ) and last few rows (shown using raw_data.tail() )of raw_data are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*7Jzlp4CozICUYkFlwb-xlg.png" /><figcaption>First 5 rows of raw_data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*wTfMYKmQV6GG8bdhiYAZuQ.png" /><figcaption>Last 5 rows of raw_data</figcaption></figure><h3>Extracting Relevant Series</h3><p>In this series of articles, the Close prices of the S&amp;P 500 market index are analyzed. Here, we extract the series we’re interested in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c24b8ecafb6aca5486176595884a04c/href">https://medium.com/media/2c24b8ecafb6aca5486176595884a04c/href</a></iframe><p>Since the data is stock market data, we will not observe any value for the weekends. Thus, the time interval between 2 successive observations is 1 day even if the 2 observations are recorded on a Friday and then on a Monday. To convert our dates to follow the business days format (5 days a week), we use the asfreq() method of pandas with “b” as the argument.</p><h3>Handling Missing Values</h3><p>Next, let’s see whether this data has any missing values. This is an important preprocessing step, as the way we fill these values can have a huge impact on the tend.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcd2c27cb1c6686b920d93893a99ddbe/href">https://medium.com/media/dcd2c27cb1c6686b920d93893a99ddbe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*Mrc8Ze_2MH8Y9LjnWFHecw.png" /><figcaption>Output for the cleaning_spx.py code block</figcaption></figure><p>In the code cell above, data.spx.isnull().sum() takes the dataframe (data), extracts the column (spx) and applies the function isnull() to it. This results in a boolean array with True for every Null value encountered. The sum() function takes the sum of these boolean values. Since, True is represented as 1 and False as 0 , this gives the number of missing values in the spx series. The describe() function gives a few statistical measures of the series.</p><p>The number of null values (233) is clearly very small as compared to the count of observations (6459). Thus, a simple imputing function from pandas will be enough for this case. The fillna() function fills the missing values with the values encountered just before the missing value. This behavior is governed by the “ffill” (front fill) argument passed to the method argument. Click <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html">here</a> for more information on other arguments for method.</p><h3>Deriving S&amp;P Returns and Volatility</h3><p>Now that the data is cleaned, it can be used to build some other useful series that helps us to understand the market trends better. These are: <strong>Returns</strong> and <strong>Volatility.</strong></p><p><strong>Returns: </strong>The percent change in a stock price over a given amount of time. In this case, the returns over each day are calculated and stored in the column spx_ret.</p><p><strong>Volatility: </strong>The volatility in a market index refers to the fluctuations in its returns. To gauge the fluctuations or stability in the market, sometimes the magnitude of returns or squared returns are chosen. In this series, the magnitude of returns is chosen as the measure of volatility. The Volatility of spx is stored in the column spx_vol</p><p>Thus, <strong>Returns</strong> are a measure of the gain (positive returns) or loss (negative returns) of a market index, and <strong>Volatility</strong> (magnitude of Returns) is the measure of stability in the index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*sltlvI4sBMiXoX1DsioUsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*PP9pI9oz4_zcWLr4QSbQXA.png" /><figcaption>Formulas for Market Returns and Volatility</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a33a9017b7d97c60c2b4fd22840837e/href">https://medium.com/media/5a33a9017b7d97c60c2b4fd22840837e/href</a></iframe><p>In the above code cell, the Returns and Volatility of spx is calculated. The pct_change() function takes the percent change in the current value and a previous value in the series. How far back should one go to take the previous value is controlled by the numeric value that is given as an argument to this function. Thus, the 1 argument in pct_change() takes the percent change between the current value and the value one-time step before. The mul() function is just used to scale the percents from 0–1to 0–100. Once the Returns are calculated, Volatility is calculated using the abs() function that retrieves the magnitude of the Returns.</p><p><strong>Note:</strong> We’re calculating Returns, and subsequently Volatility, with respect to the data observed one time period previously. It means that for the first observation, we will not have any value (or Null/NA) for Returns and Volatility. This is obvious as for the first value (recorded on 1994–01–06 in this case), we do not have any previous value, and hence, we cannot calculate the Returns or the Volatility here.</p><p>Let’s take a final look at our data by using the head() and the tail() functions to view the first and last 5 rows of the data, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Hs8ScyWxMhgqIkXjJIyQFQ.png" /><figcaption>First 5 rows of the preprocessed S&amp;P 500 data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*ygsJ04UlrR1DWo9nIzRpHw.png" /><figcaption>Last 5 rows of the preprocessed S&amp;P 500 data</figcaption></figure><h3>Conclusion</h3><p>In this article, the S&amp;P 500 data is scrapped off the yfinance API, it is cleaned and used to derive other series like S&amp;P 500 Returns and Volatility. In the next part, the 3 series generated will be visualized using common time series exploration techniques.</p><h3>Links to other parts of this series</h3><ul><li>Statistical Modeling of Time Series Data Part 1: Preprocessing</li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-2-exploratory-data-analysis-5c3aaedc04b7">Statistical Modeling of Time Series Data Part 2: Exploratory Data Analysis</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-modeling-of-time-series-data-part-3-forecasting-stationary-time-series-using-sarima-f0ff1284bebb">Statistical Modeling of Time Series Data Part 3: Forecasting Stationary Time Series using SARIMA</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-of-time-series-data-part-4-forecasting-volatility-using-garch-1e9ff832f7e5">Statistical Modeling of Time Series Data Part 4: Forecasting Volatility using GARCH</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-5-arma-garch-model-for-time-series-forecasting-98beeedcfba8">Statistical Modeling of Time Series Data Part 5: ARMA+GARCH model for Time Series Forecasting.</a></li><li><a href="https://medium.com/@yashveersinghsohi/statistical-forecasting-for-time-series-data-part-6-forecasting-non-stationary-time-series-using-9acc28c39db9">Statistical Modeling of Time Series Data Part 6: Forecasting Non - Stationary Time Series using ARMA</a></li></ul><h3>References</h3><p>[1] <a href="https://365datascience.com/courses/time-series-analysis-in-python/">365DataScience</a> Course on Time Series Analysis</p><p>[2] <a href="https://machinelearningmastery.com/time-series-forecasting/">machinelearningmastery</a> blogs on Time Series Analysis</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b52f26f6213c" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/statistical-modeling-of-time-series-data-part-1-data-preparation-and-preprocessing-b52f26f6213c">Statistical Modeling of Time Series Data Part 1 : Data Preparation and Preprocessing</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>