<?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 Andrew Wigmore on Medium]]></title>
        <description><![CDATA[Stories by Andrew Wigmore on Medium]]></description>
        <link>https://medium.com/@awigmore?source=rss-228975b7d50a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*No3mC7DpSUk6Huk_.jpg</url>
            <title>Stories by Andrew Wigmore on Medium</title>
            <link>https://medium.com/@awigmore?source=rss-228975b7d50a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:11:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@awigmore/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[How to find weather data using NLP (Natural Language Processing)]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-find-weather-data-using-nlp-natural-language-processing-3093f7544a5f?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3093f7544a5f</guid>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[weather-api]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 17:44:50 GMT</pubDate>
            <atom:updated>2021-07-12T06:41:37.493Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Natural_language_processing">Natural Language Processing (NLP)</a> is an artificial intelligence process used to by computer systems to find the meaning of text content. This allows the human users to ask questions using sentences written in a natural way using normal sentences. Successful NLP systems will allow users to ask questions in different ways and still be able to understand the meaning of the question being asked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*px_niUcnOZjGqRB_yU7ePg.jpeg" /></figure><p>In this article we use Natural Language Processing (NLP) to create a sample Java application that can find weather data using ‘natural language’ text questions. This allows users to find weather data using queries such as:</p><ul><li><em>Tell me the weather in Tokyo, Japan on the 6th January 1975.</em></li><li><em>What will the weather be in London, England next Wednesday?</em></li><li><em>What was the weather in Washington,DC last 4th July?</em></li></ul><p><em>For the full source of this example, download it from the GitHub repository: </em><a href="https://github.com/visualcrossing/WeatherApi/tree/master/Java/com/visualcrossing/weather/samples">https://github.com/visualcrossing/WeatherApi/tree/master/Java/com/visualcrossing/weather/samples</a></p><h3>Steps to create a simple NLP weather answer bot</h3><p>In our sample, we will restrict our NLP processing to identifying if the user is asking a question about weather data. Supported questions will be find out the upcoming weather forecast or looking up historical weather observations.</p><p>To do this, we need to identify two pieces of information:</p><ol><li>The location for which the user is attempting to find weather information.</li><li>The date or date range for the weather data.</li></ol><p>Once we have found this information, we can then look up the weather data. To do this, we will use the <a href="https://www.visualcrossing.com/resources/documentation/weather-api/timeline-weather-api/">Visual Crossing Weather API</a>. This Timeline Weather API makes it easy to look up both past and future weather data as it automatically adjusts to the date range we ask for. If we ask for dates in the future, it will give us the weather forecast. If we ask for data in the past, then it will give us historical weather observations.</p><p><em>To run the sample code, you will need a free Weather API key. If you don’t have an API key, head over to the </em><a href="https://www.visualcrossing.com/weather/weather-data-services"><em>free sign up page</em></a><em> to create your key.</em></p><h3>Step one — setting up the NLP Processing</h3><p>There are a number of excellent open source Java libraries that can be used for NLP processing. These include <a href="https://opennlp.apache.org/">Apache OpenNLP</a> and the <a href="https://stanfordnlp.github.io/CoreNLP/">CoreNLP </a>created by the <a href="https://nlp.stanford.edu/">Standard NLP Group</a>. In this sample, we will use CoreNLP as it provides a simple way to get started and includes pre-trained models for many of the questions we need the API to answer.</p><h4>Identifying the location and dates</h4><p>We will use our NLP processing to work to find two pieces of information from the user questions so we can find appropriate weather data — the location and dates. We will therefore focus on appropriate using named entity recognition to find entity mentions within the text. Entity mentions represent items of particular interest within the text such as a person, location, date or time.</p><p>We are looking for entity mentions that identify the target location of the weather data (such as city, state or province or country) and the dates for which we should find the weather data.</p><p>Therefore we need the NLP processor to be able to the location from the text. Let’s consider a couple of examples.</p><p>In this case, the processor should identify the location is Tokyo, Japan and that the user has provided an exact date — 6th January 1975. <a href="https://corenlp.run/">CoreNLP includes a demo sit</a> e that provides a graphical interpretation of the text:</p><p>We can see that the library correctly identifies the location as the combination of a city and country and then identifies and parses the intended date correctly.</p><p>We will be able to pass the location of ‘Tokyo, Japan’ and the date to the Weather API to look up the weather information.</p><p><em>What will the weather be in </em><strong><em>London, England</em></strong><em> </em><strong><em>next Wednesday</em></strong><em>?</em></p><p>The location in this case is London, England. The date is a little trickier as it’s not a simple date (although there are many ways a user might ask for a date so even that is not a trivial exercise!) We would like the NLP to be able to interpret ‘next Wednesday’ as asking for date and then convert it to an exact date.</p><p>If we run the above text through the online text, we can see that again the library correctly finds the location and intended date:</p><p>We can see the the NLP processing as correctly understood the concept of ‘next Wednesday’. From there, the library finds the next Wednesday after the current date.</p><p><em>What was the weather in </em><strong><em>Washington,DC</em></strong><em> </em><strong><em>last 4th July</em></strong><em>?</em></p><p>If we look at our final example, again we see that the NLP library correctly processes the location and target date:</p><p>Again the library has been able to identify the City of Washington,DC and interpreted the ‘last’ to refer to the last occurrence of the 4th of July.</p><h3>Step two -creating the NLP Java code</h3><p>We are now ready to create the first part of our Java sample. Our simple will be a Java application that prompts the user for text, processes the text for the requested location and dates and then looks up the weather data. This will be processed via the Java system.out to keep things simple.</p><p>Before jumping into the code, first download the required libraries from CoreNLP. These samples were written using version 4.2.2 but any recent version should work.</p><p>If you configure your Java project using maven, you can find the require maven dependencies <a href="https://search.maven.org/artifact/edu.stanford.nlp/stanford-corenlp">here</a>. The maven dependencies we added were:</p><pre>&lt;dependency&gt; <br> &lt;groupId&gt;edu.stanford.nlp&lt;/groupId&gt; <br> &lt;artifactId&gt;stanford-corenlp&lt;/artifactId&gt; <br> &lt;version&gt;4.2.2&lt;/version&gt; <br>&lt;/dependency&gt; <br>&lt;dependency&gt; <br> &lt;groupId&gt;edu.stanford.nlp&lt;/groupId&gt;<br> &lt;artifactId&gt;stanford-corenlp&lt;/artifactId&gt;<br> &lt;version&gt;4.2.2&lt;/version&gt;<br> &lt;classifier&gt;models&lt;/classifier&gt;<br> &lt;/dependency&gt;</pre><h4>Setting up the NLP Pipeline</h4><p>The first part of our code is the main Java method. In this method we first set up the CoreNLP pipeline and create a basic loop for the user to enter text. For more information on the set up and configuration of CoreNLP, see the <a href="https://stanfordnlp.github.io/CoreNLP/api.html">CoreNLP API samples.</a></p><pre>public static void main(String[] args) {<br> // set up pipeline properties<br> Properties props = new Properties();<br> // set the list of annotators to run<br> props.setProperty(&quot;annotators&quot;,&quot;tokenize,ssplit,pos,lemma,ner&quot;);<br> <br> // set to use the neural algorithm<br> props.setProperty(&quot;coref.algorithm&quot;, &quot;neural&quot;);<br>        props.setProperty(&quot;ner.docdate.usePresent&quot;, &quot;true&quot;);<br>        props.setProperty(&quot;sutime.includeRange&quot;, &quot;true&quot;);<br>        props.setProperty(&quot;sutime.markTimeRanges&quot;, &quot;true&quot;);<br>        <br> // build pipeline<br> System.out.printf(&quot;Starting pipeline...%n&quot;);<br> StanfordCoreNLP pipeline = new StanfordCoreNLP(props);<br> System.out.printf(&quot;Pipeline ready...%n%n&quot;);<br><br> }<br>}</pre><p>We have reduced the numbers of annotators for our sample because we are mainly focused on the output of the ‘ner’ annotator. ‘ner’ is short for ‘ NERCombinerAnnotator’ which is responsible for the named entity processing we need to find the locations and dates. The remaining annotators are required for ner to function.</p><p>We now add a loop to the above main method to allow the user to enter text and have the sample process the data.</p><pre>public static void main(String[] args) {<br> // set up pipeline properties<br> Properties props = new Properties();<br> // set the list of annotators to run<br> props.setProperty(&quot;annotators&quot;,&quot;tokenize,ssplit,pos,lemma,ner&quot;);<br> <br> // set to use the neural algorithm<br> props.setProperty(&quot;coref.algorithm&quot;, &quot;neural&quot;);<br>        props.setProperty(&quot;ner.docdate.usePresent&quot;, &quot;true&quot;);<br>        props.setProperty(&quot;sutime.includeRange&quot;, &quot;true&quot;);<br>        props.setProperty(&quot;sutime.markTimeRanges&quot;, &quot;true&quot;);<br>        <br> // build pipeline<br> System.out.printf(&quot;Starting pipeline...%n&quot;);<br> StanfordCoreNLP pipeline = new StanfordCoreNLP(props);<br> System.out.printf(&quot;Pipeline ready...%n%n&quot;);<br> <br> //loop for ever asking the user for text to process<br> try (Scanner in = new Scanner(System.in)) {<br>  while (true) {<br>  System.out.printf(&quot;Enter text:%n%n&quot;);<br>  <br>  String text = in.nextLine();<br>  try {<br>   processText(pipeline, text);<br>  } catch (Throwable e) {<br>   // TODO Auto-generated catch block<br>   e.printStackTrace();<br>  }<br>  <br>  }<br> }<br>}</pre><p>After the user enters text, the sample passes the configured pipeline and the text to a second method ‘processText’ to process the text.</p><h4>Processing the text for location and date</h4><pre>private static void processText(StanfordCoreNLP pipeline, String text) throws Exception {<br> CoreDocument document = new CoreDocument(text);<br> // annnotate the document<br> pipeline.annotate(document);<br> <br> if (document.entityMentions()==null || document.entityMentions().isEmpty()) {<br>  System.out.println(&quot;no entities found&quot;);<br>  return;<br> }<br> <br> String city=null;<br> String state=null;<br> String country=null;<br> LocalDate startDate=null;<br> LocalDate endDate=null;<br>     for (CoreEntityMention em : document.entityMentions()) {<br>      <br>      <br>      if (DATE.equals(em.entityType())) {<br>      Timex timex=em.coreMap().get(TimeAnnotations.TimexAnnotation.class);<br>      Calendar t1=timex.getRange().first;<br>      if (t1!=null) {<br>       startDate=LocalDateTime.ofInstant(t1.toInstant(), ZoneId.systemDefault()).toLocalDate();<br>      }<br>      Calendar t2=timex.getRange().second;<br>      if (t2!=null) {<br>       endDate=LocalDateTime.ofInstant(t2.toInstant(), ZoneId.systemDefault()).toLocalDate();<br>      }<br>      } else if (LOCATION_CITY.equals(em.entityType())) {<br>      city=em.text();<br>      } else if (LOCATION_STATE_OR_PROVINCE.equals(em.entityType())) {<br>      state=em.text();<br>      } else if (LOCATION_COUNTRY.equals(em.entityType())) {<br>      country=em.text();<br>      }<br>     }<br>     String location=&quot;&quot;;<br>     if (city!=null) location+=location.isEmpty()?city:(&quot;,&quot;+city);<br>     if (state!=null) location+=location.isEmpty()?state:(&quot;,&quot;+state);<br>     if (country!=null) location+=location.isEmpty()?country:(&quot;,&quot;+country);<br>     System.out.printf(&quot;Location=%s; fromDate=%s, toDate=%s%n&quot;, location,<br>      startDate!=null?startDate.format(DateTimeFormatter.ISO_LOCAL_DATE):&quot;[Null]&quot;,<br>       endDate!=null?endDate.format(DateTimeFormatter.ISO_LOCAL_DATE):&quot;[Null]&quot;<br>       );<br>     <br>     if (location==null || location.isEmpty()) {<br>      System.out.println(&quot;no location information found&quot;);<br>      return;<br>     }<br>     timelineRequestHttpClient(location, startDate, endDate);<br> }</pre><p>First the code processes the text by creating a document and then annotates it using the pipeline we configured aboveAfter annotation is complete we can then examine the results to find out if we have any of the requested entity mentions.</p><p>To find the possible entity mentions, we loop through the list found during the processing. We use the entity type to help identify the information we receive. If we find we have a date, we use the Timex instance to find the start and end date.</p><p>After that, we look for location related annotations (city, state or province name or country). If we find any of them, we remember them.</p><p>After all the entities have been examined, we construct a single location string that represents the combination of the the location entities that we found (just like an address is a combination of city, state, country etc). We need a single string to pass this location information to the Weather API to help the API identify the exact location being requested.</p><h4>Retrieving the information from the weather API</h4><p>We now have the location and date or dates range for our request so we can proceed to read weather data from the Weather API. For more information on how to use the Weather API in Java and for different ways to read data over the network, check out <a href="https://www.visualcrossing.com/resources/documentation/weather-api/how-to-use-timeline-weather-api-to-retrieve-historical-weather-data-and-weather-forecast-data-in-java/">How to use timeline weather API to retrieve historical weather data and weather forecast data in Java</a>.</p><p>We need a few more maven dependencies in our case to handle the network request and the JSON parsing:</p><pre>&lt;dependency&gt; <br> &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;<br> &lt;artifactId&gt;httpclient&lt;/artifactId&gt;<br> &lt;version&gt;4.5.12&lt;/version&gt;<br> &lt;/dependency&gt;<br>&lt;dependency&gt;<br> &lt;groupId&gt;org.json&lt;/groupId&gt;<br> &lt;artifactId&gt;json&lt;/artifactId&gt;<br> &lt;version&gt;20200518&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>The Weather API is used to request the weather data in JSON format:</p><pre>public static void timelineRequestHttpClient(String location, LocalDate startDate, LocalDate endDate ) throws Exception {<br> //set up the end point<br> String apiEndPoint=&quot;<a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/</a>&quot;;<br> <br> <br> String unitGroup=&quot;us&quot;;<br> <br> <br> StringBuilder requestBuilder=new StringBuilder(apiEndPoint);<br> requestBuilder.append(URLEncoder.encode(location, StandardCharsets.UTF_8.toString()));<br> <br> if (startDate!=null) {<br>  requestBuilder.append(&quot;/&quot;).append(startDate.format(DateTimeFormatter.ISO_DATE));<br>  if (endDate!=null &amp;&amp; !startDate.equals(endDate)) {<br>  requestBuilder.append(&quot;/&quot;).append(endDate.format(DateTimeFormatter.ISO_DATE));<br>  }<br> }<br> <br> URIBuilder builder = new URIBuilder(requestBuilder.toString());<br> <br> builder.setParameter(&quot;unitGroup&quot;, unitGroup)<br>  .setParameter(&quot;key&quot;, API_KEY)<br>  .setParameter(&quot;include&quot;, &quot;days&quot;)<br>  .setParameter(&quot;elements&quot;, &quot;datetimeEpoch,tempmax,tempmin,precip&quot;);</pre><pre>HttpGet get = new HttpGet(builder.build());<br> <br> CloseableHttpClient httpclient = HttpClients.createDefault();<br> <br> CloseableHttpResponse response = httpclient.execute(get);    <br> <br> String rawResult=null;<br> try {<br>  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {<br>  System.out.printf(&quot;Bad response status code:%d%n&quot;, response.getStatusLine().getStatusCode());<br>  return;<br>  }<br>  <br>  HttpEntity entity = response.getEntity();<br>     if (entity != null) {<br>      rawResult=EntityUtils.toString(entity, Charset.forName(&quot;utf-8&quot;));<br>     }<br>     <br>     <br> } finally {<br>  response.close();<br> }<br> <br> parseTimelineJson(rawResult);<br> <br> }</pre><p>The first part of the code creates the Timeline Weather API request URL. First the location is added to the request. The dates are added if necessary. If a single date is requested then that is added by itself otherwise two dates will be added. If no date is added to the request, the 15 day forecast will be returned.</p><p>A single date request will look like this:</p><pre><a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/Washington,DC/2020-07-04?unitGroup=us&amp;key=YOUR_API_KEY&amp;include=dates&amp;elements=datetimeEpoch,tempmax,tempmin,precip">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/Washington,DC/2020-07-04?unitGroup=us&amp;key=YOUR_API_KEY&amp;include=dates&amp;elements=datetimeEpoch,tempmax,tempmin,precip</a></pre><p>A date range request will look like this:</p><pre><a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/Washington,DC/2020-07-04/2020-08-04?unitGroup=us&amp;key=YOUR_API_KEY&amp;include=dates&amp;elements=datetimeEpoch,tempmax,tempmin,precip">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/Washington,DC/2020-07-04/2020-08-04?unitGroup=us&amp;key=YOUR_API_KEY&amp;include=dates&amp;elements=datetimeEpoch,tempmax,tempmin,precip</a></pre><p>Note also the use of the optional ‘elements’ and ‘include’ parameters. These parameters are used to filter the amount of data that is returned from the request.</p><p><em>include=dates</em> tells the API to only give us date level information (otherwise hourly information will also be included).</p><p><em>elements=datetimeEpoch,tempmax,tempmin,precip</em> instructs the API to only return those four pieces of weather data. Other information such as wind, pressure etc will not be included.</p><h4>Displaying the weather data</h4><p>The final piece of the code displays a very simple table of weather data to the command line:</p><pre>private static void parseTimelineJson(String rawResult) {<br> <br> if (rawResult==null || rawResult.isEmpty()) {<br>  System.out.printf(&quot;No raw data%n&quot;);<br>  return;<br> }<br> <br> JSONObject timelineResponse = new JSONObject(rawResult);<br> <br> ZoneId zoneId=ZoneId.of(timelineResponse.getString(&quot;timezone&quot;));<br> <br> System.out.printf(&quot;Weather data for: %s%n&quot;, timelineResponse.getString(&quot;resolvedAddress&quot;));<br> <br> JSONArray values=timelineResponse.getJSONArray(&quot;days&quot;);<br> <br> System.out.printf(&quot;Date\tMaxTemp\tMinTemp\tPrecip\tSource%n&quot;);<br> for (int i = 0; i &lt; values.length(); i++) {<br>  JSONObject dayValue = values.getJSONObject(i);<br>        ZonedDateTime datetime=ZonedDateTime.ofInstant(Instant.ofEpochSecond(dayValue.getLong(&quot;datetimeEpoch&quot;)), zoneId);<br>            <br>        double maxtemp=dayValue.getDouble(&quot;tempmax&quot;);<br>        double mintemp=dayValue.getDouble(&quot;tempmin&quot;);<br>        double precip=dayValue.getDouble(&quot;precip&quot;);<br>          <br>        System.out.printf(&quot;%s\t%.1f\t%.1f\t%.1f%n&quot;, datetime.format(DateTimeFormatter.ISO_LOCAL_DATE), maxtemp, mintemp, precip );<br>    }<br>}</pre><p>This code parses the incoming JSON data from the Weather API. From there, the code loops through the values in the days array and extracts the datetime, tempmax,tempmin and precip values from each day.</p><p>The time is processed by reading the date using the seconds since epoch and supplying the location time zone ID. This creates a ZonedDateTime instance.</p><p>The final result is a simple of weather data for the location and dates requested in the original text.</p><p>Thank you for reading. Please let me know if you have any comments or questions below!</p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/resources/documentation/weather-api/how-to-find-weather-data-using-nlp/"><em>https://www.visualcrossing.com</em></a><em> on June 11, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3093f7544a5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-find-weather-data-using-nlp-natural-language-processing-3093f7544a5f">How to find weather data using NLP (Natural Language Processing)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</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 load historical weather data into any database]]></title>
            <link>https://awigmore.medium.com/how-to-load-historical-weather-data-into-any-database-d12cdaead1c0?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d12cdaead1c0</guid>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[climate]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 13:14:20 GMT</pubDate>
            <atom:updated>2020-11-30T19:43:18.340Z</atom:updated>
            <content:encoded><![CDATA[<p>Many business intelligence, data science, and academic research projects need high quality historical weather data to be available in a database. Weather data is typically quite large in volume, and its analysis often requires processing thousands or even millions of detailed records in order to find valuable patterns and apply them to the task at hand. For this reason, using a database as a storage and analysis platform is the best option for many projects.</p><p>In this article, we will walk through the steps of importing historical weather data into a database. While the flow is the same for any database, the exact command syntax and SQL varies somewhat for different database platforms. To make your project easier, we have noted specific commands for most popular database platforms below.</p><h3>Creating a new database</h3><p>This database creation step is required here for completeness so that readers starting from scratch can follow along easily. However, many readers may already have an existing database into which they want to add weather data. If you are one of those, you can safely skip this step and jump to the next header below.</p><p>If you have just installed a fresh database server or want to keep your weather data entirely separate from your existing data, then you will want to create a new database instance. In nearly all databases this can be done simply by logging in with administrator access and executing a “create database” command like this.</p><pre>CREATE DATABASE Weather_DB;</pre><p>(Note that this example names the database “Weather_DB”. Feel free to choose something else that better meets your own naming convention. Just make sure to use the same name consistently throughout all of the steps in the article.)</p><p>In most databases there are optional parameters that can be added to tune the database or the storage associated with it. For example, in <a href="https://dev.mysql.com/doc/refman/5.7/en/create-database.html">MySQL</a> you can specify a character set and collation type, in <a href="https://www.tutorialspoint.com/db2/db2_databases.htm">DB/2</a> you can specify security settings and storage options, and in <a href="https://docs.oracle.com/cd/B28359_01/server.111/b28310/create003.htm#ADMIN11080">Oracle</a> and <a href="https://docs.microsoft.com/en-us/sql/t-sql/statements/create-database-transact-sql?view=sql-server-ver15">SQL Server</a> you can set a host of options including languages, logfiles, and date formats. If you are working in an environment managed by others, then you will want to check with your local DBA to determine any appropriate, additional options. Otherwise, the universal create database command above should be fine to get you started.</p><h3>Obtaining weather data</h3><p>Now that we have a database in which to store weather data, we need to find a source for that data. A weather data service such as <a href="https://www.visualcrossing.com/weather-data">Visual Crossing Weather</a> can provide bulk weather data in various convenient formats such as CSV that be directly imported into nearly any database. The <a href="https://www.visualcrossing.com/weather/weather-data-services">web-based query interface</a> lets you specify the detailed weather query that we want to run and then allows you to instantly download the results as a CSV file. You can then use this same query as the foundation for a recurring <a href="https://www.visualcrossing.com/resources/documentation/weather-data/bulk-weather-data-in-visual-crossing/">bulk data</a> query, if want to retrieve updated data over time.</p><p>If you would like to follow a step-by-step guide for downloading a CSV result set based on your own weather query, please follow the <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-can-i-download-weather-history-data-as-a-csv-file/">CSV tutorial</a> or watch the matching guide <a href="https://youtu.be/Ruh2n6HwblQ">video</a>. Following these steps will get you a weather data CSV file for your exact location and date range in just a couple of minutes.</p><h3>Creating a weather table</h3><p>Now that we have a CSV file containing weather data, we are ready to load it as a table into the database. If you are familiar with your database’s GUI tools, you can typically load a CSV file easily via their UI. However, in this article we’ll discuss how to load the file via a scriptable command. This is extremely useful since SQL and other scripts can be easily automated for future and periodic use. In many cases you will want to load periodic weather data updates as part of an <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">ETL</a> process.</p><p>If you are using a command line tool, before working with a database, you typically need to set that database as the current default target for your actions. On most databases, this is done with the “use” command.</p><pre>USE Weather_DB;</pre><p>(Note that the database name “Weather_DB” matches the name that we created in this article above. If the database in which you want to store the data has a different name, simply replace “Weather_DB” with that alternate name.)</p><p>However, on <strong>DB/2</strong>, you typically connect log into a database directly, so you would use a command such as “connect to Weather_DB” instead. This is also true on <strong>Microsoft Access</strong> and <strong>Postgres</strong> (also known as <strong>PostgreSQL</strong>) where you connect to a specific database when you log in.</p><p>We next need to create the table to hold the weather data. The table structure is the same for all major databases even though the column types differ slightly. We’ll start off with a standard SQL create statement and then note how to modify it as needed for various popular databases.</p><pre>CREATE TABLE Weather_Data ( address varchar(256) DEFAULT NULL, latitude float DEFAULT NULL, longitude float DEFAULT NULL, date_time datetime DEFAULT NULL, maxt float DEFAULT NULL, mint float DEFAULT NULL, temperature float DEFAULT NULL, precip float DEFAULT NULL, wspd float DEFAULT NULL, wdir float DEFAULT NULL, wgust float DEFAULT NULL, pressure float DEFAULT NULL);</pre><p>This table structure will work for <strong>Microsoft SQL Server</strong>, <strong>MySQL</strong>, <strong>MariaDB</strong>, and other databases that adhere to standard SQL. However, some databases require minor modifications to the types. Here are the changes required for other popular databases.</p><p><strong>IBM DB/2</strong></p><ul><li>Change the “float” type to “real”. (Note that many modern versions of DB/2 have an internal mapping that allows you to create a column as type “float” and let DB/2 automatically store it as type “real”.</li></ul><p><strong>Microsoft Access</strong></p><ul><li>Change the “varchar” type to “text”.</li></ul><p><strong>Oracle</strong></p><ul><li>Change the “datetime” type to be “date”.</li><li>Although it is optional, Oracle recommends that you create variable-length string columns using the “varchar2” type instead of “varchar”. Internally, they both represent the same type to the database.</li></ul><p><strong>Postgres</strong></p><ul><li>Change the “datetime” to be “timestamp”.</li><li>Change “float” to be “real”.</li></ul><h3>Loading the weather data</h3><p>Now we are ready to load the weather data into our new table. The syntax is somewhat different for nearly every database. However, the process is the same. We want to take the CSV file that we downloaded and use a SQL or script command to import it into the table the that we just created to store it.</p><p>Because the command is different for each database, we’ll discuss each popular database in turn. Also, for the sake of these examples, we’ll assume the the weather data file name is named “Weather_File.csv” and is stored in a directory named “c:\MyWeather”. If your location and name are different, in the example commands below, just change the file parameter to match your own local paths.</p><h4>IBM DB/2</h4><p>In DB/2 the command to import our historical weather CSV file is as follows:</p><pre>IMPORT FROM &quot;c:\MyWeather\Weather_File.csv&quot; OF DEL SKIPCOUNT 1 INSERT INTO Weather_Data;</pre><p>This will load the entire set of records from the weather CSV file into the table that we created above. Note that the “SKIPCOUNT 1” parameter tells DB/2 to skip the headers in the first row of data. For more details on optional parameters and usage of the DB/2 “Import” command, please see the article from IBM here: <a href="https://www.ibm.com/support/pages/how-import-data-db2-database-table-csv-file">https://www.ibm.com/support/pages/how-import-data-db2-database-table-csv-file</a>.</p><h4>Microsoft Access</h4><p>In Microsoft Access loading a CSV is typically done via the graphical wizard. However, you can also use VBA to script the process. (There are many tutorials on the internet showing the steps for using the Access GUI import functionality, if you need a helping hand. Here is one example: <a href="https://blog.ip2location.com/knowledge-base/how-to-import-csv-into-microsoft-access-database/">https://blog.ip2location.com/knowledge-base/how-to-import-csv-into-microsoft-access-database/</a>) In VBA the action command to load our sample CSV is named “TransferText” and looks like this:</p><pre>DoCmd.TransferText TransferType:= acImportdelim, TableName:=&quot;Weather_Data&quot;, FileName:=&quot;c:\MyWeather\Weather_File.csv&quot;, HasFieldNames:=true</pre><p>You will need to run this command as VBA within Access. For this you often need to wrap this command into a simple VBA function. Note that the HasFieldNames tells Access that the first row of the CSV contains our column names, and these should match the table that we created above. You can read more about the details and parameters of the “TransferText” function here:<br><a href="https://docs.microsoft.com/en-us/office/vba/api/access.docmd.transfertext">https://docs.microsoft.com/en-us/office/vba/api/access.docmd.transfertext</a></p><h4>Microsoft SQL Server</h4><p>SQL Server can directly import our weather CSV file with a SQL command such as this.</p><pre>BULK INSERT Weather_Data FROM &#39;c:\MyWeather\Weather_File.csv&#39; WITH ( FIRSTROW = 2, FIELDTERMINATOR = &#39;,&#39;, ROWTERMINATOR = &#39;\n&#39;, TABLOCK )</pre><p>These standard parameters tell SQL Server to skip the header row, configure the delimiters, and request a table lock (“TABLOCK”) during the insert process. To learn more about SQL Server’s “Bulk Insert” command parameters, see Microsoft’s documentation here: <a href="https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-ver15">https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-ver15</a></p><p>Note also that it is also easy to accomplish this CSV import via the SQL Server GUI tools. If you are interested in this option, you can follow it step-by-step in Microsoft’s tutorial here: <a href="https://docs.microsoft.com/en-us/sql/relational-databases/import-export/import-flat-file-wizard?view=sql-server-ver15">https://docs.microsoft.com/en-us/sql/relational-databases/import-export/import-flat-file-wizard?view=sql-server-ver15</a></p><h4>MySQL (and MariaDB)</h4><p>MySQL’s import syntax is similar to SQL Server. You can import our weather data file with this command:</p><pre>LOAD DATA INFILE &#39;c:\MyWeather\Weather_File.csv&#39; INTO TABLE Weather_Data FIELDS TERMINATED BY &#39;,&#39; ENCLOSED BY &#39;&quot;&#39; LINES TERMINATED BY &#39;/n&#39; IGNORE 1 ROWS;</pre><p>The parameters simply tell MySQL the table name, the delimiters, and to ignore the header row in the data. If you want to learn more about the other parameters that are available, you can find the detailed “Load Data” documentation here: <a href="https://dev.mysql.com/doc/refman/8.0/en/load-data.html">https://dev.mysql.com/doc/refman/8.0/en/load-data.html</a> and very similar options for MariaDB here: <a href="https://mariadb.com/kb/en/load-data-infile/">https://mariadb.com/kb/en/load-data-infile/</a>. Note that this import can also be accomplished via various GUI admin tools such as <a href="https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-table.html">MySQL Workbench</a>.</p><h4>Oracle</h4><p>It is likely not a surprise to those of you who are Oracle users that Oracle is a bit more complex than other databases when it comes to importing CSV files. The standard way to accomplish this is via the <a href="https://docs.oracle.com/cd/B19306_01/server.102/b14215/part_ldr.htm">SQL Loader</a> tool. If you have any experience with Oracle, you have likely already used this tool. It is an external tool with the primary mission of importing data from external sources into Oracle database tables. Hence it is ideally suited to our CSV import task.</p><p>SQL Loader is powered by a <a href="https://docs.oracle.com/cd/B19306_01/server.102/b14215/ldr_control_file.htm#i1006645">Control File</a> that feeds the appropriate load parameters to tell the tool where to find the data and how to load it. In our case, we can use a control file like this to load our weather data.</p><pre>LOAD DATA infile &#39;c:\MyWeather\Weather_File.csv&#39; REPLACE INTO TABLE Weather_Data fields terminated by &#39;,&#39; optionally enclosed by &#39;&quot;&#39; ( address, latitude, longitude, date_time, maxt, mint, temperature, precip, wspd, wdir, wgust, pressure )</pre><p>If you saved the above command file with the name WeatherDataLoader.ctl, you could then run SQL Loader with a command like this.</p><pre>sqlldr userid/passwd@Weather_DB control=WeatherDataLoader.ctl</pre><p>(Note that you need to replace the placeholders in the command above with your proper userid and password.)</p><p>As with many tasks in Oracle, there are several other ways to accomplish a CSV import. You can use the <a href="https://docs.oracle.com/database/121/ADMQS/GUID-7068681A-DC4C-4E09-AC95-6A5590203818.htm">SQL Developer</a> admin tool GUI or even another Oracle command line utility package cleverly named <a href="https://docs.oracle.com/database/121/ARPLS/u_file.htm">UTL</a>.</p><h4>Postgres (PostgreSQL)</h4><p>Postgres makes it easy to copy data from a CSV file into a table using the “copy” command. Simply specify basic parameters using a command like this:</p><pre>COPY Weather_Data FROM &#39;c:\MyWeather\Weather_File.csv&#39; DELIMITER &#39;,&#39; CSV HEADER;</pre><p>The “CSV HEADER” parameter tells Postgres to treat the first row of the CSV as headers instead of data. If you want more details on the Postgres “Copy” command and its many options, you can find the details here: <a href="https://www.postgresql.org/docs/9.2/sql-copy.html">https://www.postgresql.org/docs/9.2/sql-copy.html</a></p><h3>Summary and What’s Next</h3><p>If you followed along, by now you should have some historical weather data loaded into your database table. Of course, this is just the starting point. You can now begin the interesting and enlightening process of analyzing the data to find weather trends, patterns, and relationships with other data. If you have other data such as business transactions, customer details, employee productivity records, etc. you can now learn how your existing data correlates with weather and which specific weather metrics are interesting to your business. You likely want to use a business intelligence tool such as <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-can-i-load-historical-weather-data-into-microsoft-power-bi/">Power BI</a>, <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-to-load-historical-weather-data-into-tableau-desktop/">Tableau</a>, <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-to-add-historical-weather-data-to-qlik-sense/">Qlik</a>, <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-to-load-weather-forecast-data-into-oracle-analytics-desktop/">Oracle Analytics Desktop</a>, <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-to-add-historical-weather-data-to-tibco-spotfire-via-odata-request/">TIBCO Spotfire</a>, or <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-can-i-find-historical-weather-data-for-analysis-in-r/">R Studio</a>. Tools such as these will leverage the power of your database to make finding patterns and correlations easy. The results can then be displayed and analyzed graphically.</p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-to-load-historical-weather-data-into-any-database"><em>https://www.visualcrossing.com</em></a><em> on October 30, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d12cdaead1c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Python and Pandas to join historical weather data to road accident data]]></title>
            <link>https://python.plainenglish.io/how-to-use-python-and-pandas-to-join-historical-weather-data-to-road-accident-data-60468f718422?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/60468f718422</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 03:56:09 GMT</pubDate>
            <atom:updated>2020-07-24T17:39:11.807Z</atom:updated>
            <content:encoded><![CDATA[<p>I am currently investigating the relationship between weather conditions and accidents by using a dataset of road accidents in Fairfax County, Virginia obtained from the <a href="https://www.dmv.virginia.gov/">Virginia Department of Motor Vehicles</a>.</p><p>The first step to perform the analysis is to combine the accident data with the historical weather conditions. In this article, we will discuss how we take the raw accident data and integrate that data with historical weather data.</p><p>As we have over 3000 rows of accident data, we are going to automate the combination of the accident data with the weather data to produce a final dataset that we can use for continued analysis. To do this, we will write a Python script that uses <a href="https://pandas.pydata.org/">Pandas</a> as a way to easily load and process the accident data and combine it with the historical weather data.</p><p>The weather data will be sourced from the <a href="https://www.visualcrossing.com/weather-api">Visual Crossing Weather API</a> that makes it simple to load accurate weather history observations for the time and locations specified in the accident reports.</p><h4>Source Accident Data</h4><p>The source accident data we will be using includes accident data for the first half of 2020 in Fairfax County, Virginia, USA. The data includes the location of the accident expressed as a latitude, longitude location and the date and time of the accident. In addition, the data includes various attributes about the accident such as amount damage and whether or not there were any injuries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*m2JvRsOhoNrpRFRenqXdUA.png" /></figure><h4>Historical weather data lookup</h4><p>To look up the weather observations for each row of accident data, we need the location, which we can obtain using the latitude and longitude columns, and the date and time. The Weather API provides <a href="https://www.visualcrossing.com/resources/documentation/weather-api/requesting-sub-hourly-weather-data-using-the-weather-api/">sub-hourly</a> temporal resolution from many weather stations, so we can look up the weather conditions very accurately.</p><p>In addition to the weather, we will also request the sunset and sunrise times, so we can determine if there is relationship to the state of the sun compared to accidents.</p><p>The following represents the weather API query to look up the weather for our first row of accident data above:</p><pre>https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?&amp;contentType=json&amp;aggregateMinutes=15&amp;unitGroup=us&amp;includeAstronomy=true&amp;collectStationContributions=true&amp;key=API_KEY&amp;startDateTime=2020-01-16T00:11:00&amp;endDateTime=2020-01-16T00:11:00&amp;locations=38.94800,-77.30635</pre><p>We specify the location using the locations parameter: <em>&amp;locations=38.94800,-77.30635</em></p><p>The date and time using the start and end date time parameters: <em>&amp;startDateTime=2020–01–16T00:11:00&amp;endDateTime=2020–01–16T00:11:00</em></p><p>We then include a set of parameters to request data at the 15 minute resolution and to include astronomy details (sunrise and sunset in this case): <em>&amp;aggregateMinutes=15&amp;unitGroup=us&amp;includeAstronomy=true</em></p><p>For more information on the parameters above, see the <a href="https://www.visualcrossing.com/resources/documentation/weather-api/weather-api-documentation/">Weather API Documentation</a>.</p><p>The result of the weather API request is a simple <a href="https://www.visualcrossing.com/resources/documentation/weather-api/weather-api-json-result-structure/">JSON </a>structure that includes the requested weather data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*on_7nqLzI_-SoUeP.png" /></figure><p>We can use this data to select the weather data values that we are interested in investigating.</p><h4>Using Python and Pandas to request weather data in bulk</h4><p>As we have many rows of accident data, rather than manually look up the data for each row, we will automate the data retrieval. This will also position the next phase of research to analyze if any weather or astronomical conditions correlate with the accident.</p><p>We will use a python script to perform the automation. Within the script, we will use a Pandas DataFrame to load and manipulate the data. This will help position the script to both store the joined accident-weather dataset and also be read for more sophisticated analysis of the data.</p><h4>The Python script</h4><p>We will use the following libraries to help simplify the Python script:</p><pre>import pandas as pd<br>import math<br>import datetime<br>import urllib.request<br>import json</pre><p>Pandas will be used for the DataFrame and the math and datetime libraries will be used for some simple error checking, parsing and transformation. The urllib and json libraries will be used to submit and parse the weather API requests.</p><p>We first use the pandas library to load the accident data from CSV file into a DataFrame :</p><pre>raw_accident_data=pd.read_csv(&#39;Motor_Vehicle_Collisions_FairfaxCountyVa.csv&#39;)</pre><p>In our first test we will create an array that combines the crash weather data. Here is the empty output structure:</p><pre>records=[] labels = [&#39;Crash Date&#39;, &#39;GPS Latitude&#39;, &#39;GPS Longitude&#39;,&#39;Document Number&#39;,&#39;Crash Type&#39;,&#39;temp&#39;,&#39;precip&#39;,&#39;wspd&#39;,&#39;sunrise&#39;,&#39;sunset&#39;,&#39;stationinfo&#39;]</pre><p>Now we have the input data loaded and our output structured defined, we can iterate through each for of the data to load the weather data:</p><pre>for i, row in raw_accident_data.iterrows(): <br><br>    latitude=row[&#39;GPS Latitude&#39;]<br>    longitude=row[&#39;GPS Longitude&#39;]<br>    documentNumber=row[&#39;Document Number&#39;]<br>    crashType=row[&#39;Crash Type&#39;]<br>    datetimeStr=row[&#39;Crash Date&#39;] <br><br>    if math.isnan(latitude) or math.isnan(longitude) or (latitude==0 and longitude==0):<br>        print(&quot;Bad latlon {},{}&quot;.format(latitude,longitude))<br>        continue<br><br>    if datetimeStr&lt;start_date:<br>        print(&quot;Bad date {}&quot;.format(datetimeStr))<br>        continue<br><br>    try:<br>        date_time=datetime.datetime.strptime(datetimeStr, &#39;%m/%d/%Y %H:%M&#39;)<br>    except ValueError:<br>        print(&quot;Bad date format {}&quot;.format(datetimeStr))<br>        continue<br><br>    latitude=&#39;{:.5f}&#39;.format(latitude)<br>    longitude=&#39;{:.5f}&#39;.format(longitude)</pre><p>In the first part of the loop we read the core information from the Pandas dataframe row. We then perform checks to make sure the input data is complete and useful. This includes ensuring the latitude, longitude and date time are valid. Finally, we ensure that the latitude has five decimal places.</p><p>Note that we parse the date time into an actual date time value so that we can then reformat it for use in the query in the next step.</p><p>We can now submit the Weather API request for the row values we have read above:</p><pre>query_params = &#39;&amp;contentType=json&amp;aggregateMinutes=15&amp;unitGroup=us&amp;includeAstronomy=true&amp;collectStationContributions=true&amp;key={}&amp;startDateTime={}&amp;endDateTime={}&amp;locations={},{}&#39;<br><br>query_params=query_params.format(weather_api_key, date_time.isoformat(), date_time.isoformat(),latitude,longitude)<br>  <br>try:<br>   response = urllib.request.urlopen(weather_api_endpoint <br>                                      +&quot;?&quot;+ query_params)<br>   data = response.read()<br>except Exception:<br>  print(&quot;Error reading from {}&quot;<br>          .format(weather_api_endpoint +&quot;?&quot;+ query_params))<br>  continue<br>    <br>weatherData = json.loads(data.decode(&#39;utf-8&#39;)) <br><br>errorCode=weatherData[&quot;errorCode&quot;]<br>                   if &#39;errorCode&#39; in weatherData else 0<br>    <br>if (errorCode&gt;0):<br>   print(&quot;Error reading from errorCode {}, error={}&quot;<br>              .format(weather_api_endpoint +<br>                  &quot;?&quot;+ query_params, errorCode))<br>  continue</pre><p>We insert the row parameters into the preformatted query parameters string. Then we submit the Weather API request.</p><p>We parse the request using the JSON library into a variable called ‘weatherData’. We check that no error code was returned (if it was then we continue to the next row).</p><p>We are now ready to extract the weather data we are interested in.</p><pre>locations=weatherData[&quot;locations&quot;]<br> for locationid in locations:  <br>    location=locations[locationid]<br>    for value in location[&quot;values&quot;]:<br>       records.append((date_time.isoformat(),<br>                                    latitude,<br>                                   longitude,<br>                              documentNumber,<br>                                   crashType,<br>                               value[&quot;temp&quot;],<br>                             value[&quot;precip&quot;],<br>                               value[&quot;wspd&quot;],<br>                            value[&quot;sunrise&quot;],<br>                             value[&quot;sunset&quot;],<br>                       value[&quot;stationinfo&quot;] ))</pre><p>The json is a collection of locations which in turn include a collection of weather data values. In our case there is simple a single location (for the latitude, longitude we requested for the crash location) and a single value (or the time of the crash).</p><p>We can therefore create a single row of output data from the input pieces of data plus the temperature (“temp”), precipitation (“precip”), wind speed (“wspd”), the sunset and sunrise and also the “stationinfo”.</p><p>The station info tells us exactly where the weather data was found. This will be useful for tracing the data and consistency checking.</p><p>The final part of the script in this first step is to save the data as a CSV that includes the crash and weather data.</p><pre>output_df = pd.DataFrame.from_records(records, columns=labels) output_df.to_csv(&#39;output.csv&#39;, index=False)</pre><p>We use the Pandas data frame again to perform this conversion and save to disk. Here’s what the output looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*KWNb3Vk8JKm_AEdhStpoMw.png" /></figure><h4>Closing thoughts</h4><p>We are now ready to perform analysis on the data to see how weather affects accident events.</p><p>If you have data that you would like to combine with weather data to perform analysis and investigation, check out the <a href="https://www.visualcrossing.com/weather/weather-data-services">Weather Data Services page</a> where you can sign for a free trial, view and download historical and forecast weather data and even build Weather API queries like the ones we have used in this example. You can also see how to include weather data in <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-can-i-load-historical-weather-data-into-microsoft-power-bi/">Power BI</a>, <a href="https://www.visualcrossing.com/resources/documentation/weather-api/how-to-load-weather-data-into-microsoft-excel-using-a-web-query-data-connection/">Microsoft Excel</a>, <a href="https://www.visualcrossing.com/resources/blog/how-to-import-weather-data-into-mysql/">MySQL </a>or any <a href="https://www.visualcrossing.com/resources/blog/how-to-load-historical-weather-data-using-python-without-scraping/">programming language</a>.</p><p>If you have any questions or comments, please post them below.</p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/resources/documentation/weather-api/how-to-use-python-and-pandas-to-join-historical-weather-data-to-road-accident-data/"><em>https://www.visualcrossing.com</em></a><em> on July 15, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60468f718422" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-to-use-python-and-pandas-to-join-historical-weather-data-to-road-accident-data-60468f718422">How to use Python and Pandas to join historical weather data to road accident data</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate recent weather history data retrieval using Microsoft Power Query]]></title>
            <link>https://awigmore.medium.com/automate-recent-weather-history-data-retrieval-using-microsoft-power-query-fb7eb3c350b6?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb7eb3c350b6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[weather-api]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 03:57:39 GMT</pubDate>
            <atom:updated>2020-05-01T13:08:29.396Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous articles about integrating Weather History data into <a href="https://www.visualcrossing.com/resources/documentation/weather-data-tutorials/how-can-i-load-historical-weather-data-into-microsoft-power-bi/">Power BI</a> and <a href="https://www.visualcrossing.com/resources/documentation/weather-data-for-excel-and-google-sheets/parameter-based-web-queries-in-excel/">Microsoft Excel</a>, we have used the Visual Crossing Weather API to retrieve historical weather data. In this article we discuss how to make those weather data queries automatically read the latest weather conditions using Microsoft Power Query.</p><p>If you would like to see the full example query in action within Microsoft Power BI, <a href="https://github.com/visualcrossing/WeatherApi/raw/master/PowerQuery/DynamicHistoryPull.pbix">download our sample Power BI report</a>.</p><h3>The weather data service request</h3><p>A typical <a href="https://www.visualcrossing.com/weather-api">Visual Crossing Weather API</a> history service request looks like the following request:</p><pre><a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?aggregateHours=24&amp;shortColumnNames=false&amp;contentType=csv&amp;unitGroup=uk&amp;key=YOUR_KEY&amp;locations=Hereford,UK&amp;startDateTime=2020-04-01T00:00:00&amp;endDateTime=2020-04-15T00:00:00">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?aggregateHours=24&amp;shortColumnNames=false&amp;contentType=csv&amp;unitGroup=uk&amp;key=YOUR_KEY&amp;locations=Hereford,UK&amp;startDateTime=2020-04-01T00:00:00&amp;endDateTime=2020-04-15T00:00:00</a></pre><p>For more information on how this request has been created, see our <a href="https://www.visualcrossing.com/resources/documentation/weather-api/weather-api-documentation/">Weather API documentation</a>.</p><p>In the above request, the date range for our historical weather data will be fixed. The weather data will start on April 1st and finish on April 15th 2020. But what happens if we want our Power BI Report or Excel worksheet to automatically refresh and reflect the last week or month of weather observations rather than a fixed date?</p><p>We can easily achieve this by using <a href="https://powerquery.microsoft.com/en-us/">Microsoft Power Query</a>. Power Query is used behind the scenes in both of the articles above. Now, to make the query dynamic, we will modify the query and create dynamic start and end dates.</p><blockquote><em>Power Query is also used in our extensive </em><a href="https://www.visualcrossing.com/resources/blog/weather-excel-workbooks/"><em>Weather Workbooks</em></a><em> series. If you are looking to see how error handling and data transformations can be made on the weather, check out that series.</em></blockquote><h3>Adding dynamic dates to the query</h3><p>In the query above, the dates are fixed. We will need to make the query dynamic:</p><pre>https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?aggregateHours=24&amp;shortColumnNames=false&amp;contentType=csv&amp;unitGroup=uk&amp;key=KPYNQ6AWUDJE9AFERDCHJHSXK&amp;locations=Hereford,UK&quot; &amp; &quot;&amp;startDateTime=&quot; &amp; StartDateText &amp; &quot;&amp;endDateTime=&quot; &amp; EndDateText</pre><p>Note how the last line joins together two parameters ‘StartDateText’ and ‘EndDateText’. We will populate these parameters with the text.</p><p>The logic to populate the two parameters will be as follows:</p><ol><li>Look up the current date and time.</li><li>Round the current date and time to the following midnight.</li><li>Find the start date by subtracting 14 days from the end date found in step 2.</li><li>Format the start and end dates found in steps 1–3 for insertion into the weather API request.</li><li>Insert the formatted start and end dates into the weather API request.</li></ol><h4>Step 1 — Look up the current date and time</h4><p>To look up the current date and time we can use the Power Query DateTime.FixedLocalNow method.</p><pre>Now=DateTime.Date(DateTime.FixedLocalNow()),</pre><h4>Step 2 — Round the current date and time to the following midnight</h4><p>The Weather API requests are inclusive of the start date and exclusive of the end date. Therefore to include the current date, we need to have the end date end at midnight of the following day.</p><p>We can do that by creating a new date time that contains only the date parts of the ‘Now’ date time. This creates a day time value of midnight on the current date. From here, we can add one day to the date to create our end date.</p><pre>MidnightNow=#datetime(Date.Year(Now), Date.Month(Now), Date.Day(Now),0,0,0), //midnight on today&#39;s date EndDate=Date.AddDays(MidnightNow,1) //midnight on tomorrow&#39;s date</pre><h4>Step 3 — Find the start date by subtracting 14 days from the end date</h4><p>Now we can find the start date by subtracting as many dates as we would like from the end date. In our case we’ll look back 14 days. Note that we add a negative number to subtract days.</p><pre>StartDate=Date.AddDays(EndDate,-14),</pre><h4>Step 4 — Format the start and end dates</h4><p>Finally we need to convert the start and end date times to text values that we can include in our weather API call. The API uses a format similar to the ISO 8601 date time format:</p><pre>StartDateText=DateTime.ToText(StartDate, &quot;yyyy-MM-ddTHH:mm:ss&quot;),<br>EndDateText=DateTime.ToText(EndDate, &quot;yyyy-MM-ddTHH:mm:ss&quot;),</pre><h4>Step 5 — Insert the formatted start and end dates into the weather API request</h4><p>We can now insert the start and end dates into the Weather API request URL:</p><pre><a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?</a> aggregateHours=24&amp;shortColumnNames=false&amp;contentType=csv&amp;unitGroup=uk&amp;key=KPYNQ6AWUDJE9AFERDCHJHSXK&amp;locations=Hereford,UK&quot; &amp; &quot;&amp;startDateTime=&quot; &amp; StartDateText &amp; &quot;&amp;endDateTime=&quot; &amp; EndDateText</pre><p>The remainder of the Power Query code can remain the same. This code will request the CSV data, extract the headers and configure the data types.</p><h3>The full power query code</h3><p>Here is the full Power Query code to look up the historical weather data. Note that must enter a valid API key for this to function correctly.</p><pre>let Now=DateTime.Date(DateTime.FixedLocalNow()), MidnightNow=#datetime(Date.Year(Now), Date.Month(Now), Date.Day(Now),0,0,0), EndDate=Date.AddDays(MidnightNow,1), StartDate=Date.AddDays(EndDate,-14), StartDateText=DateTime.ToText(StartDate, &quot;yyyy-MM-ddTHH:mm:ss&quot;), EndDateText=DateTime.ToText(EndDate, &quot;yyyy-MM-ddTHH:mm:ss&quot;), WeatherAPIURL=&quot;https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?aggregateHours=24&amp;shortColumnNames=false&amp;contentType=csv&amp;unitGroup=uk&amp;key=YOUR_KEY&quot; &amp; &quot;&amp;locations=Hereford,UK&quot; &amp; &quot;&amp;startDateTime=&quot; &amp; StartDateText &amp; &quot;&amp;endDateTime=&quot; &amp; EndDateText, Source = Csv.Document(Web.Contents(WeatherAPIURL),[Delimiter=&quot;,&quot;, Encoding=65001, QuoteStyle=QuoteStyle.None]), #&quot;Promoted Headers&quot; = Table.PromoteHeaders(Source, [PromoteAllScalars=true]), #&quot;Changed Type&quot; = Table.TransformColumnTypes(#&quot;Promoted Headers&quot;,{{&quot;Address&quot;, type text}, {&quot;Date time&quot;, type date}, {&quot;Minimum Temperature&quot;, type number}, {&quot;Maximum Temperature&quot;, type number}, {&quot;Temperature&quot;, type number}, {&quot;Dew Point&quot;, type number}, {&quot;Relative Humidity&quot;, type number}, {&quot;Heat Index&quot;, type text}, {&quot;Wind Speed&quot;, type number}, {&quot;Wind Gust&quot;, type number}, {&quot;Wind Direction&quot;, type number}, {&quot;Wind Chill&quot;, type number}, {&quot;Precipitation&quot;, type number}, {&quot;Precipitation Cover&quot;, type number}, {&quot;Snow Depth&quot;, type text}, {&quot;Visibility&quot;, type number}, {&quot;Cloud Cover&quot;, type number}, {&quot;Sea Level Pressure&quot;, type number}, {&quot;Weather Type&quot;, type text}, {&quot;Latitude&quot;, type number}, {&quot;Longitude&quot;, type number}, {&quot;Resolved Address&quot;, type text}, {&quot;Name&quot;, type text}, {&quot;Info&quot;, type text}, {&quot;Conditions&quot;, type text}}) in #&quot;Changed Type&quot;</pre><p>If you would like to see the full example query in action within Microsoft Power BI, <a href="https://github.com/visualcrossing/WeatherApi/raw/master/PowerQuery/DynamicHistoryPull.pbix">download our sample Power BI report</a>.</p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/resources/documentation/weather-api/automate-recent-weather-history-data-retrieval-using-microsoft-power-query/"><em>https://www.visualcrossing.com</em></a><em> on April 15, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb7eb3c350b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to import weather data into a MySQL database]]></title>
            <link>https://awigmore.medium.com/how-to-import-weather-data-into-a-mysql-database-4e06397d460b?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e06397d460b</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Fri, 13 Mar 2020 20:14:29 GMT</pubDate>
            <atom:updated>2020-03-13T20:14:29.251Z</atom:updated>
            <content:encoded><![CDATA[<p>How to import weather forecast data and historical weather data into a MySQL database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*AL08vkA49fmP7YMg.jpg" /></figure><p>In this article, we are going to import weather data into a MySQL database. In addition to setting up the database tables, we will demonstrate techniques to import both historical weather data and weather forecast data. We will include the ways to retrieve the weather data and how to set up a script so the weather data can be refreshed on a schedule.</p><h3>Weather data provider</h3><p>In this article, we are going to use a <a href="https://www.visualcrossing.com/weather-api">Weather API</a> that supports retrieving weather data as a web service. The data includes historical weather observations and weather forecast data and is available in a range of formats include CSV and JSON so the data is perfect for importing into MySQL. There is also a free API plan available.</p><p>If you don’t have an account, you can simply sign up for a free trial for <a href="https://www.visualcrossing.com/weather/weather-data-services">Weather Data Services</a> to obtain access. For help on getting started with the Weather Data Services page, see <a href="https://support.visualcrossing.com/hc/en-us/articles/360037279172-Getting-Started-With-Weather-Data-Services">Getting Started With Weather Data Service</a>.</p><h3>Setting up the MySQL Database</h3><p>Our first step is to create a MySQL database and create an empty table within the new database where the weather data will reside. In this example we are using MySQL version 8. We won’t be doing anything particularly complex however and so other versions should work as well.</p><p>First we set up a new database schema for holding the weather data. We have named our new schema ‘weather_data_schema’. Within this schema we have created a single table called ‘weather_data’. Both weather history data and weather forecast data hold the same fundamental data, and so we can use the same table for both history and forecast results. In more advanced cases, different tables may be useful to include some of the data that specific to historical data or forecast data.</p><p>To create the table, we use the following script. To make things simple, we have named our columns with the same column name as the incoming weather data variable names.</p><pre>CREATE TABLE `weather_data` (<br>  `address` varchar(256) DEFAULT NULL,<br>  `latitude` float DEFAULT NULL,<br>  `longitude` float DEFAULT NULL,<br>  `datetime` datetime DEFAULT NULL,<br>  `maxt` float DEFAULT NULL,<br>  `mint` float DEFAULT NULL,<br>  `temp` float DEFAULT NULL,<br>  `precip` float DEFAULT NULL,<br>  `wspd` float DEFAULT NULL,<br>  `wdir` float DEFAULT NULL,<br>  `wgust` float DEFAULT NULL,<br>  `pressure` float DEFAULT NULL<br>) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;</pre><p>We now have a database with an empty weather data table. We are reading to load some weather data!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*erpfBHchQ0rrb2Fe.png" /></figure><h3>Loading the weather data into MySQL using Python</h3><p>As we mentioned above, we are going to use a weather web service called the Visual Crossing Weather API to retrieve the weather data we are interested in. In our first example, we are going to create a Python script that we can run at regular intervals to retrieve the weather forecast data.</p><h4>Prerequisites</h4><p>Our Python script was written in <a href="https://www.python.org/">Python 3.8.2</a>. In addition to the core Python, we installed the <a href="https://dev.mysql.com/downloads/connector/python/">MySQL Connector for Python</a>. Finally, we had some errors about missing libraries for dns so we had to install <a href="https://pypi.org/project/dnspython/">DNSPython</a>. This last dependency may not be required when you create script.</p><p>Here’s the full list of import statements in our script</p><pre>import urllib.request <br>import json <br>import mysql.connector <br>from datetime import date, datetime, timedelta</pre><h4>Script part one — setting up the input parameters</h4><p>Our Python script is split into two parts. The first part downloads the weather data and the second part inserts the weather data into the MySQL database table. The weather data is retrieved using a RESTful weather api. This means that we simply have to create a web query within the Python script and download the data.</p><p>The first part of the sets up some variables to customize the weather data that is entered. In your script you may want to extract these as parameters to the script.</p><pre># This is the core of our weather query URL<br>BaseURL = &#39;<a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/&#39;">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/&#39;</a></pre><pre>ApiKey=&#39;INSERT_YOUR_KEY_HERE&#39;<br>#UnitGroup sets the units of the output - us or metric<br>UnitGroup=&#39;us&#39;</pre><pre>#Locations for the weather data. Multiple locations separated by pipe (|)<br>Locations=&#39;Washington,DC&#39;</pre><pre>#FORECAST or HISTORY<br>QueryType=&#39;FORECAST&#39;</pre><pre>#1=hourly, 24=daily<br>AggregateHours=&#39;24&#39;</pre><pre>#Params for history only<br>StartDate = &#39;&#39;<br>EndDate=&#39;&#39;</pre><p>As the code demonstrates, you should enter your API key to set the value of the variable ‘ApiKey’. You can also switch the query between forecast and history weather data. The Locations parameter is a pipe (|) separated list of location addresses, partial address or longitude,latitude values for the weather data retrieval. For more information on the full set of Weather API parameters, see the <a href="https://www.visualcrossing.com/weather-api-documentation">Weather API documentation</a>.</p><h4>Script part two — downloading the weather data</h4><p>The next section of code creates the Weather API request from the parameters, submits the request to the server and then parses the result.</p><pre># Set up the specific parameters based on the type of query<br>if QueryType == &#39;FORECAST&#39;:<br>    print(&#39; - Fetching forecast data&#39;)<br>    QueryParams = &#39;forecast?aggregateHours=&#39; + AggregateHours + &#39;&amp;unitGroup=&#39; + UnitGroup + &#39;&amp;shortColumnNames=true&#39;<br>else:<br>    print(&#39; - Fetching history for date: &#39;, DateParam)</pre><pre># History requests require a date.  We use the same date for start and end since we only want to query a single date in this example<br>    QueryParams = &#39;history?aggregateHours=&#39; + AggregateHours + &#39;&amp;unitGroup=&#39; + UnitGroup +&#39;&amp;startDateTime=&#39; + StartDate + &#39;T00%3A00%3A00&amp;endDateTime=&#39; + EndDate + &#39;T00%3A00%3A00&#39;</pre><pre>Locations=&#39;&amp;locations=&#39;+Locations</pre><pre>ApiKey=&#39;&amp;key=&#39;+ApiKey</pre><pre># Build the entire query<br>URL = BaseURL + QueryParams + Locations + ApiKey+&quot;&amp;contentType=json&quot;</pre><pre>print(&#39; - Running query URL: &#39;, URL)<br>print()</pre><pre>response = urllib.request.urlopen(URL)<br>data = response.read()<br>weatherData = json.loads(data.decode(&#39;utf-8&#39;)))</pre><p>In this case, we are using the JSON result to retrieve the weather data for easy parsing when we insert the data into MySQL. The output JSON is formatted as follows. The top-level includes locations and columns information. Each location’s weather data is found as a individual location instance. Below each location is an array of values. These values correspond to the individual time periods in the requested data so will be hourly or daily in our example. For full information about the returned weather data, see the <a href="https://www.visualcrossing.com/weather-data-documentation">weather data documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*X5mttgJZvWhSBYDN.png" /></figure><h4>Script part three — insert the weather data into our MySQL table</h4><p>Our next part of the script actually inserts the weather data into the database table. Here’s the code to set up the connection and sets up the SQL statements. Note that in this example we simply empty any existing data within the weather data table. There’s no reason to do that if you would prefer to build up a record of the weather data.</p><pre>print( &quot;Connecting to mysql database&quot;)<br>#connect to the database. Enter your host, username and password<br>cnx = mysql.connector.connect(host=&#39;127.0.0.1&#39;,<br>    user=&#39;YOUR_USERNAME&#39;,<br>    passwd=&#39;YOUR_PASSWORD&#39;,<br>    database=&#39;weather_data_schema&#39;)</pre><pre>cursor = cnx.cursor()</pre><pre># In this simple example, clear out the existing data in the table</pre><pre>delete_weather_data=(&quot;TRUNCATE TABLE `weather_data_schema`.`weather_data`&quot;)<br>cursor.execute(delete_weather_data)<br>cnx.commit()</pre><p>The next part of the script then iterates through the locations and then the weather data values within the locations. The code creates statement to perform the insert. Then during the value loop it creates a parameters from the weather data.</p><pre># Create an insert statement for inserting rows of data <br>insert_weather_data = (&quot;INSERT INTO `weather_data_schema`.`weather_data`&quot;<br>                &quot;(`address`,`latitude`,`longitude`,`datetime`,`maxt`,`mint`,`temp`,`precip`,`wspd`,`wdir`,`wgust`,`pressure`)&quot;<br>                &quot;VALUES (%(address)s, %(latitude)s, %(longitude)s, %(datetime)s, %(maxt)s,%(mint)s, %(temp)s, %(precip)s, %(wspd)s, %(wdir)s, %(wgust)s, %(pressure)s)&quot;)<br>    <br># Iterate through the locations<br>locations=weatherData[&quot;locations&quot;]<br>for locationid in locations:  <br>    location=locations[locationid]<br>    # Iterate through the values (values are the time periods in the weather data)<br>    for value in location[&quot;values&quot;]:<br>        data_wx = {<br>        &#39;address&#39;: location[&quot;address&quot;],<br>        &#39;latitude&#39;: location[&quot;latitude&quot;],<br>        &#39;longitude&#39;: location[&quot;longitude&quot;],<br>        &#39;datetime&#39;: datetime.utcfromtimestamp(value[&quot;datetime&quot;]/1000.),<br>        &#39;maxt&#39;:  value[&quot;maxt&quot;] if &#39;maxt&#39; in value else 0,<br>        &#39;mint&#39;: value[&quot;mint&quot;] if &#39;mint&#39; in value else 0,<br>        &#39;temp&#39;: value[&quot;temp&quot;],<br>        &#39;precip&#39;: value[&quot;precip&quot;],<br>        &#39;wspd&#39;: value[&quot;wspd&quot;],<br>        &#39;wdir&#39;: value[&quot;wdir&quot;],<br>        &#39;wgust&#39;: value[&quot;wgust&quot;],<br>        &#39;pressure&#39;: value[&quot;sealevelpressure&quot;]<br>        }<br>        cursor.execute(insert_weather_data, data_wx)<br>        cnx.commit()<br>               <br>cursor.close() <br>cnx.close()<br>print( &quot;Database connection closed&quot;)</pre><pre>print( &quot;Done&quot;)</pre><p>After the script executes, we can see the data if we fresh the data inside MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*MQy1zSZ7OaAfCLjG.png" /></figure><h3>Next steps</h3><p>If you would like the full code, you can found it in our <a href="https://github.com/visualcrossing/WeatherApi/blob/master/python_samples/weather_data_loading_mysql.py">Github repository</a>. In this article, we’ve seen how easy it is to insert weather data into a database such as MySQL. Do you have questions? Please ask below!</p><p>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/blog/how-to-import-weather-data-into-mysql"><em>https://www.visualcrossing.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e06397d460b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Find Weather Data for your next Data Science Project]]></title>
            <link>https://awigmore.medium.com/how-to-find-weather-data-for-your-next-data-science-project-4443616a7a96?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4443616a7a96</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Thu, 12 Mar 2020 19:28:20 GMT</pubDate>
            <atom:updated>2020-03-12T19:28:20.921Z</atom:updated>
            <content:encoded><![CDATA[<p>How to Find Weather Data for Your Next Data Science Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wVvizuO6fXTDFbbr.jpg" /></figure><p>The use of weather data in data science is hugely varied and there are applications in all applied verticals. However at the heart of all data science projects are accurate, trustworthy weather datasets. In this article, we’ll explain the types of weather data available for data science, how to get them, how to make sure they are trustworthy and finally how to incorporate the data into your project so that you can gain the maximum benefit and insight.</p><p>Many data science projects involve sourcing raw data to complete the project. Whether the task is data visualization, data analysis, machine learning or other data science activity, all projects start with at least one set of data. If your task involves analyzing or visualizing the weather itself, just a source of weather data may be enough. If your project is to try to analyze how another set of data is influenced or correlates to weather and climate patterns, then you’ll need a dataset that supports accurately joining the data together. If you also want to make predictions, then you’ll need a source of weather forecast data.</p><h3>Types of Weather Data — Weather Forecast &amp; Historical Weather</h3><p>Before we dive into the details of how to obtain and use weather data, it’s worth reviewing the types of weather data you will find and how they are typically used.</p><h4>Historical weather data</h4><p>Around the world, tens of of thousands of weather stations are continuously monitoring the weather. These individual weather stations provide weather history observations that can be used as the input to a weather forecast or as a record of the weather for us to analyze in our own work. The weather stations report at regular intervals and include weather elements such as temperature, precipication (rain, snow etc), wind, pressure and possible many more weather variables.</p><h4>Historical weather summaries and climate data</h4><p>Historical and climate summaries are simply the aggregation of the raw historical weather observation data to provide a picture of what the typical weather for a location has been. For example, we can take many years of historical weather data to calculate that the average temperature in Paris, France for January is 8C/46F. On any given January day the temperature may well be much colder or warmer than 8C but the long term climate average is 8C. Such historical weather summaries can be calculated across years, months, weeks and even days to help create a ‘typical’ weather picture for a location. They can also be used to give a picture of the possible weather extremes by identifying the highest and lowest values of any particular weather metric. For the case of Paris, France we can see that the highest temperature is 16C/61F and the lowest maximum temperature recorded is a chilly -6C/21F.</p><h4>Weather forecast data</h4><p>The last type of weather data available is the weather forecast. This provides a detailed prediction of how the weather will behave over the coming days. Weather forecasts typically range from three to 15 days out with the first seven days being the most accurate. Multiple organizations create weather forecasts which all have their own strengths and weaknesses. The most accurate weather forecast data will combine the output from multiple forecast models to provide the best estimate forecast.</p><h3>Ensuring the Weather Data is suitable for Data Science</h3><p>Weather data for data science needs to achieve a number of goals. Firstly, the data must be accurate and complete of course. In addition to being in the trustworthy, the data must be in a format that can be used in our chosen Data Science tool, be it R, Excel a database or a custom Python script. Let’s first look at making sure the weather data is complete and accureate. For weather data, “completeness” is required geographically (there is data nearby to the locations I’m investigating) and temporally (there is accurate data for the date and time that I’m interested in).</p><h4>Spatial and temporal resolution</h4><p>One of the most important features of the weather data is that it is includes enough spatial and temporal resolution. What does this mean? For historical data it means that it’s necessary to find a source of weather data that is close enough to the point of interest to be considered accurate. If the weather station is too far away from the target location, it is likely that the weather data will not be correct for the location we are analyzing.</p><p>Unfortunately there are a limited number of weather stations so it’s necessary to be careful if you load weather history records by simply using the ‘closest’ weather station. It’s better to look at all close by weather stations and combine the results of the weather stations into the best estimate for the location of interest. For example if I am interested in the weather data for Fairfax, Virginia, there are multiple weather stations nearby — Washington Dulles Airport, Washington National Airport and multiple other stations. They are all close, so which should I trust? The answer is to trust all of the stations! By doing this, we validate that we are using the most representative weather values for the data. This technique helps eliminate localized effects such as Washington National Airport tending to report warmer temperatures because of its proximity to the warm Potomac River.</p><p>We must also check that the data includes enough day and time accuracy to allow it to be analyzed effectively. Weather data for data science that will be compared to another data set such as business performance data typically requires that there is at least hourly weather data available so that any time-of-day analysis can be performed accurately. It is not possible to analyze hourly business data if the weather data is only reported as a daily summary — rain at night often has no bearing on activities during the daytime.</p><h4>Error checking and observation completeness</h4><p>Another problem with historical data is that weather stations don’t report the weather occasionally due to equipment failure, planned outages or other causes. Using multiple stations helps mitigate this problem by being able to fall back to alternative weather stations if other stations did not report certain hourly records.</p><p>The final part of the historical data validation is to identify errors in the weather station observations. Unfortunately some weather observations include errors in addition to omissions. When using weather observations within data science applications, it’s important to have an understanding of whether the data has been analyzed and cleansed. If so what procedures have been followed?</p><h3>Technologies available to import the weather data</h3><p>Once we have identified a reliable source of weather data, we can now prepare to obtain the data so we can integrate it within our data science application. There are a number of typical ways to retrieve weather data.</p><h4>Downloadable data files</h4><p>Some data provides will provide you with weather data in a flat file format. These formats may be in a standard format such as Comma Separated Values (CSV) format. In this case, the data can often be used or imported directly into a Data Science project. Other data providers will provide raw historical data in a format that is not so easily read into normal data science tools. This is typical for raw data from government meteorological departments because weather observation data can be very large. Earth Science have developed data formats such as GRIB and NetCDF to allow such large data volumes to be processed.</p><p>Raw historical weather data sets such as this will generally require pre-processing to be able to use them in a data science project. In addition, most will not include full error checking or the ability to interpolate the observations from multiple nearby weather stations.</p><p>Commercial weather data providers (some of which include a free trial), will often perform additional data processing and formatting that makes the data more easily consumed into a data science project. Data formats can include CSV, JSON or other plain text file format.</p><h4>Weather API for automated data retrieval and loading</h4><p>Downloading weather data and then importing into the database or other application is generally suitable for a small number of data loads. For example importing a fixed amount of historical weather data for analysis with a fixed set of dates. Unfortunately, it is often too restrictive to deal only with a fixed set of weather data. Weather forecasts for example are generally needed to be refreshed at least daily. If the application uses recent weather history, that too can need a regular refresh. The latter can often require an update at least every hour so that the dashboard, visualization or other output is able to display the very latest information.</p><p>To achieve such a frequent data refresh requires an automated procedure to retrieve the weather data and then load it into the application. One of the best ways to do this is via a web service API. Web services use the same technologies as the general world wide web (HTTP and HTTPS network protcols) to transfer the weather data from provider to the client.</p><p>Web services will sometimes use a custom scripting client such as Python, PHP, JavaScript or Java to retrieve the data in JSON, CSV or XML format. After retrieving the data, the script may process the data and then save the data or upload the data into another application for analysis.</p><p>Many applications that are used for Data Science can import data directly from such web services. For example Microsoft Excel, Power BI and many business intelligence applications such as MicroStrategy and Tableau are able to read information from a web service directly. In this case, it’s often useful to have a weather data provider that can supply the weather data in a standard data format such as a CSV so that the application can easily import the data.</p><h4>ODATA</h4><p><a href="https://www.odata.org/">ODATA</a> (short for Open Data Protocol) is a standard form of RESTful web service that some applications such as Excel and SAP Analytics Cloud support. ODATA acts just like a web service except that the exchange format is very formalized so that data science clients know how to consume the data without any modifications. If your application and data provider both support ODATA then this will provide an easy path to importing the weather data into your application.</p><h3>Accurately analyzing weather data</h3><p>We have now found and imported our weather data into the application so we can perform our data science. Now let’s look at the typical data we can expect within a weather data report.</p><p>The typical weather data dataset will include multiple columns such as <a href="https://www.visualcrossing.com/weather-data-documentation">temperature, precipitation and wind speed etc</a>. If the dataset is using a short time period for each item of data such as an hourly weather forecast or hourly historical observations, then not a lot of post processing will occur on the dataset that is imported. However if the data is aggregated to summarize a day, month or year then multiple weather data observations are aggregated into a single report. There are different ways for to happen and it’s important to understand what a particular aggregated weather variable value is obtained.</p><p>Temperature is typically aggregated in three ways — the maximum temperature, minimum temperature and the arithmetic mean of the temperature. The mean temperature can be the mean of all hourly values or the average of the maximum and minimum values. In a typical day, the maximum temperature often occurs in the afternoon and therefore simply reporting the maximum temperature is a good substitute for the overall temperature of day. In some circumstances, maximum temperature does not occur in the afternoon such as when an colder or warmer air masses are moving through a location. In these cases, using the maximum daily temperature to compare against business performance may not produce accurate analysis and results. It is generally better to analyze temperature at the hourly level.</p><p>For some applications it is necessary understand more about the maximum and minimum temperature when investigating the typical weather for a time and location. For example, consider the normal temperature for a location in January. We would like to understand the normal maximum temperature (mean maximum temperature) plus also the possible variability. What temperature range do 80% of the days fall between? What is the maximum maximum or minimum maximum temperature possible at this location? The maximum temperature is a good guide to the typical weather at a location, particularly when additional statistical values are considered so a full understanding of the typical temperature and the variability is understood.</p><p>Rainfall is typically summed over the aggregation period. The <a href="https://www.visualcrossing.com/blog/what-is-precipitation-coverage">precipitation coverage</a>, the amount of time the rain fell for, is often as important a driver for business metrics as the amount of rain that falls. A short, sharp but heavy thunderstorm at the end of the day in Miami, Florida may well have less impact on tourist activities than a longer but lighter all day light rain. However the former may well produce significantly more rainfall and therefore look worse in the daily weather observation data.</p><h3>Sources of Weather Data</h3><p>Visual Crossing <a href="https://www.visualcrossing.com/weather-data">Microsoft Data</a> provides historical weather data and weather forecast data available for download, <a href="https://www.visualcrossing.com/weather-api">web service</a> and ODATA access.</p><p>Get started with our free trial and free data tier at <a href="https://www.visualcrossing.com/weather/weather-data-service">Weather Data Services</a>.</p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/blog/how-to-find-weather-data-for-data-science"><em>https://www.visualcrossing.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4443616a7a96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Degree Day Calculator for Microsoft Excel]]></title>
            <link>https://awigmore.medium.com/degree-day-calculator-for-microsoft-excel-d31d51582ba5?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d31d51582ba5</guid>
            <category><![CDATA[degree-days]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[microsoft-excel]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 16:50:16 GMT</pubDate>
            <atom:updated>2020-02-26T16:50:16.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Gss42FbwUnH44vhj.jpg" /></figure><p>Degree Days are a way to help determine how much warmth or cold there has been, typically over a season such as winter, summer or a plant’s growing season. Degree Days are used to determine a building’s typical heating or cooling requirements over a season. They are used in agriculture, farming and gardening to plan plant and crop planting, management and harvest dates. In this blog we provide Microsoft Excel-based degree day calculator that you can download and use.</p><h3>Quick Start</h3><p>To download the interactive Microsoft Excel Degree Days Calculator, please download the file:</p><p><a href="https://github.com/visualcrossing/WeatherApi/raw/master/Excel_Workbooks/DegreeDayCalculator.xlsx">Degree Days Calculator Workbook</a></p><p>To start using the Degree Day Workbook, sign up for a <a href="https://www.visualcrossing.com/weather/weather-data-services">Weather Data Services Product Key</a>. After sign up, you can find your product key under your account details.</p><p>Paste your product key into the Growing Degree Calculator Introduction worksheet. Then enter an address for the location to look up Degree Days. The location address can be a full address, a partial address (such as “city, country” ) or latitude, longitude value (40.2,-75.3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zkFssp66F9YolEt4.png" /></figure><p>Once the data is refreshed, the Heating Degree Days, Cooling Degree Days and Growing Degree Days will be presented in three separate worksheets. You can click between them and modify the degree day parameters on each of them.</p><h3>Using Weather Data to Calculate Degree Days</h3><p>Last year, I wrote a article <a href="https://www.visualcrossing.com/blog/using-microsoft-excel-to-analyze-gardening-weather-part-3-growing-degree-days">Create a Growing Degree Days Calculator in Microsoft Excel</a>. This new calculator expands on that work to include degree day calculators for Heating Degree Days and Cooling Degree days. In addition, the updated calculator makes it easy to get started by removing the need to install an Excel add-in. In this new version, we use the <a href="https://www.visualcrossing.com/weather-api">Weather API</a> to load weather history data and weather forecast data using Excel Web Queries.</p><p>There are three degree calculators included in this workbook.</p><h3>Heating Degree Days</h3><p>Heating Degree Days (HDD) measure the number of effective day when the average daily temperature fell below 65F. At 65F, buildings are expected to turn on their heating when the temperature drops below this point. If the average daily temperature is colder, say 32F, then the building will require more heating. Therefore for for every degree lower than 65, an extra degree is added. A day that has a mean temperature of 60F will have a HDD value of five. A day that has a mean temperature of 32F will have a HDD value of 33.</p><p>The heating degree days can be added up over a season to show the total amount of HDD for that particular season.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9eP5RGhWbMnDk8no.png" /></figure><h3>Cooling Degree Days</h3><p>Cooling Degree Days (CDD) give an indication of how hot a summer is by creating a picture of the amount of cooling required. CDD are calculated in a similar way to heating degree days however they measure the degree days above 65F. For example, a day where the average temperature is 75F will have a cooling degree value of 10F.</p><h3>Growing Degree Days</h3><p>Growing Degree Days (GDD) give a way to manage the planting, management and harvest of a crop on the farm or garden. They use the idea that many species of plants grow and flourish above a minimum temperature. The warmer it is above that temperature then the faster the plant will mature. This is considered a more accurate way to estimate the growth stage of a plant compared to the age of a plant. This approach considers that, assuming other factors such as irrigation are equal, a plant will grow faster if it is warmer. However, at some higher temperature, the plant may not grow faster if it gets warmer.</p><p>If we consider corn, we can say that corn does not grow unless the temperature is at least 50F. Corn will mature faster if the temperature is warmer until 86F when corn reaches its maximum maturation rate. We use 50 as the minimum temperature in the same was a 65F was the minimum for Cooling Degree Days. So if a day has an average temperature of 65, that day will have 15 Growing Degree Days for corn.</p><p>Different crops have different values for the minimum temperature (Tbase) and the maximum temperature (Tmax). Cumulative growing degree days across the growing season can be used to indicate when the crop requires fertilizer or may be ready for harvesting. For example some varieties will reach maturity in around 2000–2500 GDD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8WT5AdNxMGuFlJab.png" /></figure><h3>Details of the Growing Degree Day Calculation</h3><p>The full Growing Degree calculation and Microsoft Excel implementation can be found in <a href="https://www.visualcrossing.com/blog/using-microsoft-excel-to-analyze-gardening-weather-part-3-growing-degree-days">last year’s article</a>. If you are interested in additional weather data for calculating degree days or any other weather climate analysis, check out our <a href="https://www.visualcrossing.com/weather-api">Weather Data</a> platform that provides weather history data, 15-day weather forecast data and climate summaries.</p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/blog/degree-day-calculator"><em>https://www.visualcrossing.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d31d51582ba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a weather forecast report in Power BI]]></title>
            <link>https://awigmore.medium.com/how-to-create-a-weather-forecast-report-in-power-bi-c2a50b867b0e?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2a50b867b0e</guid>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Thu, 13 Feb 2020 15:57:55 GMT</pubDate>
            <atom:updated>2020-02-13T15:57:55.982Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@awigmore/how-to-import-weather-data-into-power-bi-afccdd12c8f0">previous article</a> we described the process to integrate historical weather data into a Power BI Report. In this article we are going to extend those ideas to create a weather forecast report. Here is a sample of what we are going to produce.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuNTi_PvNf1gfAnw0rIZYQ.png" /><figcaption>Weather Forecast Report in Power BI</figcaption></figure><p>The report retrieves the weather forecast data for multiple locations. The user can switch between locations to view the forecast for each location in detail. The report displays the 15-day weather forecast including daily high and low temperature, wind speed and gust, and rainfall and snowfall. Other weather forecast variables are available but we are going to limit ourselves to this set for this example.</p><h3>Populating the weather forecast data</h3><p>The first step in creating our report is to populate the Power BI report with weather forecast data from a weather service capable of providing a direct query connection to Power BI. We will be using the <a href="https://www.visualcrossing.com/weather-data">Visual Crossing Weather Data</a> platform to provide the weather forecast data as their Weather API service provides an easy way to read the weather forecast for multiple locations in a single service call. Visual Crossing also offer an easy way to build data queries directly in the browser so it makes the process easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCUYWQO_gDSLxyPsmk57tg.png" /><figcaption>Weather Forecast in the Browser</figcaption></figure><p>We will not go into the full detail on how to create a query within the Weather Data platform as it fully describe in the <a href="https://medium.com/@awigmore/how-to-import-weather-data-into-power-bi-afccdd12c8f0">previous article</a>. The high level steps are:</p><ol><li>Open the <a href="https://www.visualcrossing.com/weather/weather-data-services">weather data services page</a> (create a free trial account if necessary)</li><li>Enter in your list of locations</li><li>Run the weather forecast directly in the browser to see the data.</li><li>Use the query URL builder to create a URL that we can use to retrieve the same weather forecast data directly in Power BI.</li></ol><p>The final query URL will look like:</p><pre>https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast?&amp;aggregateHours=24&amp;contentType=csv&amp;unitGroup=us&amp;key=YOUR_API_KEY&amp;locations=Miami%2C%20FL%7CNew%20York%2C%20NY%7CLos%20Angeles%2CCA</pre><p>The forecast query is simpler than the historical weather data because there are fewer parameters. We simply need the list of locations and whether the result should be a daily summary forecast or a detailed hourly weather forecast.</p><p>The <strong>aggregateHours </strong>parameter specifies the length of the forecast period — hourly, twice daily or daily. We are looking for a daily weather forecast summary so we use the value of 24 hours. Changing this value to 1 would create an hourly weather forecast.</p><p>The <strong>locations </strong>parameter provides the list of locations for which to look up the weather forecast.The locations parameter can include multiple locations. This is simply performed by concatenating location addresses with the pipe (‘|’) character (if you built the query via the query page then this will be done for you).</p><p>Just as with the weather history data connection, we need to create a parameterized web query connection with Power BI Desktop so that we have a refreshable query for the weather forecast data into Power BI.</p><p>We need just three parameters in the Power BI query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*Oklunp31QxEoiF05vlJlQQ.png" /></figure><p>Note how the location parameter value has been populated with multiple locations.</p><p>The Power Query URL definition includes these parameters in the query definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*ERnJcmTsAOE8vpWMkYmw8w.png" /></figure><p>The preview shows that the multiple location based weather forecast is available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REk-ZeA46vFLSh1gFE-3Jw.png" /></figure><p>When we import data using CSV format such as this, we initially rely on Power Query to automatically identify the column data types (text, number etc). Some weather variables only have data for a small number of the days and so Power Query may not correctly interpret the values as number.</p><p>A good example of this is snowfall. The first 200 rows of the query may well not include snowfall values so Power Query will not guess the column type as numeric. We need to double check the column data types that Power Query guesses and manually correct any data types that were guessed incorrectly. If columns don’t show in Power BI as measures, that is a good hint that the data import did not assign the expected column data type.</p><h3>Building the weather forecast dashboard</h3><p>Now that we have the data, we can start building the dashboard. There are a couple of elements:</p><p><strong>Location slicer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gt7Mm1ygoYEy27UpdV8YVA.png" /></figure><p>The location slicer allows the user to select the location to filter the remainder of the visualizations. We have driven it from the Address field</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*8dwOhgDqlYgl3ftEQe784A.png" /></figure><p><strong>Temperature forecast</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j41ceY5vKlhm0kKt2TWeQw.png" /></figure><p>The temperature forecast is a stacked area chart to illustrate the daily high and low temperatures. By stacking the area like this we provide the user with an easy way to determine not only the temperature extremes but also the spread of temperatures throughout the day.</p><p>We use a stacked area because the stacking gives a clearer indication of the two temperature values. This stack is created by adding a new derived measure to fields. This new measure is the difference between the maximum and minimum temperatures:</p><pre>Max Temp Delta = sum(WeatherForecast[Max Temperature])-sum(WeatherForecast[Min Temperature])</pre><p>By stacking this delta measure on top of the minimum temperature we get a clear separation of the minimum and maximum temperatures.</p><p><strong>Wind and wind gust forecast</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijPdbMyOVgS22KUseZgCZg.png" /></figure><p>The stacked technique is used again to display the wind speed and any additional wind gust. The light pink shows the wind speed (generally defined as the average speed over an amount of time) whereas the dark pink highlights the wind gusts (the wind speed over a short period of time). Again we use a delta to be able to stack the colors like this:</p><pre>Wind Gust Delta = sum(WeatherForecast[Wind Gust])-sum(WeatherForecast[Wind Speed])</pre><p><strong>Precipitation and Snow Forecast</strong></p><p>The final chart shows the precipitation and snow forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QH-hOykswAH3aq_bKtKWoQ.png" /></figure><p>The green values indicate the liquid water amount of any precipitation when melted (rain, snow etc). The dark blue indicate the predicted snow amounts. Therefore when there is only a green value, this indicates rain. When there is a snow forecast there is both a blue bar indicating the amount of snow and a green bar indicating how much liquid water would have fallen if this were rain.</p><p>In this chart, both values are derived directly from the weather forecast Precipitation and Snow fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*-jnmYK5tucoWQoi20jfFGQ.png" /></figure><h3>Refreshing the weather forecast automatically in Power BI</h3><p>Now we have initial weather forecast report so let’s publish it to the web version of Power BI. First we publish to the web version from Power BI desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Uwpu9aQ1lGCk8OtoisA2hw.png" /></figure><p>We have published to “My workspace”. If we look into the datasets, we can see the newly published WeatherForecastDashboard dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eW4Jv9zl0thgWUWBfIJqOQ.png" /></figure><p>The last thing necessary is for the weather forecast data to refresh automatically so that whenever we open the report, the weather forecast is updated.</p><p>If we open the settings for this dataset, we can set up a Scheduled refresh so that our weather forecast data is always up to date:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*FV9xDTEXEjIowvgJqcF7FQ.png" /><figcaption>Setting the Scheduled refresh in Power BI</figcaption></figure><p>Here we have set up a daily refresh so that the data updates every day at 7am. The weather forecast will be updated just in time for the start of the work day.</p><h3>Next steps</h3><p>We have now shown two weather data reports and dashboards in Power BI — an historical weather data report and a multi-location weather forecast report. This is just the start of what could be achieved using the weather data.</p><p>Existing business data could be joined to the historical weather data to identify weather based trends. Weather forecast data could be combined with business rules to highlight any weather forecast that will impact the running of the business — either for the good or bad.</p><p>There is also a great deal more weather data available than the information we used in these initial reports. Would you like to drill down to the hourly weather forecast data? Would you like to understand how the climate has changed for a location? Using weather data within Power BI opens up a rich set of weather data investigation opportunities.</p><p>Do you have questions on how to use weather data within Power BI? Please let me know in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2a50b867b0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to import weather data into Power BI]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-import-weather-data-into-power-bi-afccdd12c8f0?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/afccdd12c8f0</guid>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 23:34:43 GMT</pubDate>
            <atom:updated>2020-02-13T12:54:08.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Load Weather Data into Power BI</h3><p>In this article we will create a simple Power BI report that includes weather history data. The focus will be on creating a new weather data query within Power BI and then creating parameters for the query. From here we will create a simple report and discuss some of the common features used displaying weather data.</p><figure><img alt="The finished Power BI report including weather data" src="https://cdn-images-1.medium.com/max/1024/1*yBeKZC906WXqTfYK99dAtw.png" /><figcaption>The finished Power BI report including weather data</figcaption></figure><h3>Creating the Weather Data Query</h3><p>We will start by creating the Weather Data Query within Power BI. This will provide the daily historical weather records for a selected location for a range of dates.</p><p>To set up the query we will use the Power BI desktop tool. Our source of weather will be <a href="https://www.visualcrossing.com/weather-data">Visual Crossing Weather Data</a>. This weather data provider offers web based queries including weather history data and 15-day weather forecast.</p><p>In our case we would like to create a query that retrieves the daily historical weather records for a single location for a specified data range. In a subsequent step we will add parameters within our Power BI query to set values for the location, dates, units of measurement etc.</p><p>The first step is to create the web query request URL. Visual Crossing offers a convenient tool for creating such as web query using the <a href="https://www.visualcrossing.com/weather/weather-data-services">Weather Data Services</a> page. We can use this weather data page to create a historical weather data definition request and then we can view the data in the browser to ensure that is what we were looking for. Once we are satisfied with the data in the browser, we can create a web based URL version of the request that we can use for retrieving the data using a Power BI Web Query.</p><blockquote>The same techniques can be used to import data into <a href="https://medium.com/@awigmore/how-to-load-weather-data-into-microsoft-excel-89d5d65567c0">Microsoft Excel</a></blockquote><p>Here’s the result of creating a request for the historical weather data for the year 2019 in Miami, Florida, USA:</p><figure><img alt="Preview of the Historical Weather Data in the web browser" src="https://cdn-images-1.medium.com/max/1024/1*jQ1XLAtIVLOQd3Cnz8XQig.png" /><figcaption>Preview of the historical weather data in the web browser</figcaption></figure><p>In this case we have restricted the data to the daily summaries (maximum and temperatures, total rainfall, etc). Hourly data is available if necessary.</p><p>We can see the data in the browser is exactly the data set we are hoping to integrate into our Power BI report so we can now create the URL query to retrieve the same data. We hit on “Query API” in the tool to bring up the query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*dYMBfs-nCU6DYYkA-45I4w.png" /></figure><p>The query can be formatted to use various transmission techniques including a GET or POST request or even an ODATA request. All of these are suitable for Power BI data queries but we are going to focus on the simple GET request.</p><p>The raw request looks like:</p><pre><a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?goal=history&amp;aggregateHours=24&amp;startDateTime=2019-01-01T00%3A00%3A00&amp;endDateTime=2019-12-31T00%3A00%3A00&amp;collectStationContributions=false&amp;maxStations=-1&amp;maxDistance=-1&amp;includeNormals=false&amp;shortColumnNames=false&amp;sendAsDatasource=false&amp;allowAsynch=false&amp;contentType=csv&amp;unitGroup=us&amp;key=KPYNQ6AWUDJE9AFERDCHJHSXK&amp;locations=Miami%2C%20FL">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?goal=history&amp;aggregateHours=24&amp;startDateTime=2019-01-01T00%3A00%3A00&amp;endDateTime=2019-12-31T00%3A00%3A00&amp;collectStationContributions=false&amp;maxStations=-1&amp;maxDistance=-1&amp;includeNormals=false&amp;shortColumnNames=false&amp;sendAsDatasource=false&amp;allowAsynch=false&amp;contentType=csv&amp;unitGroup=us&amp;key=KPYNQ6AWUDJE9AFERDCHJHSXK&amp;locations=Miami%2C%20FL</a></pre><p>Let’s look at the details of this request. To keep things simple, let’s remove the optional parameters and also we decode some of the non-alphanumeric characters such as the ‘:’. Finally adding some formatting so each parameter is on a single line makes things a little easier to read.</p><pre><a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?goal=history&amp;aggregateHours=24">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?<br>&amp;aggregateHours=24</a><br>&amp;startDateTime=2019-01-01T00:00:00<br>&amp;endDateTime=2019-12-31T00:00:00<br>&amp;contentType=csv<br>&amp;unitGroup=us<br>&amp;key=YOUR_API_KEY<br>&amp;locations=Miami,FL</pre><p>The main parameters of this request are:</p><p><strong>aggregatehours </strong>is the hours for each history period so aggregatehours=24 is a daily time summary for the historical records. Setting this to a value of one would result in hourly records.</p><p><strong>startDateTime and endDateTime</strong> are the start and end times for the data we would like. We have specified a start time of January 1st to December 31st.</p><p><strong>contentType </strong>is the format of the data we will receive. In this case we’ve left the format a Comma Separated Values (CSV) which is perfect for importing into Power BI (and Excel etc).</p><p><strong>unitGroup </strong>is the units of measurement we would like for the data we receive. For example ‘us’ sets temperature to degrees Fahrenheit and miles for distance whereas ‘metric; sets temperature to Celsius and distance to kilometers.</p><p><strong>key</strong> is the API key that will be populated automatically for you be the Weather Services page.</p><p><strong>locations</strong> is the list of locations that you would like weather data for. In this case we’ve specified Miami, FL. We could specify multiple locations by separating them by a ‘| ‘ (pipe) character. We could also use latitude and longitude values.</p><p>If you would like a full list of available parameters and their description, check out the <a href="https://www.visualcrossing.com/weather-api">Weather API</a> documentation.</p><h3>Adding the Power BI Desktop Web Query</h3><p>We can now enter the parameter into Power BI Desktop to retrieve the weather data.</p><p>To create the basic query, select ‘Get Data’ from the Home ribbon bar and choose ‘Web’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*rzIOtNyvXLTaR31lkIGaIg.png" /></figure><p>For the first query, we’ll add the static request directly from the Weather Data Query Builder page into the text definition. We’ll then add parameters in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*AU9zr6SzuGB6vhKzvBZ7Vw.png" /></figure><p>As soon as we hit ‘OK’, Power BI retrieves the data and shows a preview:</p><figure><img alt="Preview of the weather history data in Power BI" src="https://cdn-images-1.medium.com/max/902/1*4_zinU8VndKQuPbUEO7PYA.png" /><figcaption>Preview of the weather history data in Power BI</figcaption></figure><p>We can see that Power BI has done a great job of interpreting the CSV data retrieved from the weather data service. We can hit ‘Load’ to load the data into Power BI. After a moment, the fields from the historical weather data records are populated ready for us to start creating our report.</p><figure><img alt="Historical Weather Data Fields Populated in Power BI Desktop" src="https://cdn-images-1.medium.com/max/378/1*6dVn9fqQnrws0juJ11JaXg.png" /><figcaption>Historical Weather Data Fields Populated in Power BI Desktop</figcaption></figure><h3>Our first weather data chart — temperature by day</h3><p>Before we move on to adding parameters to our query, let’s add the first chart to our report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*BNgx9fO8-HgpcqIpumsvww.png" /><figcaption>Maximum and minimum temperature by day in a Power BI chart</figcaption></figure><p>Here is the chart definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*1Gm6vl-zF-IoOa9gJwm5oQ.png" /><figcaption>Definition for the maximum and minimum temperature chart</figcaption></figure><p>We chose a line chart using the Maximum and Minimum Temperature fields for values (y-axis). The Date time field was used for the x-axis. Note that we changed the default aggregation of the temperature values from sum to average:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*5VhopqHE66gsvPoZEJDTiA.png" /></figure><p>We did this because “Sum of Temperature” means very little if we change the day level data to week, month, quarter of year. Temperatures are normally summarized by the average (i.e. arithmetic mean), maximum or minimum function.</p><p>For example, I might be interested in the normal High temperature for January (the average), the highest temperature during January (the maximum) or the lowest temperature during January (the minimum). It is unlikely that we want to know that all the temperatures in January sum up to 2000F!</p><p>We’ll look at some more features of the report charts when we return to the report editing after completing the query parameters.</p><h3>Adding parameters to the Data Query</h3><p>In the previous section, we created a fixed weather data query to retrieve the historical weather data by day for Miami, Florida in 2019. To make this really useful, we need to add some parameters to the query so we can change the location, year or any other part of the query.</p><p>To do this, we open the existing query in Power Query from within Power BI Desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BInteTRNrWLdlWY-zIdMBQ.png" /><figcaption>The existing weather data query in Power Query</figcaption></figure><p>From the New Ribbon, select ‘Manage Parameters’ and create a new parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Ji2xQ8O5DW9Ki_WlESRszw.png" /><figcaption>Creating a new parameter</figcaption></figure><p>Our first parameter will allow the user to set the location for the weather data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*hiJ1Q2Ay22GDt9eS7Dfd9A.png" /><figcaption>Creating a location query parameter</figcaption></figure><p>We specify the name of the parameter (location), set the type to ‘text’ and that the parameter is a free form text entry. Finally we add a default value of ‘New York, NY’.</p><p>When we hit OK, nothing much happens. We must use this parameter in our query to cause the data to refresh with the parameter value.</p><p>To do this, we edit our query using the ‘Data source settings’ ribbon button. When we open the current query we see our basic, hard coded URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*bREW29U5kPTLEgsA0P4ArQ.png" /></figure><p>If we switch the type from ‘Basic’ to ‘Advanced’, we can start using our parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*2icHHSgvnVKjI84XBPkK7w.png" /><figcaption>Advanced query formatting allows us to use our parameters</figcaption></figure><p>We can now see that the URL is going to be built up from a series of parts. We take &amp;locations=Miami,FL from the first URL and split it between new two parts — the hard coded ‘&amp;locations=’ and the parameter value.</p><p>First, we add a new part, leaving the type as text. In the value we add ‘&amp;locations=’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*VeM5ipaFQO9hmUq7gSNaOg.png" /></figure><p>We then add another part and change the type to parameter and choose our existing ‘location’ parameter.</p><p>If after pressing OK we then press ‘Refresh Preview’, the web query will be re-run with the parameter default value of ‘New York, NY’.</p><p>We can then use the parameter to update the location dynamically. Therefore if we can enter ‘Paris, France’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*3fpoi8Nn5PiNUKwkphTD9g.png" /></figure><p>When we press OK and then ‘Refresh Query’, we see the weather history for Paris, France.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*tIn_QRV4g8lz7lIwY-YWBg.png" /></figure><p>In total we split the original web query URL into five parameters. The location, key, unit group and date range. This will allow the user to change the location and date range of the data they are interested in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*JoY73Up7NbsY16HKiX7ZRQ.png" /><figcaption>Five parameters for our weather data web query</figcaption></figure><p>We now have a good set of historical weather data. Let’s create a basic report to show this off.</p><h3>Creating the Power BI report</h3><p>In our simple Historical Weather Data report we have a couple of elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_2oSEH2fSuR2dXmB4Xhqg.png" /></figure><p>The location (“Miami, FL”) is displayed as a Card. This allows us to display dynamic data values from the weather data.</p><p>We then have a set of four KPIs to highlight some interesting weather facts for the selected time period — the maximum and minimum temperatures, the total amount of rain and finally the number of days which experienced rainfall.</p><p>The KPI definitions are very simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*TczaanHcYsjNcEBd76LC2g.png" /></figure><p>We use the Maximum of the Maximum Temperature as the indicator and then the date time year as the trend. We don’t add a target. We then modify the font size and colors.</p><p>The minimum temperature, rainfall amount and rain days KPIs are added in a similar way.</p><p>We have already looked at the temperature values chart in the previous section. We can create a wind-pressure chart in a similar way using a Line and Column chart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*gbCjpk__GGNgn7quuGtEhQ.png" /></figure><p>In this chart, the line displays the pressure and the bars display the temperature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*_47G8aTYQTgmQbv8Xpi5kw.png" /></figure><p>In the final row we have two elements showing the rainfall and a map showing the location that we have used for the data.</p><p>The year to date rainfall chart which shows how the total rain fell throughout the year. This approach clearly shows the total rainfall for the year (60 inches in this case) and also the days when a lot of rain fell (where the chart climbs steeply) and times when there was not much rain (where the chart stays flat).</p><p>In this case we can see that a lot of rain falls in Miami during the summer months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*-U1ZcOfrhVmDMEMYMZzUHg.png" /><figcaption>Cumulative rainfall chart</figcaption></figure><p>The cumulative rainfall is a simple Stacked Column Chart with one element. Rather than showing the rain fall for each day, we want to show the cumulative amount from the start of the year. To do this we create a new measure that defines the year to date value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*w3IFd0UphadDOr8ntcZ0eg.png" /></figure><p>The easiest way to do this is via a quick measure which helps guide us to the correct fields of the Year to date measure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*N7jsTvsPecp0cEKPcnJeyA.png" /><figcaption>Creating a year to date rainfall measure</figcaption></figure><p>We then use the new measure in our chart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*3cjl8kn9_EZeNBj9crCevg.png" /></figure><p>The final element of our report is the map chart that shows the location of the requested weather data.</p><p>The map uses the longitude and latitude values returned as part of the weather data query to show the point on the map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*soEP1dnkHj9ds9OAr2OH_g.png" /></figure><p>And there we have our simple Historical Weather Data Report in Power BI Desktop. The last stage is to publish this to the weather so we can enjoy the report in our favorite web browser.</p><h3>Publishing the report to Power BI on the Web</h3><p>To publish the report, hit the ‘Publish’ button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*Q4Ggh0PNnnw1ZDd3QakIMg.png" /><figcaption>Hit publish to share the report to the web</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*iC6uMGDWuA0LS-gFp_FEhQ.png" /></figure><p>In this case we will publish the report to our own work space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MITKpchcNsQm32uTE_mE2w.png" /><figcaption>The final weather data report in Power BI for the web</figcaption></figure><h3>Changing parameter values in the Power BI</h3><p>The final stage is to select a different location. To do this we have to modify the parameter values that we specified on the query. The parameters can be modified in the data set, found under ‘My workspace’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTyp7ZKx9xkIRirS8tOuhQ.png" /></figure><p>Modifying the settings for the data set brings the parameter set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*2GLgngeGkvhpTJWe1fDyVQ.png" /></figure><p>We can modify the location here. Let’s change it to London, UK</p><p>After apply the new query parameter value, we can return to the data set list in and hit refresh. We then see the new data in our report</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oSFHoAJS8aNt3NauSpOmQ.png" /><figcaption>The report with the new location</figcaption></figure><p>We have seen in this article that we can easily add weather data to our Power BI reports and dashboards. We did this by finding a great weather API source that can be accessed from the Power BI Web Query. From there, creating a great looking historical weather data report was straight forward.</p><p>What about a weather forecast? In my next article, we’ll use the techniques used here to retrieve the weather forecast and create a great looking weather map!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afccdd12c8f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-import-weather-data-into-power-bi-afccdd12c8f0">How to import weather data into Power BI</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do I add the weather forecast to my web page?]]></title>
            <link>https://awigmore.medium.com/how-do-i-add-the-weather-forecast-to-my-web-page-be3e5c7e5d06?source=rss-228975b7d50a------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3e5c7e5d06</guid>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Andrew Wigmore]]></dc:creator>
            <pubDate>Fri, 07 Feb 2020 04:43:49 GMT</pubDate>
            <atom:updated>2020-02-07T04:43:49.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*YtfDTw6ihha5RWVE.png" /></figure><p>In this article we will describe how to use a Weather API to add a weather forecast display to a web page. We will use HTML, CSS and JavaScript to build a small weather forecast control using the data retrieved from the Weather API . The focus will be on using the Weather API and displaying the most relevant information to the reader of the web page. We will extend a simple weather forecast display to create both horizontal and vertical forecast view that includes the forecast for temperature, rainfall and whether there it will be sunny or cloudy.</p><h3>Technologies — Weather API, HTML, CSS and JavaScript</h3><p>We want the focus of the example to using and interpreting the weather forecast data from a Weather API so we want to use the minimum of other web technologies. This can then serve as a starting point for you to create a more complete weather forecast display. We will use JavaScript, HTML and CSS technologies to display the forecast within the page. To keep the JavaScript short and simple, we will use a commonly used library called <a href="https://jquery.com/">jQuery</a> to help retrieve the data and format the HTML. There is no need to use the jQuery library — it just helps keeps the code shorter and more readable in this case.</p><h3>Retrieving the weather forecast data using a weather API</h3><p>Before we can start creating the web page, we need to find a way to retrieve the weather forecast data. Typically, services such as this are hosted in a cloud as they handle a vast amount of weather data including the forecast plus historical records that can go back many years for 1000s of weather stations. To allow for easy retrieval of the data, a weather API is built to allow programs, such as the web page we are building, to easily retrieve the data. For a web page, we want a Weather API that allows us to retrieve data using a web based connection.</p><p>We will be using the <a href="https://www.visualcrossing.com/weather-api">Visual Crossing Weather API</a>. The API allows retrieval of weather forecast data as well as historical weather records and it has been designed with web based applications and web pages in mind. The Visual Crossing Weather API includes an easy way to build weather API queries via the <a href="https://www.visualcrossing.com/weather/weather-data-services">Weather Data Services Page</a>. On this page we can create a query for the weather forecast, historical weather observations and also historical climate summaries. We can also view the results in the browser and even download them to an spreadsheet, so we can make sure that the weather data fits our requirements.</p><p>The process to create a query for a location is simple:</p><p><strong>1. Open the </strong><a href="https://www.visualcrossing.com/weather/weather-data-services"><strong>Weather Data Query page</strong></a></p><p><strong>2. Create a free trial account if necessary and log in</strong>. The tool offers a free trial including API access.</p><p><strong>3. Add a single location</strong> using the location address or latitude,longitude co-ordinates. The tool supports adding multiple locations and even importing the locations from a spreadsheet or other file. In our simple case we’re choosing a single location that we will associate with the weather forecast viewer that we are building.</p><p><strong>4. Build the weather data definition</strong>. In this case we will use the default, daily forecast request. We could also have built a request to retrieve weather data for multiple locations or to retrieve historical weather data.</p><p><strong>5. View the data in the browser</strong>. We can view the data directly in the browser so that we can understand the data we will be receiving from the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g0feyqZkVY_mDDRH.png" /></figure><p><strong>6. Create the Weather API request</strong>. Finally, we use the forecast definition we created for viewing the data in browser to create a Weather API request to retrieve the data ourselves. The API supports many types of additional parameters to suit various needs. The only thing we will change is the output format from CSV to JSON. JSON format will make it easier to process via JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hhhVJSPMzpbGYx75.png" /></figure><p>More information can be found on the Weather Data &amp; Weather API through the <a href="https://support.visualcrossing.com/hc/en-us/sections/360004059911-Weather-Data-Weather-API-Documentation">weather data documentation</a>.</p><h3>The Weather API query results</h3><p>Here is the query that we have constructed using the query builder page:</p><pre><a href="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast?unitGroup=us&amp;aggregateHours=24&amp;contentType=json&amp;shortColumnNames=true&amp;location=New%20York,%20NY&amp;key=YOUR_API_KEY">https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast?unitGroup=us&amp;aggregateHours=24&amp;contentType=json&amp;shortColumnNames=true&amp;location=New%20York,%20NY&amp;key=YOUR_API_KEY</a></pre><p>In our simple case we will only need to modify a couple of the parameters through the code when the forecast display is populated:</p><p><strong>location</strong> — the location parameter specifies the address of the location for which we would like the weather forecast. We will replace this with the user selection via a parameter in the HTML.</p><p><strong>unitGroup</strong> — the unitGroup tells the API what units to return weather data in — US or metric.</p><p><strong>key</strong> — This is the API key that is used by the Weather API to uniquely identify your account.</p><p>For more information on the weather API queries, see the <a href="https://www.visualcrossing.com/weather-api-documentation">Weather API documentation</a></p><h3>The Weather API query results</h3><p>You can see the result of the query by pasting the URL into a browser. To help with readability, we have used the browser Network log Preview feature to format the JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*C9-_UNCYVfh_srdU.png" /></figure><p>The Weather Forecast response is a JSON structure. The main structure is a key-value map that uses the name of each requested location as the key and the weather data for each location as the value. As we only specified an address, the key is the address that we entered. Each location value includes an array of values plus some other general information — some of which is not used for weather forecast data. The value array represents the weather forecast time periods. There are 15–16 elements representing the 15–16 calendar days in the weather forecast. The variable number of days in the forecast are a result of how the weather forecast hours split across calendar days. For example, if the ‘15-day’ forecast starts at 6pm, then it will cross over 16 calendar dates (15-day refers to a 15*24 hours period, not 15 calendar days). We will need to write code that can handle a variable number of possible forecast days.</p><p>Each day within the forecast has a series of weather elements representing the forecast for that day. In this case we can see that we have requested data in US units so the high temperature (maxt) is predicted to be 45F and low temperature (mint) is predicted to be 40F.</p><p>We are going to be creating HTML from each of these days and extracting the weather elements to show in our forecast and creating HTML elements to contain the data.</p><p>For more information on the weather data format and available variables, see the <a href="https://www.visualcrossing.com/weather-data-documentation">weather data documentation</a></p><h3>Adding the Weather Forecast to Web Page</h3><p>We will now build the weather forecast display.</p><h4>Weather forecast HTML container</h4><p>We will start by using a simple DIV element as the placeholder for the Weather Forecast.</p><pre>&lt;div class=&quot;verticalweatherForecast&quot; data-key=&quot;YOUR_API_KEY&quot; data-location=&quot;London, UK&quot; data-unitGroup=&quot;metric&quot;&gt;/&gt;</pre><p>This HTML element defines the location of the weather forecast content within the HTML page. The HTML element also provides some of the parameters needed by the forcast display by using custom attribute prefixed with ‘data-’. These parameters are the API key, the location and the unit group to use to display the data. The class, ‘verticalweatherForecast’ is web page’s style information indicate the container size, style etc.</p><p>In this simple example, we are going to rely on the container styling rules to govern what size to display our weather forecast. From this information, we will choose a horizontal or vertical display and apply some simple styling to create a weather forecast. If size of the container element changes after the inital rendering we will rely on the existing HTML and CSS rules to display the content — we won’t re-execute the refresh code and re-render to reflect a different orientation. This is en exercise that can be left to the reader!</p><h4>Attaching and initializing the container</h4><p>We are ready to write some Javacript to retrieve the weather data using the request we created above. We can then use this data to populate the forecast element. A simple JavaScript class called ‘WeatherForecastWidget’ will handle the weather forecast data retrieval and display. There will be one instance of WeatherForecastWidget for every weather forecast widget on the page. In our test page we are going to have two forecast displays so we will have two instances of the class. Here is the skeleton structure of the class:</p><pre>function WeatherForecastWidget(selector) {<br>    //Initialize the widget using the container parameters<br>    this.config={<br>        &quot;location&quot;:selector.attr(&quot;data-location&quot;),<br>        &quot;unitGroup&quot;:selector.attr(&quot;data-unitGroup&quot;) || &quot;us&quot;,<br>        &quot;key&quot;: selector.attr(&quot;data-key&quot;) <br>    }</pre><pre>    //the root HTML tag selector<br>    this.selector=selector;</pre><pre>     //weather forecasta data<br>    this.data=null;</pre><pre>    var me=this;<br>    //constructs Weather API request and then loads the weather              forecast data from the Weather API</pre><pre>    this.loadForecastData=function() {<br>       ...<br>    }</pre><pre>    //displays the weather data inside the container tag<br>    this.refresh=function() {<br>       ...<br>    }<br>}</pre><p>When we execute the ‘attach’ bootstrap code, we’ll pass the jQuery selector of the forecast widget container element. The forecast widget class extracts the location, unitGroup and api key from custom attributes on the forecast container HTML tag. The class then has two skeleton methods which we will populate. The first method, ‘loadForecastData’, loads the Weather Data from the Weather API. The second, ‘refresh’, refreshes the forecast display.</p><p>The following code is used to attach the HTML to the widget and create the WeatherForecastWidget instance.</p><pre>var attach=function(selector) {<br>   var instance=new WeatherForecastWidget($(selector) );<br>   instance.loadForecastData();<br>   return instance;<br>}</pre><p>We call this attach method once for each of our two forecasts. The attach code must be executed after the page has loaded and so we place this attach code at the bottom of the html page:</p><pre>WeatherForecastDisplay.attach(&quot;.horizontalweatherForecast&quot;); WeatherForecastDisplay.attach(&quot;.verticalweatherForecast&quot;);</pre><p>There are other ways to initialize the control. For example the JavaScript code could find appropriate container divs using as a CSS selector searches. Notice that the above attach method does return the newly created WeatherForecastWidget instance which we could use in the future to attach event handlers for interactivity etc.</p><h4>Loading the Weather Forecast Data</h4><p>Let’s now look at the loadForecastData method which loads the Weather Forecast data:</p><pre>//constructs Weather API request and then loads the weather forecast data from the Weather API<br>this.loadForecastData=function() {<br>    //endpoint<br>    var uri=&quot;https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast?&quot;;<br>    <br>     //parameters uri+=&quot;unitGroup=&quot;+me.config.unitGroup+&quot;&amp;aggregateHours=24&amp;contentType=json&amp;shortColumnNames=true&amp;location=&quot;+me.config.location+&quot;&amp;key=&quot;+me.config.key;<br>     $.get(uri, function( rawResult ) {<br>            me.data=rawResult;<br>            me.refresh();<br>      );<br>}</pre><p>We can see that the method is quite simple. The method first constructs the URI based upon the unitGroup, location and key parameters and then submits it to the jQuery get method to retrieve the return value. When the request completes, the code populates the data property of the WeatherForecastWidget instance in the callback of the get method. Finally the callback calls the ‘refresh’ method to refresh the display. To keep things clean we have not added a lot of network error handling code. We would recommending adding additional code for production deployment. This code should ensure a failure to connect or retrieve data is handled gracefully.</p><h4>Displaying the Weather Forecast Data</h4><p>We now should have the weather forecast ready to display in the HTML Container. This display is performed through the refresh method.</p><p>We have split the method up into smaller chunks for this walk through. The first section of the refresh method sets up the selectors, extracts the forecast data and exits cleanly if a bad or missing data situation occurs.</p><pre>//&#39;me&#39; refers to the WeatherForecastWidget instance<br>var root=$(me.selector);//no data at all - exit<br>if (!me.data) {<br>    $(me.selector).html(&quot;No data available for &quot;+me.config.location);<br>    return;<br>}<br>//no locations in the data -  exit<br>var locations=me.data.locations;<br>if (!locations) {<br>     root.html(&quot;No locations found in data for &quot;+me.config.location);<br>     return;<br>}<br>        <br>var locationsIds=Object.keys(locations);<br>var locationData=locations[locationsIds[0]];<br>var forecastValues=locationData.values;</pre><p>We now are ready to populate the HTML. First we create a basic HTML structure of a div element for the location label and container for the days. The ‘days’ element will contain another div element for every day of the weather forecast.</p><pre>//add a root style for CSS specificity and top level rules<br>root.toggleClass(&quot;forecastwidget&quot;, true);<br>//construct the HTML skeleton<br>root.html(&quot;&lt;div class=&#39;location&#39;&gt;&lt;/div&gt;&quot;+<br>                &quot;&lt;div class=&#39;days&#39;&gt;&lt;/div&gt;&quot;+<br>                &quot;&lt;div class=&#39;footer&#39;&gt;&lt;a href=&#39;https://www.visualcrossing.com/weather-api&#39; title=&#39;Weather Data by Visual Crossing&#39; target=&#39;_blank&#39;&gt;Credit&lt;/a&gt;&quot;);</pre><p>Before we can populate the days, we need to decide whether to display the days horizontally or vertically. We are going to keep things very simple — if the container is wider than it is tall, then we assume horizontal display. If it is taller than it is wide then we will use vertical display. We will use an additional CSS class to switch the format of the days when the display is vertical. If there is not enough room to hold all the days of weather forecast we will use the CSS to hide the extra content.</p><pre> //use the container size to decide how to display the forecast<br> var rect=root.get(0).getBoundingClientRect()<br> var isVertical=rect.height&gt;rect.width;<br> root.children(&quot;.days&quot;).toggleClass(&quot;vertical&quot;, isVertical);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*odwY8fAytHUjoAbU.png" /></figure><h4>Populating the weather forecast day</h4><p>Each day of the forecast is a set of HTML elements that correspond to a variable of the weather forecast. We are going to show five pieces of information for each day — the date, an icon which summarizes the conditions, the maximum and minimum temperatures, the expected rainfall and a little text summary of the conditions.</p><pre>&lt;div class=&#39;day&#39;&gt;<br>     &lt;div class=&#39;date&#39;&gt;&lt;/div&gt;<br>     &lt;i class=&#39;icon fas&#39; &gt;&lt;/i&gt;<br>     &lt;div class=&#39;maxt&#39;&gt;&lt;/div&gt;<br>     &lt;div class=&#39;mint&#39;&gt;&lt;/div&gt;<br>     &lt;div class=&#39;precip&#39;&gt;&lt;i class=&#39;fas fa-tint fa-xs fa-fw&#39;&gt;&lt;/i&gt;&lt;span class=&#39;value&#39;&gt;&lt;/span&gt;&lt;/div&gt;<br>     &lt;div class=&#39;conditions&#39;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p>To create and populate the above HTML, we iterate the forecast values (which represent each day of the forecast). We add a new HTML structure for each day which looks like this:</p><pre>&lt;div class=&#39;day&#39;&gt;<br>     &lt;div class=&#39;date&#39;&gt;&lt;/div&gt;<br>     &lt;i class=&#39;icon fas&#39; &gt;&lt;/i&gt;<br>     &lt;div class=&#39;maxt&#39;&gt;&lt;/div&gt;<br>     &lt;div class=&#39;mint&#39;&gt;&lt;/div&gt;<br>     &lt;div class=&#39;precip&#39;&gt;&lt;i class=&#39;fas fa-tint fa-xs fa-fw&#39;&gt;&lt;/i&gt;&lt;span class=&#39;value&#39;&gt;&lt;/span&gt;&lt;/div&gt;<br>     &lt;div class=&#39;conditions&#39;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p>For temperature, location name and conditions, we can insert the weather forecast variable value directly into the appropriate div for the day with the minimum of formatting. In this case we rounded the values to remove unnecessary decimal points. Later we will discuss how the unit of measurement for each value could be added.</p><p>The date, precipitation (rainfall) and conditions icon are a little more involved. The datetime of the forecast period is returned as the number of milliseconds since the JavaScript epoch but using the local time of the location requested. As JavaScript automatically adjusts this for the browser timezone, it’s necessary to remove the offset that JavaScript adds. We then format the date to produce a Month-Date value. We have decided to pair the rainfall amount with a drip icon when precipitation is greater than zero for additional emphasis. This means we have to add logic to hide the whole rain div element if there is no rainfall predicted. We do this by adding the ‘hidden’ class when no rainfall is predicted.</p><p>We choose the icon based on the forecast condition — rain, wind and cloud cover. In this case the logic is quite straightforward: if it will rain, show a rain icon, else if it will be very windy, show a windy icon, else use the skycover (the cloudiness) to produce an icon representing the amount of cloud. As the skycover amount ranges from 0 (sunny) -100% (completely cloudy) we split the range into three ranges 0–25%=Sunny, 25–75%=Partly cloudy, &gt;75%=Cloudy. We use the <a href="https://fontawesome.com/">Font Awesome</a> icons to create a simple graphical display. These icons are included in the page as a font. CSS rules are used to choose the icon and so the logic for the icon specifies the appropriate icon class for the calculated conditions.</p><pre>forecastValues.forEach(function(d) {<br>        //create a new day div with children<br>        var dayElement=$(&quot;&lt;div class=&#39;day&#39;&gt;&quot;+<br>                &quot;&lt;div class=&#39;date&#39;&gt;&lt;/div&gt;&quot;+<br>                &quot;&lt;i class=&#39;icon fas&#39; &gt;&lt;/i&gt;&quot;+<br>                &quot;&lt;div class=&#39;maxt&#39;&gt;&lt;/div&gt;&quot;+<br>                &quot;&lt;div class=&#39;mint&#39;&gt;&lt;/div&gt;&quot;+<br>                &quot;&lt;div class=&#39;precip&#39;&gt;&lt;i class=&#39;fas fa-tint fa-xs fa-fw&#39;&gt;&lt;/i&gt;&lt;span class=&#39;value&#39;&gt;&lt;/span&gt;&lt;/div&gt;&quot;+<br>                &quot;&lt;div class=&#39;conditions&#39;&gt;&lt;/div&gt;&quot;+<br>                &quot;&lt;/div&gt;&quot;);<br>        <br>        //add the day to the days element<br>        root.find(&quot;.days&quot;).append(dayElement);<br>        <br>        <br>        //temperature and conditions are simply inserted into the appropriate div<br>        dayElement.find(&quot;.maxt&quot;).html(Math.round(d.maxt));<br>        dayElement.find(&quot;.mint&quot;).html(Math.round(d.mint));<br>        dayElement.find(&quot;.conditions&quot;).html(d.conditions);<br>        <br>        //date is added with a little additional formatting<br>        var date= new Date(d.datetime);<br>        //by default the values are returned in the local time zone of the location requested <br>        date=new Date(date.getTime()+ date.getTimezoneOffset()*60000);<br>        dayElement.find(&quot;.date&quot;).html(MONTHS[date.getMonth()]+&quot; &quot;+date.getDate());<br><br><br>        //the rainfall value includes so hide the whole section if no rainfall<br>        var precip=dayElement.find(&quot;.precip&quot;);<br>        precip.toggleClass(&quot;hidden&quot;,  !d.precip);<br>        precip.find(&quot;.value&quot;).html(d.precip);<br>        <br>        //a simple logic decides which icon to show based upon the conditions<br>        var icon=dayElement.find(&quot;.icon&quot;);<br>               <br>        if (+d.precip&gt;0.1) {<br>            icon.toggleClass(&quot;fa-cloud-showers-heavy&quot;,true);<br>        } else if (+d.wspd&gt;40) {<br>            icon.toggleClass(&quot;fa-wind&quot;,true);<br>        } else if  (+d.cloudcover&gt;75) {<br>            icon.toggleClass(&quot;fa-cloud&quot;,true);<br>        }  else if  (+d.cloudcover&gt;30) {<br>            icon.toggleClass(&quot;fa-cloud-sun&quot;,true);<br>        } else {<br>            icon.toggleClass(&quot;fa-sun&quot;,true);<br>        }<br>        <br>        //make the icon twice as big if vertical<br>        icon.toggleClass(&quot;fa-2x&quot;, isVertical);<br>});</pre><h4>Formatting the forecast</h4><p>If you run the page now, the weather forecast should be populated however it looks awful! We need to add some CSS to format it correctly. The first step is to arrange the days horizontally or vertically depending on the view we decided earlier. If you recall, we added the additional ‘vertical’ CSS class if the display should be vertical. This will allow us to add CSS rules that are conditional on the orientation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*PULW-4j6paOQtTY9.png" /></figure><p>Three CSS selectors define the basic layout. The .forecastwidget rule itself defines that the location, days and footer should be displayed vertically. The .days class indicates that should be displayed using flex layout. When this is displayed in horizontal view, we use row-based flex layout and when it is displayed using the vertical view, we use column-based flex layout</p><pre>.forecastwidget {<br>     display: flex;<br>     flex-direction: column;<br>     padding: 5px;<br>     font-size: 14px;<br>     background-color:#ffffff;<br>     margin:10px;<br>     border-radius: 7px;<br>}<br>//basic days rules - used for both horizontal and vertical layout<br>.forecastwidget .days {<br>     display: flex;<br>     flex-direction: row;<br>     justify-content: start;<br>     flex: 1;<br>     overflow: hidden;<br>}<br>//vertical layout overrides the orientation of the days<br>.forecastwidget .days.vertical {<br>     flex-direction: column;<br>     font-size: 1.2em;<br>}</pre><p>Switching the order from horizontal to vertical is not enough to make an attractive forecast however. We need to arrange the content within the day a little differently based on the view. We will use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a> to arrange the day content (sorry <a href="https://caniuse.com/#feat=css-grid">older browsers</a>!).</p><p>For the horizontal view, the weather forecast elements are arranged vertically. We do this by specifying a grid layout with two columns. Most of the weather elements span both of these columns but the Maximum and minimum elements span one — left and right.</p><pre>//define a grid layout with two columns<br>        .forecastwidget .days .day {<br>            display: grid;<br>            grid-template-columns: 50% 50%;<br>            <br>            justify-content: center;<br>            align-items: center;<br>            padding: 0px 5px;<br>            font-size: 0.9em;<br>            justify-items: center;<br>            grid-gap: 1px;<br>        }   <br><br>        //most forecast elements take up two columns<br>        .forecastwidget .days .day * {<br>            grid-column: span 2;<br>            display: flex;<br>            align-items: center;<br>            justify-content: center;<br>        }<br>        //maximum and minimum elements are arrange side by side<br>        .forecastwidget .days .day .maxt {<br>            grid-column: 1 ;<br>        }<br>        .forecastwidget .days .day .mint {<br>            grid-column: 2 ;<br>        }</pre><p>For the horizontal view, the weather forecast elements are arranged vertically. We do this by specifying a grid layout with two columns. Most of the weather elements span both of these columns but the Maximum and minimum temperature elements span one — left and right.</p><pre>/*define a grid layout with two columns*/<br>.forecastwidget .days .day {<br>            display: grid;<br>            grid-template-columns: 50% 50%;<br>            <br>            justify-content: center;<br>            align-items: center;<br>            padding: 0px 5px;<br>            font-size: 0.9em;<br>            justify-items: center;<br>            grid-gap: 1px;<br>}   <br><br>/*most forecast elements take up two columns*/<br>.forecastwidget .days .day * {<br>            grid-column: span 2;<br>            display: flex;<br>            align-items: center;<br>            justify-content: center;<br>}<br>/*maximum and minimum elements are arrange side by side*/<br>        .forecastwidget .days .day .maxt {<br>            grid-column: 1 ;<br>}<br>.forecastwidget .days .day .mint {<br>            grid-column: 2 ;<br>}</pre><p>We now override this for our vertical view. The vertical view uses a horizontal display for each day. This horizontal view is a single row of cells so all of the elements use a single span cell. We add CSS rules to override the day arrangement when the forecast is displayed in vertical mode:</p><pre>/*define a grid layout with size columns*/<br>.forecastwidget .days.vertical .day {<br>      grid-template-columns: 50px 30px 30px 30px 60px auto;<br>      grid-gap: 4px;<br>      justify-content: start;<br>      margin: 2px 0px;<br>      padding: 4px 0px;<br>}<br>/*Every element takes up a single grid cell*/<br>.forecastwidget .days.vertical .day * {<br>      grid-column: span 1;<br>}<br>/*No special layout is required for the temperature values*/<br>.forecastwidget .days.vertical .day .maxt,<br>  .forecastwidget .days.vertical .day .mint  {<br>            grid-column: default ;<br>}</pre><p>We should now have a relatively attractive weather forecast layout. The final thing we do is add a little bit of formatting to the elements.</p><pre>        /*element styling rules*/<br>        .forecastwidget .location {<br>            font-size: 1em;<br>            font-weight: bold;<br>            flex:0;<br>        }<br>        .forecastwidget .footer {<br>            font-size: 0.7em;<br>            color:darkgrey;<br>            display: flex;<br>            justify-content: flex-end;<br>        }<br>        .forecastwidget .days .day .date {<br>            color:darkgrey;<br>            font-size: 0.9em;<br>            white-space: nowrap;<br>        }<br><br><br>        .forecastwidget .days .day:not(:last-child) {<br>            border-right:1px solid darkgray;<br>        }<br><br>        .forecastwidget .days.vertical .day:not(:last-child) {<br>            border-right:none;<br>            border-bottom:1px solid darkgray;<br>        }<br><br>        .forecastwidget .days .day .conditions {<br>            display:none;<br>            color:darkgrey;<br>            font-size: 0.9em;<br>        }<br>        .forecastwidget .days.vertical .day .conditions {<br>            display:block;<br>        }<br>        .forecastwidget .days .day  .maxt {<br>            font-weight: bold;<br>        }<br>        .forecastwidget .days .day  .mint {<br>            font-size: 0.9em;<br>            color:darkgrey;<br>        }<br>       <br>        .forecastwidget .days .day  .hidden {<br>           visibility: hidden;<br>        }</pre><h3>Our final Weather Forecast Display — where next?</h3><p>We now have our basic Weather Forecast display wired and displayed. The forecast will refresh whenever the page is reloaded. Depending on the formatting of the container element, the widget will switch from a horizontal to vertical view. We have seen that this project is quite straightforward if you are familiar with HTML, CSS and JavaScript. After learning how to build the weather API query, the results can be retrieved in JSON format and immediately used to create an HTML weather forecast.</p><p>You can find the full code for this sample in the <a href="https://github.com/visualcrossing/WeatherApi/blob/master/html_samples/weather-forecast-display-jquery.html">Github</a>.</p><p>There are some missing features that would be nice to add. Firstly we don’t display the units of measurements on the temperature or rainfall values. It’s easy to find out what unit a particular weather value should be formatted in. In the Weather Forecast JSON, the weather element definitions can be found in the ‘columns’ object that is returned along with the locations. The columns object is a map of all the available columns that are used in the data. Each variable contains two very useful values — the variable full name and also the unit of measurement used for the value.</p><p>Another feature that would be nice to add would be some more interactivity — for example if forecast days are hidden, add a way for the user to open the hidden days or maybe click on a day to retrieve the hourly forecast?</p><p>Finally, it would be great if we could take advantage of some of the more advanced features of the weather API. How about creating an infinite weather forecast that switches to use <a href="https://www.visualcrossing.com/blog/how-do-I-find-the-best-long-range-weather-forecast">historical climate statistics</a> to predict the weather more than 15 days out? Alternatively we could allow users to bring up historical weather data records in a similar forecast-style widget.</p><p>In our next part of this blog I will look into some of these more advanced features to make our weather forecast widget a little more complete!</p><p><em>Originally published at </em><a href="https://www.visualcrossing.com/blog/how-do-I-add-weather-forecast-to-my-webpage"><em>https://www.visualcrossing.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3e5c7e5d06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>