<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2017/04/21/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/"> R Views</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><br>
</p>
<p><br>
</p>
<p>In a <a target="_blank" rel="nofollow" href="https://rviews.rstudio.com/2017/03/17/quandl-and-forecasting/">previous post</a>, we imported oil data from Quandl and applied a simple model to it. Today, we’ll port that work over to a Shiny app (by way of flexdashboard, of course) that allows a user to choose a commodity (oil, copper or gold), choose a frequency for the time series, and choose how many periods ahead to forecast. The app will display the price history and the forecasted price. To see it in action, have a look <a target="_blank" rel="nofollow" href="http://colorado.rstudio.com:3939/commodities-quandl-flexdb/">here</a>.</p>
<p>As with the previous Notebook, the main purpose of this post is to build a template where a more sophisticated or proprietary model could be used for forecasting. By setting it up so that models could be selected as inputs, several different models could be included. We are not as concerned with the modeling as much as we are with providing a format that is friendly to both end users and any future collaborator that might want to take this app and expand upon it.</p>
<p>Let’s get to it! In the code chunk below, we are immediately faced with a few important decisions. The first of those is the format of the user input. At the extreme, we could use <code>textInput</code> and simply allow the user to enter the code for the desired data set. The benefit is that we would not limit the user in any way; he or she could choose any dataset on Quandl. The cost would be that the user would need to know – or go to Quandl and look up – the code for any data set.</p>
<p>For example, to import WTI oil prices, the user would have to type in “FRED/DCOILWTICO”. That’s no problem if most of the end users know that code, but it’s a big problem otherwise. We want to emphasize convenience and broad usability, so we are going with <code>selectInput</code> instead of <code>textInput</code>, meaning our app will show a drop-down of a few choices. The user just selects “WTI oil” instead of typing “FRED/DCOILWTICO”“, or selects”copper&quot; instead of typing “ODA/PCOPP_USD”. But, if a user wants to work with a data set that we haven’t included, said user is out of luck.</p>
<p>Another big decision is how many choices to give the user. I have included only 3: oil, gold and copper. In industry, you would probably include several more, perhaps all of the industrial metals, but there’s is a cutoff somewhere. Or maybe we prefer one choice, because this app is just for oil analysis. Either way, the number of options in the drop-down menu is another trade-off between usability and flexibility.</p>
<p>The final decision is a bit more nuanced, and requires looking ahead to how these inputs will be used further down in the app. Have a peek at the object called <code>dataChoices</code>, and you might notice that we don’t strictly need that object. We could have put the vector of choices as an argument to <code>selectInput</code>, so that our code would have read <code>choices = c(&quot;WTI oil&quot; = &quot;FRED/DCOILWTICO&quot;, ...)</code> instead of <code>choices = dataChoices</code>. In that choice assignment, “WTI oil” is called the name and “FRED/DCOILWTICO” is called the value (together we can think of them as a name-value pair). The entire reason for building a separate <code>dataChoices</code> object is that we want the ability to extract either the name or the value of the name-value pair. Usually we would care only about the value, because we want to pass the value to Quandl and import the data, but that name is going to be useful as well when we label our graph.</p>
<p>The ability to extract names and values will become even more useful when we get to the frequency of the time series and forecasting. For now, let’s look at <code>dataChoices</code> and <code>selectInput</code>.</p>
<pre><code># Notice a tradeoff here: we're making it easy on our users because they don't need to 
# remember the naming conventions. But, we're also forced to severely limit their choices. 
# The dataChoices object is going to allow us to add a nicer label to the graph. 
# Notice also how easily we can include datasets from different sources, and not worry about
# their formats. Thanks, Quandl!

dataChoices &lt;- c(&quot;WTI oil&quot; = &quot;FRED/DCOILWTICO&quot;, # oil data from Fred
                 &quot;Copper&quot; = &quot;ODA/PCOPP_USD&quot;, # copper data from ODA
                 &quot;Gold&quot; = &quot;CHRIS/CME_GC1&quot;) # gold data from CME

selectInput(&quot;dataSet&quot;,
            &quot;Commodity&quot;,
            choices = dataChoices,
            selected = &quot;WTI oil&quot;)</code></pre>
<p>Alright, we have given the user the ability to choose a commodity. Next we want to ask about the frequency, and this gets a bit more complicated. We need to tell Quandl the frequency of the time series to import using the “daily”, “weekly”, “monthly” convention, so we set those to the values. But, further down the app when we want to store the forecast results, we’ll need to use the “days”, “weeks”, “months” phrasing and we’ll need to pull out the names from the name-value pair in <code>frequencyChoices</code>. We knew that this would be necessary because when we built our Notebook for importing, wrangling, and testing, we noted the different conventions and started thinking about how to deal with them in the Shiny context.</p>
<pre><code># The frequencyChoices object is going to allow us to pass different period conventions
# to different places further down the app. 

frequencyChoices &lt;- c(&quot;days&quot; = &quot;daily&quot;,
                      &quot;weeks&quot; = &quot;weekly&quot;, 
                      &quot;months&quot; = &quot;monthly&quot;)

selectInput(&quot;frequency&quot;,
            &quot;freq&quot;,
            choices = frequencyChoices, 
            selected = &quot;months&quot;)</code></pre>
<p>The remainder of the inputs should look familiar as they are in standard format.</p>
<pre><code>dateRangeInput(&quot;dateRange&quot;,
               &quot;Date range&quot;,
               start = &quot;1980-01-01&quot;,
               end   = &quot;2016-12-31&quot;)

numericInput(&quot;periods&quot;, &quot;Periods to Forecast&quot;, 6, min = 1, max = 100)</code></pre>
<p>Now that we’ve built the sidebar inputs, let’s put them to use. First, we will import the commodity time series data from Quandl. This will be familiar from the Notebook, but note in particular that we will use the value from the <code>input$frequency</code> choice because Quandl uses the “daily/weekly/monthly” frequency format.</p>
<pre><code># Let's pull in the Quandl data. 
# Nothing fancy here except we are going to use the reactive inputs.
# We will pass in the value from the input$dataSet key-value pair.
# We will also pass in the value from the input$frequency key-value pair. 

commodity &lt;- reactive({
  # It might be a good idea to include your quandl api key if this will be used more than 50 times in a day. 
  Quandl.api_key(&quot;your_apikey_here&quot;)
  
  commodity &lt;- Quandl(input$dataSet,
                      start_date = format(input$dateRange[1]),
                      end_date = format(input$dateRange[2]),
                      order = &quot;asc&quot;,
                      type = &quot;xts&quot;,
                      collapse = as.character(input$frequency)
  )
})</code></pre>
<p>We have imported a time series object for the dataset, date range and frequency chosen by the user. Now we want to do some forecasting and create a visualization. We’ll first use the <code>forecast()</code> function, then we’ll combine the forecasted prices and the historical prices into one xts object that can be passed to dygraph. Let’s handle this in one reactive.</p>
<p>First, we’ll call <code>forecast</code> and pass it the <code>periods</code> input from the user.</p>
<pre><code>combined_xts &lt;- reactive({
  
  # Just like the Notebook, except periods is a reactive input.
  
  forecasted &lt;- forecast(commodity(), h = input$periods)</code></pre>
<p>Now we need to combine that forecasted object with the commodity object that was created in a previous code chunk. Here we will finally thank ourselves for thinking about the name-value issue when assigning <code>frequencyChoices</code>. When we create a dataframe to hold the forecasted time series, we build a ‘date’ column using the <code>seq()</code> function. The column starts on the end date of the historical data (which the user selected with the <code>dateRange</code> input) and runs for as many periods as the user chose in the <code>periods</code> input. But, we need to supply a value to the <code>by = ...</code> argument of the <code>seq()</code> function so that it knows if we want to move 6 days, 6 weeks, 6 months, etc. To do that, we need to extract the name (“days/weeks/months”) from the <code>frequencyChoices</code> name-value pair and pass it to seq. The way we extract the name is with this selection statement: <code>names(frequencyChoices[frequencyChoices == input$frequency])</code>.</p>
<pre><code>  forecast_dataframe &lt;- data.frame(
    date = seq(input$dateRange[2], 
               # The next line is very important, and it's the reason we 
               # created the frequencyChoices object.
               by = names(frequencyChoices[frequencyChoices == input$frequency]),
               length.out = input$periods),
    Forecast = forecasted$mean,
    Hi_95 = forecasted$upper[,2],
    Lo_95 = forecasted$lower[,2])</code></pre>
<p>Now we convert the <code>forecast_dataframe</code> object to an xts and combine that new object with the <code>commodity</code> xts object. Remember, we imported the commodity data from Quandl in the form of an xts object, which saved us from having to do a conversion. This chunk should look very similar to the Notebook.</p>
<pre><code>  forecast_xts &lt;- xts(forecast_dataframe[,-1], order.by = forecast_dataframe[,1])
  
  combined_xts &lt;- cbind(commodity(), forecast_xts)
  
  # Add a nicer name for the first column.
  
  colnames(combined_xts)[1] &lt;- &quot;Actual&quot;
  
  # This is the combined object that will be passed to dygraphs below. 
  combined_xts
})</code></pre>
<p>Next, we will create a chart of the actual price history. Nothing fancy here, except again we are going extract the ‘name’ portion of a name-value pair, this time from the <code>dataSet</code> object (the first one we created in the first code chunk). We want to label the graph with ‘WTI oil’ and not the Quandl code, so we select the name with <code>names(dataChoices[dataChoices==input$dataSet])</code>.</p>
<pre><code>dygraphOutput(&quot;commodity&quot;)

output$commodity &lt;- renderDygraph({
  dygraph(commodity(),
          # We pull out the name of the selected name-value input$dataSet like so: 
          # names(dataChoices[dataChoices==input$dataSet])
          main = paste(&quot;Price history of&quot;, names(dataChoices[dataChoices==input$dataSet]), 
                       sep = &quot; &quot;)) %>%
    dyAxis(&quot;y&quot;, label = &quot;$&quot;) %>%
    dyOptions(axisLineWidth = 1.5, fillGraph = TRUE, drawGrid = TRUE)
})</code></pre>
<p>Last but not least, let’s graph the historical and forecasted time series together on one graph. We could have ported the code directly from the Notebook, but I couldn’t help tinkering just a bit. I wanted to focus the graph on the time period around where the actual data ends and the forecast begins, because that is probably what’s of most interest to the user. To do that, we’ll use the <code>dyRangeSelector()</code> function and pass two values to the <code>dateWindow</code> variable: a start date and end an date. This is pure aesthetics, but I think it’s worth the effort here.</p>
<p>We are going to use <code>seq()</code> and <code>names(frequencyChoices[frequencyChoices == input$frequency])</code> once again.</p>
<pre><code>dygraphOutput(&quot;forecasted&quot;)

output$forecasted &lt;- renderDygraph({

# We want the user to be able to see the forecasted area, so let's focus in on that 
# by truncating the view of the dygraph.
# We need to give the graph a start date and an end date. 
start_date &lt;- tail(seq(input$dateRange[2], by = &quot;-1 months&quot;, length = 6), 1)
end_date &lt;- tail(seq(input$dateRange[2], 
                     by = names(frequencyChoices[frequencyChoices == input$frequency]), 
                     length = input$periods), 1)</code></pre>
<p>Now we will supply those date objects to a piped dygraphs chain, and that will be a wrap. Have a close look at the chunk below and spot where we again extract the name from the <code>input$dataSet</code> name-value pair.</p>
<pre><code>dygraph(combined_xts(), 
        # Name about to be extracted!
        main = paste(names(dataChoices[dataChoices==input$dataSet]), 
                     &quot;: Historical and Forecast&quot;, sep = &quot;&quot;)) %>%
  # Add the actual series.
  dySeries(&quot;Actual&quot;, label = &quot;Actual&quot;) %>%
  # Add the three forecasted series.
  dySeries(c(&quot;Lo_95&quot;, &quot;Forecast&quot;, &quot;Hi_95&quot;)) %>% 
  # A range selector to focus on the where historical data ends and 
  # foracated data begins.
  # Note the user can still use the range selector to zoom out if so desired.
  dyRangeSelector(dateWindow = c(start_date, end_date))
})</code></pre>
<p>That’s all for today! We’ve built an app that can be extended in many directions – more data set choices, an input selector so the user can choose different models, more visualizations – and in that sense it can serve as a template for ourselves and anyone that wants to build upon this work.</p>
<p>This app also relies on and highlights one of the tremendous benefits of Quandl: the ability to import datasets from different sources and have them arrive in the IDE in a consistent format. This makes using Quandl with Shiny quite enjoyable after the initial skeleton is built. For example, if we or a colleague did want to change this app and substitute in different commodities, there would be no worry beyond the finding the right code on Quandl and adding another name-value pair to <code>dataChoices</code>.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rviews.rstudio.com/2017/04/21/a-shiny-app-for-importing-and-forecasting-commodities-prices-from-quandl/"> R Views</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/EGFEOiJpZg8"></a></div>