<?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 Dery Kurniawan on Medium]]></title>
        <description><![CDATA[Stories by Dery Kurniawan on Medium]]></description>
        <link>https://medium.com/@dkurniawan1395?source=rss-7a46de682dc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*GArSCi9AFPv1GWcMXafp1A.jpeg</url>
            <title>Stories by Dery Kurniawan on Medium</title>
            <link>https://medium.com/@dkurniawan1395?source=rss-7a46de682dc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:46:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dkurniawan1395/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[Stock Portfolio Optimizing using R]]></title>
            <link>https://medium.com/@dkurniawan1395/stock-portfolio-optimizing-using-r-76ed1291f7bc?source=rss-7a46de682dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/76ed1291f7bc</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Dery Kurniawan]]></dc:creator>
            <pubDate>Thu, 03 Sep 2020 00:37:17 GMT</pubDate>
            <atom:updated>2020-09-04T06:34:42.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stock Portfolio Optimization using R</h3><h4>Case study on how to optimize your stock portfolio using PortfolioAnalytics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ruw7SUGGb4nFxFy-FfwipQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chris Liverani</a> on <a href="https://unsplash.com/s/photos/stock-calculation?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Previously, we had analyzed how to measure stock portfolio performance using R (you can find it <a href="https://towardsdatascience.com/how-to-measure-stock-portfolio-performance-using-r-847c992195c2">here</a>). For now, we are going to try to optimize our stock portfolio by using PortfolioAnalytics package.</p><p><strong>A Stock Portfolio</strong> is a collection of stocks that we have as our investment asset. An investor usually will diversify their stock portfolio by allocating investments into various industries and categories. It should be done by every investor to reduce their investment risk in case one of the sectors is struggling.</p><p>Apart from diversifying their portfolio, one of the essential things that should be done by the investor is how to determine their portfolio weight.<strong> Portfolio Weight </strong>is the percentage of each stock that has been held by the investor.</p><p>By assuming we already have our choices on which stock will be included in our portfolio, there are several methods to determine the portfolio weight for each stock:</p><ol><li><strong>Equal Weight: </strong>type of weighting that gives the same weight to each stock in a portfolio. (ex: 10 Stocks in a portfolio with 10% weight for each stock)</li><li><strong>Risk-Based Weight: </strong>type of weighting that allocates the weight based on the stock risk, and it will differ from one person to another based on their risk profile. (ex: 80% on blue-chip stock, 20% on small-cap stock for low risk portfolio)</li><li><strong>Market-Cap Weight:</strong> type of weighting that gives a higher percentage on the stock with more significant market value and a lower share for stock with lower market value.</li><li>There are still many more methods available to use for portfolio weighting, and it will differ from one investor to another, depending on their investment strategy.</li></ol><p>In this article, we will calculate the portfolio weight automatically using <strong>portfolio.spec()</strong> function and aims to maximize return (mean return) and minimize risk (return standard deviation) based on its historical return data.</p><h4>Step by Step To Build Portfolio Specification Function</h4><p>For our case, we will use an example from Indonesia stock market and assume our portfolio consist of six stocks (<em>MTDL.JK</em>, <em>MYOR.JK</em>,<em> PWON.JK</em>, <em>CEKA.JK</em>, <em>UNVR.JK</em>, <em>TLKM.JK</em>)</p><ol><li>Import stock price and calculate the return for each stock for a certain period (We will use historical data from 2013 until 2019) and put it in the same xts object.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1993244f474551915e1c66235c65530/href">https://medium.com/media/f1993244f474551915e1c66235c65530/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*YeKqAQA9FlrYqAYT1p_PRQ.png" /><figcaption>Fig-1. Return of Each Stock in Single XTS Object</figcaption></figure><p>2. Build portfolio specifications using a <strong>portfolio.spec() </strong>function. In this step, we should add our stock name that has been store in our xts object.</p><p>3. Add portfolio objective in portfolio specification using <strong>add.objective() </strong>function. We will add two objectives for our portfolio, maximize mean returns, and minimize standard deviation.</p><p>4. Add portfolio constraint in portfolio specification using <strong>add.constraint()</strong> function. We will put two constraints for our portfolio,</p><ul><li><strong>Full Investment:</strong> Total weight for our portfolio should be 100%</li><li><strong>Box:</strong> To set manually range of minimum and maximum weight for each asset that we hold</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*MkIixuHRgEYvfMiWAVIBew.png" /><figcaption>Fig-2. Portfolio Specification that has been made</figcaption></figure><p>5. Optimize your portfolio with a portfolio specification that has been made using <strong>optimize.portfolio()</strong> function</p><p>6. Extract optimized weight using <strong>extractWeights() </strong>function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*gpD2tXTr3IBKIxVJdoGn6Q.png" /><figcaption>Fig-3. Optimized Weight for Our Portfolio</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a249768f4d0e6a07ed20c84c205f91fa/href">https://medium.com/media/a249768f4d0e6a07ed20c84c205f91fa/href</a></iframe><p>Using <strong>optimize.portfolio()</strong> function, we generate optimized weight based on the specification we made before. We will try to compare the performance from this weight-optimized portfolio with the performance from an equal-weight portfolio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCHuvnzg1WtCtE--A6p6xA.png" /><figcaption>Fig-4. Performance Comparison between Optimized and Equal Weight Portfolio</figcaption></figure><p>Assuming the portfolio has been used in 2020, it is clearly showing that our optimized-weight portfolio performs better compared to the equally-weighted portfolio.</p><blockquote>There’s a common rule used by most of the investor in the world. The rule said, <strong>“do not put all your eggs in one basket.” </strong>But, determine how many eggs in each basket will take you to another level of satisfaction if you’re doing it well.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76ed1291f7bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RFM Clustering on Credit Card Customers]]></title>
            <link>https://medium.com/data-science/rfm-clustering-on-credit-card-customers-cdec560281c0?source=rss-7a46de682dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdec560281c0</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[rfm-analytics]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <dc:creator><![CDATA[Dery Kurniawan]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 15:05:22 GMT</pubDate>
            <atom:updated>2020-08-13T15:05:22.605Z</atom:updated>
            <content:encoded><![CDATA[<h4>Case study of K-Means clustering on Recency, Frequency, and Monetary values (RFM) of customer’s credit card transaction data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mm72L9gpOS06xupykITFRg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@adeolueletu?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Adeolu Eletu</a> on <a href="https://unsplash.com/s/photos/marketing-analytics?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote><strong>Recency, Frequency, &amp; Monetary (RFM)</strong> is one of the techniques that can be used for customer segmentation and is one of the conventional ways for segmentation that been used for a long time.</blockquote><ol><li><strong>Recency</strong> refers to <em>when the customer did the most recent transaction using our product</em></li><li><strong>Frequency </strong>refers to <em>how often customers do transactions using our product</em></li><li><strong>Monetary Value </strong>refers to <em>how much does a customer spend in our product</em></li></ol><p><strong>RFM </strong>method is straightforward; we only have to transform our data (usually in the shape of transactional data) into data frame consists with three variables <strong><em>Recent Transaction, Transaction Frequency,</em> </strong>and <strong><em>Transaction Amount (Monetary Values).</em></strong></p><p>Transactional data itself is the data which records or captures every transaction that been done by customers. Typically, transactional data consists of transaction time, transaction location, how much amount our customers spend, which merchant the deal took place, and every detail that can be recorded at the moment transactions were made.</p><p>Let see our transactional dataset that later will be used as our study case. Our dataset is a 2016 credit card transactional data from every customer. Transactions dataset consist of 24 features which recorded during every transaction our customers made. Even if we have many features on our dataset; we will not use all of them and only use small numbers of features which can be transformed into <strong><em>Recency, Frequency, </em></strong>and <strong><em>Monetary Values </em></strong>instead.</p><p>Link to dataset: <a href="https://www.kaggle.com/derykurniawan/credit-card-transaction">https://www.kaggle.com/derykurniawan/credit-card-transaction</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*Wvxcwv2yBUtynyrFjNHHxw.png" /><figcaption>Fig-1. Transactional Data Features</figcaption></figure><p>If we return to our description of <strong>RFM</strong> features; we only have to keep <em>customerId, transactionDate, </em>and <em>transactionAmount </em>to create <strong>Recency, Frequency,</strong> and <strong>Transaction Amount </strong>features in the new data frame that grouped by <em>customerId </em>features.</p><p>For the <strong><em>Recency </em></strong>feature, we can subtract the current date with the maximum value of transactionDate (latest transaction). Since our dataset only contains 2016 transactional data, we will set 1st January 2017 as our current date.</p><p>For the <strong><em>Frequency </em></strong>feature, we count how many transactions were made for every customer using <strong>n()</strong> function in R.</p><p>for the <strong>Transaction Amount </strong>feature, we calculate the summation of transactionAmount for every customer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6852425b3972438c852c506ec32d2705/href">https://medium.com/media/6852425b3972438c852c506ec32d2705/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*mhaLaU1ky3DCgFGWddq6Pw.png" /><figcaption>Fig-2. First six rows of RFM Dataset</figcaption></figure><p>Now we have three main feature for the RFM segmentation. It is similar to any other data analytical case, the first step that we have to do is exploring our dataset, and in this case, we will check every feature distribution using histogram plot using <strong>hist() </strong>function in R.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpsgGFqXHvwbMLXLPkWfeA.png" /><figcaption>Fig-3 Histogram of RFM Features Data</figcaption></figure><p>Our RFM dataset is so right-skewed, and it will be a catastrophic problem in K-Means clustering method since this method using the distance between points as one of its calculation to determine which cluster is the points fitted the most. <strong>Log transformation</strong> can be used to handle this kind of skewed data, and since we have <strong>0 </strong>(zero values) in the data, we will use log(n + 1) to transform our data instead of the ordinary log transformation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700d3e85996b326f2c511ddbfa7ba035/href">https://medium.com/media/700d3e85996b326f2c511ddbfa7ba035/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xaoRSC0mO7wmuZCGDWmXkQ.png" /><figcaption>Fig-4. Histogram of RFM Features Data — Logarithmic Scale</figcaption></figure><p>Logarithmic transformation provides better data for K-Means method to calculate and find the best cluster for our data by getting rid much of skewed data in our RFM dataset.</p><h4>K-Means Clustering</h4><p>K-Means clustering method by definition is a type of unsupervised learning which been used for defining the unlabeled data into groups based on its similarity.</p><p>In R, K-Means clustering can be quickly done using <strong>kmeans() </strong>function. But, we have to find the number of clusters before creating the K-Means model. There are so many ways to find the best number of groups to assign, one of them is by using our business sense and assign the number directly, or we also can use mathematical sense to calculate the similarity between each point.</p><p>On this example, we will use the within-cluster sum of squares that measures the variability of the observations within each cluster. We will iteratively calculate the within-cluster sum of squares for every cluster in range of 1 to 10 and choose the group with the lowest value and no further significant changes in value for its next cluster, or often we called it as the <strong><em>Elbow Method</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb846522703975a6e86a1e5034744832/href">https://medium.com/media/fb846522703975a6e86a1e5034744832/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCM4Q84MkkEQXAWbQgqZlg.png" /><figcaption>Fig-5 Dataset Elbow Method Visualization (N = 4)</figcaption></figure><p>Using the elbow method, we will assign <strong>four groups </strong>as our number of clusters. Using <strong>kmeans()</strong> function in R we only need to put cluster number in <strong>centers </strong>parameter and assign the clustering results into our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb15d7b867a1600b59f91003a7c54771/href">https://medium.com/media/eb15d7b867a1600b59f91003a7c54771/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*n-IomECV1sgAD6O6H4G_1g.png" /><figcaption>Fig-6. Dataset after Segment Addition</figcaption></figure><p>We now have assigned every Customer ID into their groups in the segment feature. For the next step, we will check the basic <strong>RFM</strong> profile from every segment by grouping the average value of <strong>RFM</strong> features based on its segment number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*ED4oXu32tGin1KQg5Q8hew.png" /><figcaption>Fig-7. RFM Summary per Segment</figcaption></figure><p>So, we have four groups and let’s discuss the detail for every group:</p><ol><li><strong>Segment-1 (Silver): </strong>Middle-class customer with second-most considerable transactions frequency and spending amount.</li><li><strong>Segment-2 (Gold):</strong> Most valuable customers who have the most significant spending amount and the one who make transactions the most</li><li><strong>Segment-3 (Bronze): </strong>Commoner customer with low transactions frequency and low spending amount. But, this segment has the largest number of the customer.</li><li><strong>Segment-4 (Inactive): </strong>Inactive/less-active customers whom latest transactions had done in more than a month ago. This segment has the lowest number of customer, transaction frequency, and transaction amount.</li></ol><p>Now, we have four groups of customer with detailed <strong>RFM</strong> behaviour from each group. Usually this information can be used for arrange marketing strategy that well-targeted to the customers who share similar behaviour. <strong><em>Recency, Frequency, </em></strong>and <strong><em>Monetary Values</em></strong><em> </em>segmentation is simple but useful for knowing your customer better and aiming an efficient and optimum marketing strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdec560281c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/rfm-clustering-on-credit-card-customers-cdec560281c0">RFM Clustering on Credit Card Customers</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Measure Stock Portfolio Performance using R]]></title>
            <link>https://medium.com/data-science/how-to-measure-stock-portfolio-performance-using-r-847c992195c2?source=rss-7a46de682dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/847c992195c2</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Dery Kurniawan]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 15:51:39 GMT</pubDate>
            <atom:updated>2020-07-29T04:21:30.049Z</atom:updated>
            <content:encoded><![CDATA[<h4>Case study on how to do portfolio analysis using Indonesia stock market data in R</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWKTDXElpzLDMMnFLdn4Zw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chris Liverani</a> on <a href="https://unsplash.com/s/photos/stock?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>Stock market is a place where people arrange a transaction for buying or selling shares of publicly listed company</blockquote><p>Indonesia has been named as the <strong><em>Largest Economy in Southeast Asia</em></strong> by the World Bank. As one of the four most populous countries in the world with more than 200 million people living in this country, Indonesia has a bargaining power to emerge as one of the biggest economies in the world. Those promising prospect of Indonesia economic condition makes this country as one of the best choices to put your investment on.</p><p>Indonesia stock markets with more than 600 listed enterprises still on the uptrends before the coronavirus outbreak. Some of the listed enterprises are state-owned enterprises and for this case study, I will only analyze 17 state-owned enterprises which been a member of the latest IDX-BUMN20 Index.</p><p><strong>Stock used for analysis:</strong></p><p>ANTM.JK, BBNI.JK, BBRI.JK, BBTN.JK, BJBR.JK, BMRI.JK, ELSA.JK, JSMR.JK, KAEF.JK, PGAS.JK, PTBA.JK, PTPP.JK, SMGR.JK, TINS.JK, TLKM.JK, WIKA.JK, WSKT.JK</p><p>The assumption for this case study:</p><ol><li>Stocks weight in the portfolio is the same for every enterprise.</li><li>Analysis based on the historical adjusted closing price data from 1st January 2013 to 26th July 2020.</li><li>Risk-Free Rate: 4.5%</li><li>Portfolio rebalancing quarterly</li></ol><h4>Import and Prepare Stocks Data</h4><p>We will import stock price data using <strong>getSymbols() </strong>function from the<strong> quantmod</strong> package. <strong>getSymbols()</strong> function is a particular function to load and manage financial data from various sources, but for this example, we will use <em>Yahoo Finance</em> as our data source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afc1340ac6d944b0739f1020f6bf46b/href">https://medium.com/media/2afc1340ac6d944b0739f1020f6bf46b/href</a></iframe><p>In default, we will have every stock price data assigned to their stock code as xts object (ex: ANTM.JK prices will be stored in ANTM.JK variable as xts object). To make it easier for analysis, we should gather all these separate data into a single xts object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab033ba1c5bdd4deff2ed98256bbf5e2/href">https://medium.com/media/ab033ba1c5bdd4deff2ed98256bbf5e2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*1YXgwzxD1VMUhan1N7G2VA.png" /><figcaption>Fig-1. Index xts object preview</figcaption></figure><h4>Portfolio Analytics</h4><p>We already made a portfolio, and it stored as single xts object in a variable named <strong>Index</strong>. The data that we store in this variable is still in closing price format for every market day, since most of the portfolio analytics method need to feed by <strong>return</strong> data, we have to calculate its Return first before taking a step into portfolio analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*ullZTSzsXgMivTu4M8Ah7w.png" /><figcaption>Fig-2. Return Calculation Formula</figcaption></figure><p>Fortunately, in R we don’t have to manually calculate every stock return day by day, we just need to call Return. calculate () function, and it will give us the return output in xts object format.</p><p>Since nobody can see the future, most of the stock market investor relies on two things before deciding which stock they will buy, first is fundamental analysis and second is technical analysis. <strong>Fundamental Analysis</strong> involves the use of economic and financial data (e.g., production, consumption, disposable income, etc.) to forecast prices in the future, whereas <strong>Technical Analysis </strong>is based primarily (and often solely) on the study of patterns in the price data itself [1]. This article will cover only some of the <strong>Technical Analysis</strong> methods available.</p><p>For the first analysis, we will try to look at every stock performance in term of their reward &amp; risk in annualized return, since Investors sometimes want to see if their investments are well-rewarded compared to its risk, and <strong>Sharpe Ratio</strong> is a great calculation that can measure it all. Higher Sharpe ratio means our investments are well-rewarded compared to the risk that we have during the investing period. For calculation, we assume Indonesia Risk-Free Rate is 4.5% yearly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80f21d3d8ace7bb796aee1ce5ca0dab5/href">https://medium.com/media/80f21d3d8ace7bb796aee1ce5ca0dab5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zITrXRpFvSUWmrwKDKp91A.png" /><figcaption>Fig-3. Sharpe Ratio for Every Stock in Portfolio</figcaption></figure><p><strong>Annualized</strong> means we recalculate the number in a certain period on a yearly basis, for example, the return of ANTM.JK is -5.35%/Year during the 2013–2020 periods. Our portfolio annualized performance show there are varies from one stock to the others. <strong>The worst performer</strong> in our portfolio is<em> PGAS.JK </em>which has a negative return and swing too much during the periods makes PGAS.JK Sharpe Ratio is the lowest among others. <strong>The best performer </strong>in our portfolio is <em>BBRI.JK</em> which shows the highest return, smallest standard deviation, and highest Sharpe Ratio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heJ9XdLgEiS4cTH3gUdpYg.png" /><figcaption>Fig-4. BBRI.JK vs PGAS.JK Adj.Close Price Chart</figcaption></figure><p>If we compare the line chart between the <em>best performer </em>and <em>the worst performer</em> stock in our portfolio, we can obviously see the differences between them. BBRI.JK has more consistent movement and steadily increase from year to year, in the opposite PGAS.JK movement fluctuates with a massive span between its peak and valley.</p><p>We can also make a general view about how our stock performance compared to Risk-Free rate Asset (4.5% annual return) using label plot in <strong>ggplot2 </strong>package<strong>.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aff464f2fa0dc8a04ef862230ab2135b/href">https://medium.com/media/aff464f2fa0dc8a04ef862230ab2135b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTZawUPgwyxwdNxJlgxsTQ.png" /><figcaption>Fig-5. Stocks Performance vs Risk-Free Rate Asset</figcaption></figure><p>If we see in the big picture, during this period, 10 companies are well-worthy to be invested for, that means if we put our investment into these stocks, we will gain much more than if we put our investments into the risk-free assets. Using this plot, we know how vital diversification is in investment, some of our investments will have a high return, but other investments are losing its value than when we buy it.</p><p>Now we will start to analyze those stocks as a portfolio and we will see how its performance if we hold all of those stocks in the same proportion from 2013 until July 2020.</p><p>First of all, we will look at our portfolio daily return distribution. Using this distribution, we will see how often our portfolio gives us a positive return and how frequent it is losing its value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/023005a2c7fd0db0eeb8ee4e220e224e/href">https://medium.com/media/023005a2c7fd0db0eeb8ee4e220e224e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipwOKAMSAWpWoz-8uGqhtw.png" /><figcaption>Fig-6. Portfolio Daily Return Distribution</figcaption></figure><p>The daily return distribution plot shows our portfolio averaging positive returns near zero with some time. It can give more than 10% return in a day, but on the other hand, it possible to lose more than 10% of its value just in a day. We will prove it using time-series daily return plot and find out when our portfolio losing so much and when it gains the highest return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kScIJG0u_KL_JGx50WD-Hw.png" /><figcaption>Fig-7. Time-Series Daily Return Plot</figcaption></figure><p>From the time-series plot, we can obviously see most of our return will be in the range of ±5%, even though there’s some outlier and the most recent is coming due to the coronavirus effect in the first half of 2020.</p><p>Using only daily return is not enough to display how well our portfolio performance. Luckily, there is <strong>charts.PerformanceSummary()</strong> function in R that will produce portfolio <em>cumulative return, daily return, and drawdown plot</em> as its output.</p><ol><li><em>Cumulative Return</em>: Time series plot that shows how much return we got from our portfolio.</li><li><em>Daily Return</em>: Time series plot that displays our portfolio daily return.</li><li><em>Drawdown</em>: Time series plot displays the distance between the peak and its bottom pit and how long the time is needed to regain its value</li></ol><pre><strong>charts.PerformanceSummary</strong>(Portfolio_Return, main = &#39;Portfolio Performance Summary&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ne0KhMnDncR0U6hOX72rgQ.png" /><figcaption>Fig-8. Portfolio Performance Summary Chart</figcaption></figure><p>Performance Summary Chart sums up every information we need in analyzing our portfolio performance during the periods. <strong>From the cumulative return chart,</strong> we know our portfolio will still have more than 100% return until the 26th of July despite the fact that some stocks have negative returns and coronavirus effects that mostly disrupt every stock market activity in the world. <strong>From the daily return chart,</strong> we will get information about which period our portfolio return fluctuated so much and using this information we can develop an insight about how the major events in certain period can disrupt stock market transaction and make a plan if there will be any other major events in the future. <strong>From the drawdown chart</strong>,<strong> </strong>we gain the knowledge about how our portfolio performs against downtrend and how long it can recover so we can have a proper strategy on how we hold the stocks if in the future downtrends are happen.</p><h4>Summary</h4><p>Technical analysis is about predicting the movement of the stock price using historical patterns and market statistics. This article has discussed how to use R-Computation to extract the pattern and gain insight into how our portfolio movement and performance during a certain period.</p><p>For future investment, we can use the analysis result as the basis for every action that we will take. As an example, we can subset this kind of analysis into a smaller period and revise our portfolio composition based on the shape ratio.</p><p>There’s also a method to find the optimum weight of our portfolio based on historical data. Hopefully, it can be discussed in the other articles.</p><blockquote><strong>Notes:</strong> We can reconstruct every code in this article for every stock and every period as long as the data is available in the data source. Just try to change it to your portfolio composition and see how your portfolio was doing in a certain period.</blockquote><p>[1] Schwarger, Jack.D., &amp; Etzkorn, M. (2017), <em>A Complete Guide to The Futures Market</em>, 2nd edition, John Wiley &amp; Sons, Inc., Hoboken, New Jersey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=847c992195c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-measure-stock-portfolio-performance-using-r-847c992195c2">How to Measure Stock Portfolio Performance using R</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Linear Regression for Manufacturing Analysis]]></title>
            <link>https://medium.com/data-science/multiple-linear-regression-for-manufacturing-analysis-c057d4af718b?source=rss-7a46de682dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c057d4af718b</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[toward]]></category>
            <category><![CDATA[manufacturing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[case-study]]></category>
            <dc:creator><![CDATA[Dery Kurniawan]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 08:14:50 GMT</pubDate>
            <atom:updated>2021-08-31T08:04:22.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_8jG79dp14x2sh47vGI9g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rozetsky?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ant Rozetsky</a> on <a href="https://unsplash.com/s/photos/industry?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Case study about how to find the most significant factor in the production process</h4><blockquote><strong>Regression </strong>is one of the mathematical approaches to measure the relationship between independent/predictor variables with their dependent/target variable.</blockquote><p>Regression widely used for at least two primary purposes. First, regression is often used as a prediction or forecasting tool. Second, in some events, a regression can be used as an analytical method in data analysis. In this article, we will use regression for its secondary purposes and get insight into how the regression model can be used to analyze past events instead of forecasting future events.</p><p><strong>Multiple Linear Regression</strong> is one of the most straightforward tools which can be used to analyze a dependent variable against several independent/predictor variables. This kind of regression is often used due to the reality of some process is not only built by one factor instead, but several other factors are also involved in every activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*39FkA9sgT6E_txFT_KANjw.png" /><figcaption>Fig-1. Multiple Linear Regression Formula</figcaption></figure><p>The linear regression formula’s <strong>slope</strong> can also be interpreted as the <em>linear relationship strength between the independent variable</em> <em>and its dependent variable</em>. Based on that definition, we can comfortably say that the higher the slope value of the independent variable, the more significant this variable influences its dependent variable.</p><p>That will be our basis to analyze and determine which factor is influenced the most in our case in the manufacturing Industry.</p><h4>Case Study:</h4><blockquote><em>Analyzing Raw Material Influence on Production Quality</em></blockquote><p>Case Definition:</p><p>Company “P” produces a product that needs to fulfil some quality requirements; one of the essential requirements is that it should have a <strong>defect value</strong> of less than 30. To produce this product, Company “P” uses three raw materials; <strong>Material-A, Material-B, and Material-C. </strong>The composition between those materials is <em>0-10 % A, 0-10% B, and 80-100% C</em>.</p><p>Based on the theoretical, defect value is always there due to the cleanliness of those raw materials. The only thing the company can do is suppress the defect value below the maximum limit.</p><p>In 2020, the defect value average per product is increased compared to 2019 and starts to approach our maximum limit (30) which is we don’t want to happen. The company is not sure which material is causing this issue. To answer that question, we will conduct a regression analysis to understand which material is the most responsible for this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JEsLrEIaUqKN5zrv3HYeMQ.png" /><figcaption>Fig-2. 2020 Defect Value Condition</figcaption></figure><h4>Data Preparation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2bdf8d3b045eefe5a4aa3a0d68495c7/href">https://medium.com/media/c2bdf8d3b045eefe5a4aa3a0d68495c7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*hp8PDkFUAoBQe7aEuJtmPQ.png" /><figcaption>Fig-2. Production Dataset</figcaption></figure><p>Features Explanation:</p><ol><li>Month: Period when the item is made</li><li>Production_No: Batch number of products</li><li>A, B, C: Raw materials input (Ton)</li><li>Defect_Value: Quality status, should be under 30</li></ol><p>Using this data, we will conduct regression calculation and find the slope for every material. The slope value will be recalculated as the weighted value by considering the raw material composition (10:10:80). This weighted value is used to find which material is the most responsible for the issue.</p><h4>Regression Modeling</h4><p>We will use the <strong>Multiple Linear Regression </strong>method and use below formula as our mathematic linear model :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*whF_ybPi6ddOMiI-UqCE4w.png" /><figcaption>Fig-3. Mathematic Model for Production Data</figcaption></figure><p>The differences between this case mathematic model with other regression model are we assume that <em>“there’s no other factor that influences Defect Value”, </em>that’s why we remove the intercept variable from our model and expecting defect value only from raw material.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4c304324640dc77f415b3555a0dc203/href">https://medium.com/media/a4c304324640dc77f415b3555a0dc203/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*L0qdbnUPLDM52HRl9pur_w.png" /><figcaption>Fig-4. Slope Regression Result</figcaption></figure><p>Those codes will return the slope for every time period, in this case, 2019 whole year and 2020 from January to May.</p><p>Since we need to recalculate those values into their weighted values, and also we expecting to get data frame to make it easier to visualize and analyze the results, to do so, we need to add below code and get the result as what we wanted to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b3f846dc06bb3566cfe221f2ad73a0b/href">https://medium.com/media/7b3f846dc06bb3566cfe221f2ad73a0b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*4Z9q8fQJzRvxRqonIOcG1g.png" /><figcaption>Fig-5. Result Data Frame</figcaption></figure><h4><strong>Visualization and Analysis</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0cc1b46415edf68ed1ab47b23636240/href">https://medium.com/media/d0cc1b46415edf68ed1ab47b23636240/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrcI26UktcNeP-MDZjt4TQ.png" /><figcaption>Fig-5. Weighted Slope Value Chart</figcaption></figure><p>So, which material has the most influence if we see the chart above? Based on the chart, it’s comfortable to say that Material-C influence to the Defect Value is vastly increased. Four from five Material-A weighted values in 2020 are higher than in 2019 with its peak laid in April 2020.</p><p>With that information, the company can prepare the countermeasure.</p><p>Some of the examples of this issue countermeasure are;</p><ol><li>Since the one which the most responsible is Material-C, the company can evaluate the quality of purchased Material-C in 2020.</li><li>Trying to reduce Material-C usage and substitute with increasing Material-B usage.</li><li>Tightly monitoring in Material-C quality before production starts.</li></ol><p>So that’s the end of this case study, this case is written based on the real problem in one of the manufacturing industry and the usage of regression to support decision making is also the real approach in solving the issue. Every person and every company can have their approach to find the solution to every problem, and that’s good as long as it can solve the issue. An approach using the regression slope is only from many methods to solve the industrial case in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c057d4af718b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/multiple-linear-regression-for-manufacturing-analysis-c057d4af718b">Multiple Linear Regression for Manufacturing Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecast Including External Information as Predictor]]></title>
            <link>https://medium.com/data-science/forecast-with-including-external-information-as-predictor-594eaae7a2b9?source=rss-7a46de682dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/594eaae7a2b9</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[indonesia]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[timeseries]]></category>
            <dc:creator><![CDATA[Dery Kurniawan]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 06:07:06 GMT</pubDate>
            <atom:updated>2020-07-02T02:58:14.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZutXrg23E8-5WroeJCwOwg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@vidarnm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Vidar Nordli-Mathisen</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Simple case study on how to use external information on forecasting method in R</h4><p>Forecasting is required in some situations: predicting supply and demands in an Industry, predicting product demand and labor needed in the production, predicting weather like rainfall, or many more cases can be solved using forecasting. The most used forecasting method is only using its historical data such as trend and seasonality while ignoring the remainder factor (information obtained from external source). However, it was not wrong but not wise enough if we are working with some data which have a high correlation with some external information. For example, the effects of the holiday season in the tourism industry, the inflation rate in the finance &amp; banking industry, competitor action, and many more conditions require external information to be considered.</p><p>While data science tools have grown significantly, it helps forecaster to simplify their works. We will take an example of using R to create a forecast, including external information, as part of its predictor.</p><p>Our dataset contains monthly information of Rainfall, Rainy days, Average Temperature in Bandung, Indonesia;</p><ol><li>Rainfall: in mm2, the quantity of rain falling within a given area in a given time</li><li>Raindays: Amount of days which rain occurred</li><li>Average Temperature</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9876cb79178101df5120db98f178f311/href">https://medium.com/media/9876cb79178101df5120db98f178f311/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*7NedJb2MU1TKkGmzw54-lg.png" /><figcaption>Fig-1. Head of Bandung Dataset</figcaption></figure><p>Bandung dataset contains time series information in the range of 2014 to 2019. As it should be done before conducting any analysis work, we need to have a clear goal that we want to solve, in this case, we will set our goal as for Predicts Rain days on 2020 Period. Using either both or one of Rainfalls or temperatures, we will try to create a simple forecasting method to reach our goal.</p><p><strong>Exploring Our Data</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a72952f569bc4e6e629931ad8276bb54/href">https://medium.com/media/a72952f569bc4e6e629931ad8276bb54/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-W-VL89WN4RQxIJxscQhwQ.png" /><figcaption>Fig-2. Decomposition Plot</figcaption></figure><p>The decomposition of the time series is one of the most powerful techniques to explore any information inside the data. Using this, we can calculate trend and seasonality strength and find the remainder pattern out of its trend and seasonality. <br>If we rule out external information, we will only make use of seasonality and trend patterns to be analyzed and considers the remainder component as an error. The difference when we use external information as our predictor is we can explain the remainder components’ variations using our external information, or in simple terms, remainder components composed by our external information.<br>So, how to determine which information we should use as our external predictor? The most useful but straightforward way is to check its correlation with our target variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*8RuH_b_4D7xuWqf8kf8-DA.png" /><figcaption>Fig-3. Correlation Table</figcaption></figure><p>Rainfalls is the one that has a moderate correlation with raindays. We will make use of this variable as our external predictor. But, let’s take a peek at the curve between those variables at first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjh1bP1d4X44jhvu-mbVcQ.png" /><figcaption>Fig-4. Rainfalls and Raindays Time Series Plot</figcaption></figure><p>At a glance on this simple plot, we can see raindays (bottom) and rainfalls (top) share even not precisely due to but still similar movement due to their correlation during the periods.</p><p><strong>Time Series Forecasting</strong></p><p>Auto Arima function in R makes forecasting even easier than how its look. But to includes external information on our model, we must specify the <strong>xreg</strong> argument with our predictor (external information). In the end, <strong>auto.arima()</strong> will take the rest of the calculation and find the best model for us.</p><pre>#Creating Model<br>fit &lt;- auto.arima(Bandung[,2], xreg=Bandung[,1], stepwise = FALSE,<br>                  approximation = FALSE, biasadj= TRUE)</pre><pre><strong>#Summary of Our Model</strong></pre><pre><strong>Series: Bandung[, 2] <br>Regression with ARIMA(5,1,0) errors <br><br>Coefficients:<br>          ar1      ar2      ar3      ar4      ar5    xreg<br>      -0.8445  -0.7907  -0.8163  -0.7130  -0.7036  0.0269<br>s.e.   0.0911   0.1081   0.1003   0.1038   0.0847  0.0049<br><br>sigma^2 estimated as 25.51:  log likelihood=-214.8<br>AIC=443.59   AICc=445.37   BIC=459.43</strong></pre><pre>#Check Residuals<br>checkresiduals(fit)</pre><pre><strong>Ljung-Box test<br><br>data:  Residuals from Regression with ARIMA(5,1,0) errors<br>Q* = 7.0153, df = 8, p-value = 0.535<br><br>Model df: 6.   Total lags used: 14</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wvnk3tK6E01V09nlpOTt8g.png" /><figcaption>Fig-5. Residuals Check on Fit Model</figcaption></figure><p><strong>auto.arima()</strong> choose non-seasonal ARIMA model with 5-order of Auto-regressive and one differencing, with errors is implicated as our <strong>xreg </strong>(external predictor). If we see the details of our model, the xreg component was not so impactful for the calculation compared to the 5-order of AR. But we will go on since it is an only simple tutorial using a simple dataset. For another dataset, external prediction can be more impactful on the model calculation.</p><p>Residuals check which been done shows the residuals are uncorrelated between each other and it means our model is good to use.</p><p>To forecast using a model with external information, we need to obtain future values of our external information. This step has a different treatment for different datasets. If we can straightforward predict its future values based on expertise, we can directly use it. But, if we can’t instantly predict its future values, we can make a separate model and forecast its future value on the same horizon with our main forecasting target. For our case, we will use auto.arima() to build another model and forecast its future value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f968870ed0b8c0d5df91c60ce8d69b7c/href">https://medium.com/media/f968870ed0b8c0d5df91c60ce8d69b7c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*MfIms7y97z04NWY1HOGa2Q.png" /><figcaption>Fig-6. Predictor Forecast for Next 12-Months</figcaption></figure><p>With external predictor values which been known, we finally can conduct a forecast for 2020 Raindays and visualize its result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*FZreWJNVhG0Oe0WbFTDY-g.png" /><figcaption>Fig-7. Raindays Forecast for Next 12-Months</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQHf7ZYoIRY_G-xt5jZFeg.png" /><figcaption>Fig-8. Bandung Raindays Forecast 2020</figcaption></figure><p>Our forecast show there will be two months (June and December) in 2020, which has the lowest rainy days in a month, and the highest rainy days amount occurs in March and September.</p><p>So, that’s how we do forecasting with includes external information as one of the regressors in the model. In more detail, we can also compare the forecast only using trend and seasonality with the forecast which utilize external information and find which model is better. However, whichever method you choose, that’s not wrong, since the different data need different treatment.</p><p>For disclaimer, this article only discusses how to include external regressors on our time series model, so in a real case of predicting rainy days, I suggest consulting with climate experts and finding another variable that correlates with how rainy days occurred.</p><p>You can find the dataset on this <a href="https://www.kaggle.com/derykurniawan/bandungrainfall">link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=594eaae7a2b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/forecast-with-including-external-information-as-predictor-594eaae7a2b9">Forecast Including External Information as Predictor</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rainfall Time Series Analysis and Forecasting]]></title>
            <link>https://medium.com/data-science/rainfall-time-series-analysis-and-forecasting-87a29316494e?source=rss-7a46de682dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a29316494e</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[indonesia]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Dery Kurniawan]]></dc:creator>
            <pubDate>Sun, 17 May 2020 10:45:50 GMT</pubDate>
            <atom:updated>2020-05-18T17:12:20.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3owW2Ev_DtnLFb9v4DgRg.jpeg" /><figcaption>Photo by SHAH Shah on Unsplash</figcaption></figure><h4>Banten, Indonesia 2019–2020 Rainfall forecasting using “R” Language</h4><p>A forecast is calculation or estimation of future events, especially for financial trends or coming weather. Until this year, forecasting was very helpful as a foundation to create any action or policy before facing any events. As an example, in the tropics region which several countries only had two seasons in a year (dry season and rainy season), many countries especially country which relies so much on agricultural commodities will need to forecast rainfall in term to decide the best time to start planting their products and maximizing their harvest. Another example is forecast can be used for a company to predict raw material prices movements and arrange the best strategy to maximize profit from it.</p><p>In this article, we will try to do Rainfall forecasting in Banten Province located in Indonesia (One of the tropical country which relies on their agriculture commodity), we have 2006–2018 historical rainfall data¹ and will try to forecast using “R” Language.</p><p>A simple workflow will be used during this process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*SUmV8YmybekPDX1U74grNw.png" /><figcaption>Fig-1. Process Workflow</figcaption></figure><h3>Import and Selecting Data</h3><p>This data set contains Banten Province, Indonesia, rainfall historical data from January 2005 until December 2018. For this forecast, I will drop 2005 and start from 2006–2018 as a foundation for our forecast.</p><pre>#Import Necessary Library<br>library(lubridate)<br>library(ggplot2)<br>library(tidyverse)<br>library(dplyr)<br>library(astsa)<br>library(forecast)<br>library(readxl)<br>library(urca)<br>library(ggfortify)<br>library(tsutils)<br><br>#Import Data<br>hujan &lt;- read_excel(&quot;../input/hujan-update/Hujan_Update.xlsx&quot;, <br> sheet = &#39;Sheet1&#39;)<br>hujan &lt;- hujan %&gt;% gather(key = &quot;Tahun&quot;, value = &quot;Curah_Hujan&quot;, <br> -Bulan)</pre><pre><em>#Converting To Time Series<br></em>hujan_ts &lt;- ts(data = hujan[,3], frequency = 12, start = c(2005,1))<br><em>#Selecting Data</em> <br>hujan_ts &lt;- window(hujan_ts, start=c(2006,1))</pre><pre>hujan_ts</pre><p>After running those code, we will get this following time series data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*cAC8USUYKdwP4muvhDSh7A.png" /><figcaption>Fig-2. Time Series Rainfall Data</figcaption></figure><h3>Exploratory Time Series Data Analysis</h3><p>The first step on exploratory data analysis for any time series data is to visualize the value against the time. We will visualize our rainfall data into time series plot (Line chart, values against time) with this following code:</p><pre>#Plot Time Series Data</pre><pre>autoplot(hujan_ts) + ylab(&quot;Rainfall (mm2)&quot;) + xlab(&quot;Datetime&quot;) + <br>  scale_x_date(date_labels = &#39;%b - %Y&#39;, breaks = &#39;1 year&#39;, minor_breaks = &#39;2 month&#39;) +<br>  theme_bw() + ggtitle(&quot;Banten Rainfall 2006 - 2018&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmctduYday63Alebk452UA.png" /><figcaption>Fig-3. Banten Rainfall Time Series Plot</figcaption></figure><p>Time series plot visualizes that rainfall has seasonality pattern without any trends occurred; rainfall will reach its higher value at the end of the years until January <strong>(Rainy Season)</strong> and decreased start from March to August <strong>(Dry Season)</strong>. This pattern will always be repeated from year to year during 2006–2018 periods.</p><p>We will decompose our time series data into more detail based on Trend, Seasonality, and Remainder component. Using this decomposition result, we hope to gain more precise insight into rainfall behavior during 2006–2018 periods.</p><p>Decomposition will be done using <strong>stl()</strong> function and will automatically divide the time series into three components (Trend, Seasonality, Remainder).</p><pre>#Decomposition using stl()<br>decomp &lt;- stl(hujan_ts[,1], s.window = &#39;periodic&#39;)</pre><pre>#Plot decomposition<br>autoplot(decomp) + theme_bw() + scale_x_date(date_labels = &#39;%b - %Y&#39;, breaks = &#39;1 year&#39;, minor_breaks = &#39;2 month&#39;) +<br>    ggtitle(&quot;Remainder&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HM_aM-Hohd5hf7LcjGgvfA.png" /><figcaption>Fig-4. Time series decomposition</figcaption></figure><p>The trend cycle and the seasonal plot shows there’s seasonal fluctuation occurred with no specific trend and fairly random remainder/residual.</p><p>There’s a calculation to measure trend and seasonality strength:</p><p><strong>Ft</strong>: Trend Strength</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*QbFk5AUfkI5nLCvzQufQBw.png" /><figcaption>Fig-5. Trend Strength Formula²</figcaption></figure><p><strong>Fs</strong>: Seasonal Strength</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*kEgMxMv_Vax4FGcilmLx4w.png" /><figcaption>Fig-6. Seasonal Strength Formula²</figcaption></figure><p>The strength of the trend and seasonal measured between 0 and 1, while <strong>“1”</strong> means there’s very strong of trend and seasonal occurred.</p><pre>Tt &lt;- trendcycle(decomp)<br>St &lt;- seasonal(decomp)<br>Rt &lt;- remainder(decomp)</pre><pre>#Trend Strength Calculation<br>Ft &lt;- round(max(0,1 - (var(Rt)/var(Tt + Rt))),1)</pre><pre>#Seasonal Strength Calculation<br>Fs &lt;- round(max(0,1 - (var(Rt)/var(St + Rt))),1)<br><br>data.frame(&#39;Trend Strength&#39; = Ft , &#39;Seasonal Strength&#39; = Fs)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*j3qo0YvSxGqAvbvmtFpTQg.png" /><figcaption>Fig-7. Trend/Seasonal Strength Calculation Result</figcaption></figure><p>By using the formula for measuring both trend and seasonal strength, we’re proving that our data has a seasonality pattern (Seasonal strength: 0.6) with no trend occurred (Trend Strength: 0.2).</p><p><strong>Seasonality Analysis</strong></p><p>We know that our data has a seasonality pattern. So, to explore more about our rainfall data seasonality; seasonal plot, seasonal-subseries plot, and seasonal boxplot will provide a much more insightful explanation about our data.</p><pre>#Seasonal Plot<br>seasonplot(hujan_ts, year.labels = TRUE, col = 1:13, <br>   main =  &quot;Seasonal Plot&quot;, ylab= &quot;Rainfall (mm2)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2udefa1HjjSm9p3SRx7a6A.png" /><figcaption>Fig-8. Rainfall Time Series Seasonal Plot</figcaption></figure><p>Seasonal plot indeed shows a seasonal pattern that occurred each year. Still, due to variances on several years during the period, we can’t see the pattern with only using this plot. Further exploration will use Seasonal Boxplot and Subseries plot to gain more in-depth analysis and insight from our data.</p><pre>#Seasonal Sub-Series Plot<br>seasplot(hujan_ts, outplot = 3, trend = FALSE, <br>      main = &quot;Seasonal Subseries Plot&quot;, ylab= &quot;Rainfall (mm2)&quot;)</pre><pre>#Seasonal Boxplot<br>seasplot(hujan_ts, outplot = 2, trend = FALSE, <br>     main = &quot;Seasonal Box Plot&quot;, ylab= &quot;Rainfall (mm2)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0zkVOzKJ4Qeq1BXw1nPOA.png" /><figcaption>Fig-9. Seasonal Sub-Series Plot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jgt--968mSXtdSZl0BKXw.png" /><figcaption>Fig-10. Seasonal Boxplot</figcaption></figure><p>Using seasonal boxplot and sub-series plot, we can more clearly see the data pattern. The horizontal lines indicate rainfall value means grouped by month, with using this information we’ve got the insight that Rainfall will start to decrease from April and reach its lowest point in August and September. Rainfall will begin to climb again after September and reach its peak in January.</p><p>With this, we can assign Dry Season on April-September period and Rainy Season on October-March. It can be a beneficial insight for the country which relies on agriculture commodity like Indonesia. Dry and Rainy season prediction can be used to determine the right time to start planting agriculture commodities and maximize its output.</p><p>Also, this information can help the government to prepare any policy as a prevention method against a flood that occurred due to heavy rain on the rainy season or against drought on dry season.</p><h3>2019–2020 Rainfall Forecasting</h3><p>The first step in forecasting is to choose the right model. To do so, we need to split our time series data set into the train and test set. The train set will be used to train several models, and further, this model should be tested on the test set.</p><p><strong>Split Train/Test Set</strong></p><p><strong>Train set:</strong> We will use all of the data until December-2017 as our training set</p><p><strong>Test set:</strong> 2018 Period (January-December) will act as our test set</p><pre><em>#Create Train Set</em><br>hujan_train &lt;- window(hujan_ts, end = c(2017,12))</pre><pre><em>#Create Test Set</em> <br>hujan_test &lt;- window(hujan_ts, start = c(2018,1))</pre><p><strong>Stationary Test</strong></p><p>Train set data should be checked about its stationary before starting to build an ARIMA model. A stationary test can be done using <strong><em>Kwiatkowski–Phillips–Schmidt–Shin Test (KPSS)</em></strong> and <strong><em>Dickey-Fuller Test (D-F Test) </em></strong>from URCA package.</p><pre><em>#Kwiatkowski–Phillips–Schmidt–Shin Test</em><br>summary(ur.kpss(hujan_train)) </pre><pre><em>#Dickey-Fuller Test<br></em>summary(ur.df(hujan_train)) </pre><pre>####################### <br># KPSS Unit Root Test # <br>####################### <br><br>Test is of type: mu with 4 lags. <br><br>Value of test-statistic is: 0.0531 <br><br>Critical value for a significance level of: <br>                10pct  5pct 2.5pct  1pct<br>critical values 0.347 0.463  0.574 0.739</pre><pre>############################################### <br># Augmented Dickey-Fuller Test Unit Root Test # <br>############################################### <br><br>Test regression none <br><br><br>Call:<br>lm(formula = z.diff ~ z.lag.1 - 1 + z.diff.lag)<br><br>Residuals:<br>    Min      1Q  Median      3Q     Max <br>-176.15  -43.66    3.80   68.21  355.75 <br><br>Coefficients:<br>           Estimate Std. Error t value Pr(&gt;|t|)    <br>z.lag.1    -0.15081    0.05230  -2.883 0.004555 ** <br>z.diff.lag -0.28241    0.08111  -3.482 0.000664 ***<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Residual standard error: 96.77 on 140 degrees of freedom<br>Multiple R-squared:  0.1755,	Adjusted R-squared:  0.1637 <br>F-statistic:  14.9 on 2 and 140 DF,  p-value: 1.36e-06<br><br><br>Value of test-statistic is: -2.8835 <br><br>Critical values for test statistics: <br>      1pct  5pct 10pct<br>tau1 -2.58 -1.95 -1.62</pre><p>Using 95% as confidence level, the null hypothesis (ho) for both of test defined as:</p><ul><li><strong>KPSS Test:</strong> Data are stationary</li><li><strong>D-F Test:</strong> Data are non-stationary</li></ul><p>So, for KPSS Test we want p-value &gt; 0.5 which we can accept null hypothesis and for D-F Test we want p-value &lt; 0.05 to reject its null hypothesis. Based on the test which been done before, <strong>we can comfortably say that our training data is stationary</strong>.</p><p><strong>Model Assignment</strong></p><p>Forecasting will be done using both of ARIMA and ETS model, the comparison between those models also will be evaluated using some parameters against the test set.</p><p><strong>ARIMA Model</strong></p><p>The first step in building the ARIMA model is to create an autocorrelation plot on stationary time series data. Sometimes to have stationary data, we need to do differencing; for our case, we already have a stationary set. Therefore the number of differences (d, D) on our model can be set as <strong>zero</strong>.</p><p>Our dataset has seasonality, so we need to build <strong>ARIMA (p,d,q)(P, D, Q)m</strong>, to get (p, P,q, Q) we will see autocorrelation plot (ACF/PACF) and derived those parameters from the plot.</p><pre>acf2(hujan_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNIlmFKX9bLMLx0G4kJslQ.png" /><figcaption>Fig-11. ACF/PACF Plot Train Set</figcaption></figure><p>ACF Plot is used to get MA parameter (q, Q), there’s a significant spike at lag 2 and the sinusoidal curve indicates annual seasonality (m = 12). PACF Plot is used to get AR parameter (p, P), there’s a significant spike at lag 1 for AR parameter.</p><p>This ACF/PACF plot suggests that the appropriate model might be <strong>ARIMA(1,0,2)(1,0,2)</strong>. To make sure about this model, we will set other model based on our suggestion with modifying <strong>(AR)</strong> and <strong>(MA)</strong> component by <strong>±1</strong>.</p><ol><li>Model-1 : <strong>ARIMA(1,0,2)(1,0,2)</strong></li><li>Model-2 : <strong>ARIMA(2,0,2)(2,0,2)</strong></li><li>Model-3 : <strong>ARIMA(1,0,1)(1,0,1)</strong></li><li>Model-4 : <strong>ARIMA(2,0,1)(2,0,1)</strong></li><li>Model-5 : <strong>ARIMA(0,0,2)(0,0,2)</strong></li><li>Model-6 : auto.arima()</li></ol><p>we will also set <strong>auto.arima()</strong> as another comparison for our model and expecting to find a better fit for our time series.</p><pre>fit1 &lt;- Arima(hujan_train, order = c(1,0,2), seasonal = c(1,0,2))<br>fit2 &lt;- Arima(hujan_train, order = c(2,0,2), seasonal = c(2,0,2))<br>fit3 &lt;- Arima(hujan_train, order = c(1,0,1), seasonal = c(1,0,1))<br>fit4 &lt;- Arima(hujan_train, order = c(2,0,1), seasonal = c(2,0,1))<br>fit5 &lt;- Arima(hujan_train, order = c(0,0,2), seasonal = c(0,0,2))<br>fit6 &lt;- auto.arima(hujan_train, stepwise = FALSE, <br>        approximation = FALSE)</pre><p>To choose the best fit among all of the ARIMA models for our data, we will compare AICc value between those models. The model with minimum AICc often is the best model for forecasting.</p><pre>data.frame(&#39;Model-1&#39; = fit1$aicc, &#39;Model-2&#39; = fit2$aicc, <br>     &#39;Model-3&#39; = fit3$aicc,<br>     &#39;Model-4&#39; = fit4$aicc, <br>     &#39;Model-5&#39; =  fit5$aicc,&#39;Auto.Arima&#39;= fit6$aicc,<br>      row.names =   &quot;AICc Value&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*lQHd6DquDD2ULq1OzurF6Q.png" /><figcaption>Fig-12. AICc Value on ARIMA Model</figcaption></figure><p>AICc value of Model-1 is the lowest among other models, that’s why we will choose this model as our ARIMA model for forecasting. But, we also need to have residuals checked for this model to make sure this model will be appropriate for our time series forecasting.</p><pre>checkresiduals(fit1)</pre><pre>	Ljung-Box test<br><br>data:  Residuals from ARIMA(1,0,2)(1,0,2)[12] with non-zero mean<br>Q* = 10.187, df = 17, p-value = 0.8956<br><br>Model df: 7.   Total lags used: 24</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKuOP-h5l6cQRLRKqRqx7A.png" /><figcaption>Fig-13. Residuals Check on ARIMA Model</figcaption></figure><p>Based on the Ljung-Box test and ACF plot of model residuals, we can conclude that this model is appropriate for forecasting since its residuals show white noise behavior and uncorrelated against each other.</p><p><strong>ETS Model</strong></p><p>We will build ETS model and compares its model with our chosen ARIMA model to see which model is better against our Test Set.</p><pre><em>#ETS Model</em><br>fit_ets &lt;- ets(hujan_train, damped =TRUE)</pre><p>Similar to the ARIMA model, we also need to check its residuals behavior to make sure this model will work well for forecasting.</p><pre>checkresiduals(fit_ets)</pre><pre>Ljung-Box test<br><br>data:  Residuals from ETS(A,Ad,A)<br>Q* = 40.433, df = 7, p-value = 1.04e-06<br><br>Model df: 17.   Total lags used: 24</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__n9DkjiejSGImXLaHLArA.png" /><figcaption>Fig-14. Residuals Check on ETS Model</figcaption></figure><p>After a residual check, ACF Plot shows ETS Model residuals have little correlation between each other on several lag, but most of the residuals are still within the limits and we will stay using this model as a comparison with our chosen ARIMA model.</p><p><strong>ARIMA vs ETS Model on Test Set</strong></p><p>Better models for our time series data can be checked using the test set. We will use both of ARIMA and ETS models to predict and see their accuracy against the test set (2018, Jan-Dec).</p><p>In the first step, we need to plot visualization between ARIMA Model, ETS Model, and our actual 2018 data. But since ggfortify package doesn’t fit nicely with the other packages, we should little modify our code to show beautiful visualization.</p><p>note: if you didn’t load ggfortify package, you can directly use : autoplot(actual data) + autolayer(forecast_data) , to do visualization.</p><pre>#Modifying Data For ggplot</pre><pre>model_1 &lt;- forecast(fit1, h=12) <br>model_ets &lt;- forecast(fit_ets, h=12)<br><br>model_1 &lt;- as.data.frame(model_1$mean)<br>model_ets &lt;- as.data.frame(model_ets$mean)<br><br>colnames(model_1) &lt;- &quot;Curah_Hujan&quot;<br>colnames(model_ets) &lt;- &quot;Curah_Hujan&quot;<br><br>hujan_train_df &lt;- as.data.frame(hujan_train)<br><br>model_1_plot &lt;- rbind(hujan_train_df,model_1)<br>model_ets_plot &lt;- rbind(hujan_train_df, model_ets)<br><br>model_1_plot &lt;- model_1_plot %&gt;% <br>  mutate(&#39;Date&#39; = seq(from = as.Date(&quot;2006-01-01&quot;, &#39;%Y-%m-%d&#39;), to = as.Date(&quot;2018-12-31&quot;,&#39;%Y-%m-%d&#39;),by = &#39;month&#39;))<br><br>model_ets_plot &lt;- model_ets_plot %&gt;% <br>  mutate(&#39;Date&#39; = seq(from = as.Date(&quot;2006-01-01&quot;, &#39;%Y-%m-%d&#39;), to = as.Date(&quot;2018-12-31&quot;,&#39;%Y-%m-%d&#39;),by = &#39;month&#39;))<br><br>hujan_ts_df &lt;- as.data.frame(hujan_ts)<br><br>hujan_ts_df &lt;- hujan_ts_df %&gt;% <br>  mutate(&#39;Date&#39; = seq(from = as.Date(&quot;2006-01-01&quot;, &#39;%Y-%m-%d&#39;), to = as.Date(&quot;2018-12-31&quot;,&#39;%Y-%m-%d&#39;),by = &#39;month&#39;))<br><br>hujan_train_df &lt;- hujan_train_df %&gt;% <br>  mutate(&#39;Date&#39; = seq(from = as.Date(&quot;2006-01-01&quot;, &#39;%Y-%m-%d&#39;), to = as.Date(&quot;2017-12-31&quot;,&#39;%Y-%m-%d&#39;),by = &#39;month&#39;))<br><br>colors &lt;- c(&quot;ARIMA Model Forecast 2018&quot; = &quot;blue&quot;, &quot;ETS Model Forecast 2018&quot; = &quot;red&quot;, &quot;Actual Data&quot; = &quot;black&quot;)<br><br><br>#Creating Plot</pre><pre>ggplot() + geom_line(model_1_plot,<br>   mapping = aes(x=Date, y=Curah_Hujan, <br>   color= &quot;ARIMA Model Forecast 2018&quot;),lty = 2) +<br>  geom_line(model_ets_plot,<br>  mapping = aes(x=Date, y=Curah_Hujan, <br>  color= &quot;ETS Model Forecast 2018&quot;),lty= 2) +<br>  geom_line(hujan_ts_df,mapping = aes(x=Date, y=Curah_Hujan, <br>  color= &quot;Actual Data&quot;), lty = 1, show.legend = TRUE) +<br>  ylab(&quot;Rainfall (mm2)&quot;) + xlab(&quot;Datetime&quot;) + <br>  scale_x_date(date_labels = &#39;%b - %Y&#39;, breaks = &#39;1 year&#39;, <br>  minor_breaks = &#39;2 month&#39;) +<br>  theme_bw() + ggtitle(&quot;Banten Rainfall 2006 - 2018&quot;) + <br>  scale_color_manual(values=colors)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bc39_MwebTBeDBk7KWD7yg.png" /><figcaption>Fig-15. Actual Data vs ARIMA &amp; ETS Forecasting</figcaption></figure><p>Even though both ARIMA and ETS models are not exactly fit the same value with actual data, but surely both of them plotting a quite similar movement against it.</p><p>In numbers, we can calculate accuracy between those model with actual data and decide which one is most accurate with our data:</p><pre>#ARIMA Model Accuracy<br>accuracy(forecast(fit1, h=12), hujan_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*1j2f3l8oF25yyEJeNKKlzQ.png" /><figcaption>Fig-16. ARIMA Model Accuracy</figcaption></figure><pre>#ETS Model Accuracy<br>accuracy(forecast(fit_ets, h=12), hujan_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*5TnUfES_8e58N3UqPKgaqA.png" /><figcaption>Fig-17. ETS Model Accuracy</figcaption></figure><p>based on the accuracy, ETS Model doing better in both training and test set compared to ARIMA Model.</p><p><strong>2019–2020 Rainfall Forecasting</strong></p><p>Using the same parameter with the model that created using our train set, we will forecast 2019–2020 rainfall forecasting (h=24).</p><p>Forecasting and Plot:</p><pre><em>#Create Model</em><br>ARIMA_Model &lt;- Arima(hujan_ts, order = c(1,0,2), <br>   seasonal = c(1,0,2))<br>ETS_Model &lt;- ets(hujan_ts, damped = TRUE, model = &quot;AAA&quot;)<br><br><em>#ARIMA Model Forecast</em><br>autoplot(forecast(ARIMA_Model, h=24)) + theme_bw() + <br>  ylab(&quot;Rainfall (mm2)&quot;) + xlab(&quot;Datetime&quot;) + <br>  scale_x_date(date_labels = &#39;%b - %Y&#39;, <br>  breaks = &#39;1 year&#39;, minor_breaks = &#39;2 month&#39;) +<br>  theme_bw() + ggtitle(&quot;Banten Rainfall Forecast 2019-2020 <br>  ARIMA Model&quot;)<br><em>#ETS Model Forecast</em><br>autoplot(forecast(ETS_Model, h=24)) + theme_bw() + <br>  ylab(&quot;Rainfall (mm2)&quot;) + xlab(&quot;Datetime&quot;) + <br>  scale_x_date(date_labels = &#39;%b - %Y&#39;, breaks = &#39;1 year&#39;, <br>  minor_breaks = &#39;2 month&#39;) +<br>  theme_bw() + ggtitle(&quot;Banten Rainfall Forecast 2019-2020 <br>  ETS Model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8JuONeEs-aMoD1nqD_3SQ.png" /><figcaption>Fig-18. ARIMA Model Forecasting 2019–2020</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xg5VM8jdwS9o7zT2mkO5-w.png" /><figcaption>Fig-19. ETS Model Forecasting 2019–2020</figcaption></figure><p>Forecasting was done using both of the models, and they share similar movement based on the plot with the lowest value of rainfall will occur during August on both of 2019 and 2020.</p><p>Our prediction can be useful for a farmer who wants to know which the best month to start planting and also for the government who need to prepare any policy for preventing flood on rainy season &amp; drought on dry season. The most important thing is that this forecasting is based only on the historical trend, the more accurate prediction must be combined using meteorological data and some expertise from climate experts.</p><p>[1]<a href="https://banten.bps.go.id/">banten.bps.go.id</a>.Accessed on May,17th 2020</p><p>[2]Hyndman, R.J., &amp; Athanasopoulos, G. (2018) <em>Forecasting: principles and practice</em>, 2nd edition, OTexts: Melbourne, Australia. OTexts.com/fpp2.Accessed on May,17th 2020.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a29316494e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/rainfall-time-series-analysis-and-forecasting-87a29316494e">Rainfall Time Series Analysis and Forecasting</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>