<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Covid-19 Analytics Archives - relataly.com</title>
	<atom:link href="https://www.relataly.com/tag/covid-19-analytics/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.relataly.com/tag/covid-19-analytics/</link>
	<description>The Business AI Blog</description>
	<lastBuildDate>Sat, 27 May 2023 10:20:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://www.relataly.com/wp-content/uploads/2023/04/cropped-AI-cat-Icon-White.png</url>
	<title>Covid-19 Analytics Archives - relataly.com</title>
	<link>https://www.relataly.com/tag/covid-19-analytics/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">175977316</site>	<item>
		<title>Geographic Heat Maps with GeoPandas: Visualizing COVID-19 Data in Python</title>
		<link>https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/</link>
					<comments>https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Wed, 08 Apr 2020 22:03:00 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Sources]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Geo Heat Maps]]></category>
		<category><![CDATA[GeoPandas]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Covid-19 Analytics]]></category>
		<category><![CDATA[Geographic Maps]]></category>
		<category><![CDATA[Heat Map]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=291</guid>

					<description><![CDATA[<p>The spreading of COVID-19 has led to an increased interest in displaying region and country-specific information on geographic heat maps. Geographic heat maps use color shadings to visualize data that includes a spatial component and refers, for example, to countries, cities, towns, mountains, etc. The color shades are defined in a color palette and determined ... <a title="Geographic Heat Maps with GeoPandas: Visualizing COVID-19 Data in Python" class="read-more" href="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/" aria-label="Read more about Geographic Heat Maps with GeoPandas: Visualizing COVID-19 Data in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/">Geographic Heat Maps with GeoPandas: Visualizing COVID-19 Data in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The spreading of COVID-19 has led to an increased interest in displaying region and country-specific information on geographic heat maps. Geographic heat maps use color shadings to visualize data that includes a spatial component and refers, for example, to countries, cities, towns, mountains, etc. The color shades are defined in a color palette and determined by numerical values on a scale. In this way, geographic heat maps give the viewer a quick overview of what is happening in different regions. This tutorial shows how to create geographic heat maps in Python using the GeoPandas library. We will work with COVID-19 data and visualize it using various color-coded maps.</p>



<p>The rest of this article proceeds as follows: We begin by going through the steps to visualize COVID-19 data on a geographic heat map. We will be using the GeoPandas library to plot the maps. Geopandas is an open-source project for working with geospatial data in Python. Our heat map will use color shades to visualize growth rates and total cases of COVID-19 in different countries. In addition, we will zoom in on specific map regions. </p>



<p>Also: <a href="https://www.relataly.com/predicting-crimes-in-san-francisco-creatingsf-crime-map-using-xgboost/2960/" target="_blank" rel="noreferrer noopener">Predictive Policing: Preventing Crime in San Francisco using XGBoost</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">What are Geographic Heat Maps?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Geographic heat maps are visual representations of data that use color or other visual encodings to show the density or intensity of data points in a geographic region. They are commonly used to represent data that is associated with a geographic location, such as population data, economic data, or weather data.</p>



<p>Geographic heat maps are typically created by overlaying a grid or mesh on a map and then assigning a color or other visual encoding to each grid cell based on the density or intensity of data points in that cell. The resulting heat map shows the distribution or pattern of data points across the geographic region and can provide valuable insights and information about the data.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image"><img decoding="async" src="https://www.relataly.com/wp-content/uploads/2020/04/image-41-1024x443.png" alt="Geographic heat map showing COVID-19 growth rates in different countries of the world. In this Python tutorial we will create similar maps."/><figcaption class="wp-element-caption">Geographic heat map showing COVID-19 growth rates in different countries of the world. In this Python tutorial we will create similar maps.</figcaption></figure>
</div>
</div>



<p>Also: <a href="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/" target="_blank" rel="noreferrer noopener">Color-Coded Cryptocurrency Price Charts in Python</a></p>



<h2 class="wp-block-heading">What are Geographic Heat Maps used for?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Geographic heat maps are used for a variety of purposes, such as:</p>



<ul class="wp-block-list">
<li><strong>Visualizing data:</strong> geographic heat maps can provide a clear and intuitive way to visualize data that is associated with a geographic location, allowing analysts and users to quickly and easily understand the data and identify patterns, trends, and relationships.</li>



<li><strong>Identifying spatial patterns: </strong>geographic heat maps can help to identify spatial patterns or trends in the data, such as clusters, outliers, or trends over time. This can provide valuable insights and information about the data and can help to inform decision-making and analysis.</li>



<li><strong>Analyzing and comparing data:</strong> geographic heat maps can be used to compare and contrast different datasets or to analyze the relationship between different variables or data sources. This can help to identify correlations, trends, or patterns that may not be immediately apparent from the raw data.</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">What are the Potential Pitfalls of Using Geographic Heat Maps?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>While geographic heat maps are useful for all kinds of purposes, there are a few potential limitations and pitfalls to consider when using heat maps:</p>



<ol class="wp-block-list">
<li>Choosing an appropriate color scale: It&#8217;s essential to choose a color scale that accurately reflects the data being represented and is easy for viewers to interpret. If the color scale is not well-suited to the data, it can be difficult for viewers to understand the patterns being shown accurately.</li>



<li>Overloading the map with too much data: It&#8217;s possible to add too much data to a heat map, which can make it difficult to interpret and potentially obscure important patterns. It&#8217;s important to balance the need for detail with the need for clarity when creating a heat map.</li>



<li>Visual distortion: When working with large or irregularly shaped regions, it can be challenging to depict the data using a heat map accurately. This can lead to visual distortion, where the map does not accurately reflect the actual distribution of the data.</li>



<li>Misinterpretation of the data: Heat maps are a visual representation of data, which can be subject to misinterpretation. It&#8217;s important to carefully consider how the data is represented and provide clear context and explanations for the presented patterns.</li>
</ol>



<p>Let&#8217;s keep these potential pitfalls in mind during the following tutorial.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">What is GeoPandas?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>GeoPandas is a Python package that provides tools for working with geospatial data. It extends the popular pandas package, which provides data manipulation and analysis tools, to include support for geographic data. GeoPandas allows users to manipulate and analyze geospatial data in a familiar pandas DataFrame structure and includes functions for reading and writing spatial data in various formats, as well as tools for visualizing and mapping data. </p>



<p>GeoPandas is built on top of other popular packages, such as Shapely and Fiona, and is a popular choice for working with geospatial data in Python.</p>



<p>With GeoPandas, users can:</p>



<ol class="wp-block-list">
<li>Read and write spatial data in various formats, such as Shapefile, GeoJSON, and GeoPackage.</li>



<li>Perform geometric operations on spatial data, such as buffering, intersection, and union.</li>



<li>Create maps and visualize spatial data using matplotlib, a popular Python plotting library.</li>



<li>Analyze and manipulate spatial data in a pandas DataFrame structure, allowing users to use the powerful data manipulation and analysis tools provided by pandas.</li>
</ol>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">Creating Geographic Heat Maps with Python and GeoPandas</h2>



<p>In this tutorial, we will learn how to create geographic heat maps using Python and the GeoPandas package. Geographic heat maps are visualizations that show the intensity of data at different locations on a map. They are commonly used to represent the distribution of a variable across a geographic area, and can be useful for identifying patterns, trends, and anomalies in the data. In this tutorial, we will learn how to create geographic heat maps using Python and the GeoPandas package. In the following, we will walk through the steps of loading, manipulating, and visualizing spatial data with GeoPandas, and demonstrate how to create geographic heat maps for covid-19.</p>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_63bafd-55"><a class="kb-button kt-button button kb-btn_753aa7-f4 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/00%20Data%20Visualization/070%20Geographic%20Heatmaps%20using%20Python.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_5b88f4-b4 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p>Before starting the coding part, make sure that you have set up your <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer noopener">Python 3</a> environment and required packages. If you don&#8217;t have an environment set up yet, you can follow&nbsp;the steps in <a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a>&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>.</p>



<p>Also, make sure you install all required packages. We will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><a href="https://docs.python.org/3/library/math.html" target="_blank" rel="noreferrer noopener">math</a></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p>You can install packages using console commands:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">pip install &lt;package name&gt;
conda install &lt;package name&gt; (if you are using the anaconda packet manager)</pre></div>



<p>We will create geographic heat maps with the GeoPandas Python library. You can install GeoPandas via the console by using the following command:</p>



<ul class="wp-block-list">
<li>conda install &#8211;channel conda-forge geopandas</li>



<li>pip install geopandas</li>
</ul>



<p>Update (2020-09-23): With the release of Python 3.8, there is a new <a href="https://geopandas.org/install.html" target="_blank" rel="noreferrer noopener">install procedure</a>:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">conda create -n geo_env
conda activate geo_env
conda config --env --add channels conda-forge
conda config --env --set channel_priority strict
conda install python=3 geopandas</pre></div>



<h3 class="wp-block-heading" id="h-download-the-geographic-map-data-from-naturalearthdata">Download the Geographic Map Data From Naturalearthdata</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>First, we will get the map with the geospatial data. Rendering maps with GeoPandas requires a shapefile. A shapefile is a DataFrame with some graphical data attached. For instance, some shapefiles show cities, countries, continents, or maps of the entire world. So in our case, the shapefile is a list of countries, whereby each country has its graphical representation in polygons. The example presented in this tutorial will use a world map.</p>



<p>Various sources on the web provide shapefiles for different geographical regions and in varying detail. For example, <a href="https://www.naturalearthdata.com/downloads/10m-cultural-vectors/">n</a><a href="https://www.naturalearthdata.com/downloads/10m-cultural-vectors/" target="_blank" rel="noreferrer noopener">aturalearthdata.com</a> provides a map of the world. To download the map, go to the natualearthdata webpage, and with a click on the green button, you can download version 4.1.0.</p>



<p>Once the download is complete, unpack the files into the folder of your Python notebook or a subfolder in the folder of your Python notebook (e.g., data/shapefiles/worldmap/).</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="295" data-permalink="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/image-14/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/04/image-14.png" data-orig-size="616,212" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-14" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/04/image-14.png" src="https://www.relataly.com/wp-content/uploads/2020/04/image-14.png" alt="natualearthdata.com geographic shapefiles " class="wp-image-295" width="295" height="102" srcset="https://www.relataly.com/wp-content/uploads/2020/04/image-14.png 616w, https://www.relataly.com/wp-content/uploads/2020/04/image-14.png 300w" sizes="(max-width: 295px) 100vw, 295px" /><figcaption class="wp-element-caption"><a href="https://www.naturalearthdata.com/downloads/10m-cultural-vectors/" target="_blank" rel="noreferrer noopener">naturalearthdata.com</a></figcaption></figure>
</div>
</div>



<h3 class="wp-block-heading" id="h-step-1-loading-the-covid-19-data">Step #1 Loading the COVID-19 Data </h3>



<p>Next, we retrieve the COVID-19 data for all countries via the statworx API. If you want to learn more about using REST APIs, check out this tutorial<a href="https://www.relataly.com/access-data-sources-using-apis-in-python/278/" target="_blank" rel="noreferrer noopener"> on accessing data sources via REST APIs</a>. </p>



<p>Also: <a href="https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/" target="_blank" rel="noreferrer noopener">Accessing Remote Data Sources via REST APIs in Python</a></p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Setting up Packages
import json
import country_converter as coco
from datetime import datetime, timedelta
import requests
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
# Getting the data
PAYLOAD = {'code': 'ALL'}
URL = 'https://api.statworx.com/covid'
RESPONSE = requests.post(url=URL, data=json.dumps(PAYLOAD))
# Convert the response to a data frame
covid_df = pd.DataFrame.from_dict(json.loads(RESPONSE.text))
covid_df.head(3)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">      date		day	month	year	cases	deaths	country		code	population	continent	cases_cum	deaths_cum
0	2019-12-31	31	12		2019	0		0		Afghanistan	AF		38041757.0	Asia		0			0
1	2020-01-01	1	1		2020	0		0		Afghanistan	AF		38041757.0	Asia		0			0
2	2020-01-02	2	1		2020	0		0		Afghanistan	AF		38041757.0	Asia		0			0</pre></div>



<p>We continue by preparing the COVID-19 data for visualizing them on a heat map.</p>



<h3 class="wp-block-heading" id="h-step-2-specifying-a-shapefile">Step #2 Specifying a Shapefile</h3>



<p>Next, we use the Geopandas library to read in a shapefile at &#8220;data/shapefiles/worldmap/ne_10m_admin_0_countries.shp&#8221;. We then select the columns &#8220;ADMIN,&#8221; &#8220;ADM0_A3&#8221;, and &#8220;geometry&#8221; from the shapefile and store them in a GeoDataFrame called &#8220;geo_df.&#8221; Finally, we display the first three rows of the GeoDataFrame.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Setting the path to the shapefile
SHAPEFILE = 'data/shapefiles/worldmap/ne_10m_admin_0_countries.shp'
# Read shapefile using Geopandas
geo_df = gpd.read_file(SHAPEFILE)[['ADMIN', 'ADM0_A3', 'geometry']]
# Rename columns.
geo_df.columns = ['country', 'country_code', 'geometry']
geo_df.head(3)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">	country		country_code	geometry
0	Indonesia	IDN				MULTIPOLYGON (((117.70361 4.16341, 117.70361 4...
1	Malaysia	MYS				MULTIPOLYGON (((117.70361 4.16341, 117.69711 4...
2	Chile		CHL				MULTIPOLYGON (((-69.51009 -17.50659, -69.50611</pre></div>



<p>We have created a dataframe with three columns, as you can see above. The column geometry contains the graphical representation of countries. Now that we have prepared the data, we can plot our first geographic map. We create the map by using the GeoPandas plot function.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Drop row for 'Antarctica'. It takes a lot of space in the map and is not of much use
geo_df = geo_df.drop(geo_df.loc[geo_df['country'] == 'Antarctica'].index)
# Print the map
geo_df.plot(figsize=(20, 20), edgecolor='white', linewidth=1, color='lightblue')</pre></div>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="420" data-attachment-id="8034" data-permalink="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/map-of-the-world-python/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/map-of-the-world-python.png" data-orig-size="1158,475" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="map-of-the-world-python" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/map-of-the-world-python.png" src="https://www.relataly.com/wp-content/uploads/2022/04/map-of-the-world-python-1024x420.png" alt="Geographic map of the world. This is an empty shema we will use as the basis for color-coded geo heatmpaps. " class="wp-image-8034" srcset="https://www.relataly.com/wp-content/uploads/2022/04/map-of-the-world-python.png 1024w, https://www.relataly.com/wp-content/uploads/2022/04/map-of-the-world-python.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/map-of-the-world-python.png 768w, https://www.relataly.com/wp-content/uploads/2022/04/map-of-the-world-python.png 1158w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div class="wp-block-kadence-infobox kt-info-box_729bf0-5d"><span class="kt-blocks-info-box-link-wrap info-box-link kt-blocks-info-box-media-align-left kt-info-halign-left"><div class="kt-blocks-info-box-media-container"><div class="kt-blocks-info-box-media kt-info-media-animate-none"><div class="kadence-info-box-icon-container kt-info-icon-animate-none"><div class="kadence-info-box-icon-inner-container"><span class="kb-svg-icon-wrap kb-svg-icon-fe_alertCircle kt-info-svg-icon"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12" y2="16"/></svg></span></div></div></div></div><div class="kt-infobox-textcontent"><p class="kt-blocks-info-box-text">If you get an error: &#8220;ImportError: The Descartes package is required for plotting polygons in GeoPandas.&#8221; you first have to install the Descartes package. You can do this by typing in your console: <code>conda install descartes</code></p></div></span></div>



<h3 class="wp-block-heading" id="h-step-3-bringing-it-all-together">Step #3 Bringing It All Together</h3>



<p>Next, we need to ensure that our data matches the country codes. The dataframe with the geospatial data of the world map contains country codes that adhere to iso3. However, our COVID-19 data uses iso2_codes. Luckily there is a country_converter available that does this job for us:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Next, we need to ensure that our data matches with the country codes. 
iso3_codes = geo_df['country'].to_list()
# Convert to iso3_codes
iso2_codes_list = coco.convert(names=iso3_codes, to='ISO2', not_found='NULL')
# Add the list with iso2 codes to the dataframe
geo_df['iso2_code'] = iso2_codes_list
# There are some countries for which the converter could not find a country code. 
# We will drop these countries.
geo_df = geo_df.drop(geo_df.loc[geo_df['iso2_code'] == 'NULL'].index)</pre></div>



<p>We have a list with all nations&#8217; names (country) and codes (country_code). An additional column includes the geographical representation of each country.</p>



<h3 class="wp-block-heading" id="h-step-4-preprocessing">Step #4 Preprocessing</h3>



<p>Our COVID-19 data so far contains historical Covid-19 cases. We want to drop these historical cases and only get the data from the last day. Then we merge the data frames. </p>



<p>Before we plot the heat map, we have to specify a variable that determines the color of the countries on the map. Our goal is to color the countries depending on the growth rate of COVID-19 cases per day. The formula for the growth rate is &#8216;new cases&#8217; / total present cases. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># We want to drop the history and only get the data from the last day
d = datetime.today()-timedelta(days=1)
date_yesterday = d.strftime(&quot;%Y-%m-%d&quot;)
# Preparing the data
covid_df = covid_df[covid_df['date'] == date_yesterday]
# Merge the two dataframes
merged_df = pd.merge(left=geo_df, right=covid_df, how='left', left_on='iso2_code', right_on='code')
# Delete some columns that we won't use
df = merged_df.drop(['day', 'month', 'year', 'country_y', 'code'], axis=1)
#Create the indicator values
df['case_growth_rate'] = round(df['cases']/df['cases_cum'], 2)
df['case_growth_rate'].fillna(0, inplace=True) 
df.head(3)</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">	country_x	country_code		geometry												iso2_code	date		cases	deaths	population	continent	cases_cum	deaths_cum	case_growth_rate
0	Indonesia	IDN					MULTIPOLYGON 	(((117.70361 4.16341, 117.70361 4...	ID			2020-06-28	1385.0	37.0	270625567.0	Asia		52812.0		2720.0		0.03
1	Malaysia	MYS					MULTIPOLYGON 	(((117.70361 4.16341, 117.69711 4...	MY			2020-06-28	10.0	0.0		31949789.0	Asia		8616.0		121.0		0.00
2	Chile		CHL					MULTIPOLYGON 	(((-69.51009 -17.50659, -69.50611...	CL			2020-06-28	4406.0	279.0	18952035.0	America		267766.0	5347.0		0.02</pre></div>



<h3 class="wp-block-heading" id="h-step-5-creating-a-geographic-heat-map">Step #5 Creating a Geographic Heat Map</h3>



<p>In the previous step, we set up the data for our map. Next, we create the geographical heat map for the world. </p>



<p>We set the path to the shapefile and use Geopandas to read it. We then rename these columns. Next, we set the range for the choropleth and create a figure and axes for Matplotlib. We remove the axis and plot the choropleth using the data from the &#8216;df&#8217; dataframe and the &#8216;case_growth_rate&#8217; column, setting the edgecolor, linewidth, and cmap. We also add a title to the map and an annotation for the data source. Additionally, we create a colorbar as a legend, using the ScalarMappable function, and add it to the figure with a specified position.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Print the map
# Set the range for the choropleth
title = 'Daily COVID-19 Growth Rates'
col = 'case_growth_rate'
source = 'Source: relataly.com \nGrowth Rate = New cases / All previous cases'
vmin = df[col].min()
vmax = df[col].max()
cmap = 'viridis'
# Create figure and axes for Matplotlib
fig, ax = plt.subplots(1, figsize=(20, 8))
# Remove the axis
ax.axis('off')
df.plot(column=col, ax=ax, edgecolor='0.8', linewidth=1, cmap=cmap)
# Add a title
ax.set_title(title, fontdict={'fontsize': '25', 'fontweight': '3'})
# Create an annotation for the data source
ax.annotate(source, xy=(0.1, .08), xycoords='figure fraction', horizontalalignment='left', 
            verticalalignment='bottom', fontsize=10)
            
# Create colorbar as a legend
sm = plt.cm.ScalarMappable(norm=plt.Normalize(vmin=vmin, vmax=vmax), cmap=cmap)
# Empty array for the data range
sm._A = []
# Add the colorbar to the figure
cbaxes = fig.add_axes([0.15, 0.25, 0.01, 0.4])
cbar = fig.colorbar(sm, cax=cbaxes)</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="363" data-permalink="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/image-41/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/04/image-41.png" data-orig-size="1155,500" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-41" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/04/image-41.png" src="https://www.relataly.com/wp-content/uploads/2020/04/image-41-1024x443.png" alt="Geographic heat map showing COVID-19 growth rates in different countries of the world" class="wp-image-363" width="1097" height="474" srcset="https://www.relataly.com/wp-content/uploads/2020/04/image-41.png 1024w, https://www.relataly.com/wp-content/uploads/2020/04/image-41.png 300w, https://www.relataly.com/wp-content/uploads/2020/04/image-41.png 768w, https://www.relataly.com/wp-content/uploads/2020/04/image-41.png 1155w" sizes="(max-width: 1097px) 100vw, 1097px" /><figcaption class="wp-element-caption">Geographic heat map showing COVID-19 growth rates in different countries of the world</figcaption></figure>



<p>As shown in the map above, countries in Central Asia and Africa currently report the highest COVID-19 growth rates. </p>



<p>There are different color palettes. You can use them by altering the cmap variable. Below is a sample of ready-to-use color scales. You can find more color scales on the <a href="https://matplotlib.org/tutorials/colors/colormaps.html" target="_blank" rel="noreferrer noopener">matblotlib page</a>.</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="311" data-permalink="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/image-25/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/04/image-25.png" data-orig-size="627,454" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-25" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/04/image-25.png" src="https://www.relataly.com/wp-content/uploads/2020/04/image-25.png" alt="Color scales, useful for creating geographic heat maps" class="wp-image-311" width="314" height="227" srcset="https://www.relataly.com/wp-content/uploads/2020/04/image-25.png 627w, https://www.relataly.com/wp-content/uploads/2020/04/image-25.png 300w" sizes="(max-width: 314px) 100vw, 314px" /><figcaption class="wp-element-caption">Colormaps</figcaption></figure>



<h3 class="wp-block-heading" id="h-step-6-zooming-in-on-specific-regions">Step #6 Zooming in on Specific Regions</h3>



<p>We have observed that many African countries are currently reporting rising case numbers, so we create a new dataframe based on a filter for African countries using the list of country codes.</p>



<p>In the following, we create a geographic map specifically for Africa. We can zoom in on a continent or a country by filtering our dataframe. The code below will filter the spatial-geo data to African countries and plot the heat map. We plot the map for Africa using this new dataframe, setting the title of the map to &#8216;COVID-19 Growth Rate per Day in Africa&#8217; and adding a source annotation to the bottom left corner of the map.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># The map shows that many african countries are currently reporting increasing case numbers
# Next we create a new df based on a filter for african countries
africa_country_list = ['ZM', 'BF', 'TZ', 'EG', 'UG', 'TN', 'TG', 'SZ', 'SD', 
                       'EH', 'SS', 'ZW', 'ZA', 'SO', 'SL', 'SC', 'SN', 'ST', 
                       'SH', 'RW', 'RE', 'GW', 'NG', 'NE', 'NA', 'MZ', 'MA', 
                       'MU', 'MR', 'ML', 'MW', 'MG', 'LY', 'LR', 'LS', 'KE', 
                       'CI', 'GN', 'GH', 'GM', 'GA', 'DJ', 'ER', 'ET', 'GQ', 
                       'BJ', 'CD', 'CG', 'YT', 'KM', 'TD', 'CF', 'CV', 'CM', 
                       'BI', 'BW', 'AO', 'DZ']
africa_map_df = df[df['iso2_code'].isin(africa_country_list)]
# Plot the map for Africa
title = 'COVID-19 Growth Rate per Day in Africa'
col = 'case_growth_rate'
source = 'Source: relataly.com \nGrowth Rate = New cases / All previous cases'
vmin = df[col].min()
vmax = df[col].max()
fig, ax = plt.subplots(1, figsize=(20, 9))
ax.axis('off')
africa_map_df.plot(column=col, ax=ax, edgecolor='0.8', linewidth=1, cmap=cmap)
ax.set_title(title, fontdict={'fontsize': '25', 'fontweight': '3'})
ax.annotate(source, xy=(0.24, .08), xycoords='figure fraction',
            horizontalalignment='left',
            verticalalignment='bottom', fontsize=10)
sm = plt.cm.ScalarMappable(norm=plt.Normalize(vmin=vmin, vmax=vmax), cmap=cmap)
cbaxes = fig.add_axes([0.35, 0.25, 0.01, 0.5])
{&quot;type&quot;:&quot;block&quot;,&quot;srcIndex&quot;:53,&quot;srcClientId&quot;:&quot;2ddd9666-6def-46e0-803e-4bf7b0366a27&quot;,&quot;srcRootClientId&quot;:&quot;&quot;}cbar = fig.colorbar(sm, cax=cbaxes)</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="664" height="557" data-attachment-id="7660" data-permalink="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/output-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/output-1.png" data-orig-size="664,557" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="output-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/output-1.png" src="https://www.relataly.com/wp-content/uploads/2022/04/output-1.png" alt="geographic map of Affirca, colored by covid-19 cases. created with geopandas in python" class="wp-image-7660" srcset="https://www.relataly.com/wp-content/uploads/2022/04/output-1.png 664w, https://www.relataly.com/wp-content/uploads/2022/04/output-1.png 300w" sizes="(max-width: 664px) 100vw, 664px" /><figcaption class="wp-element-caption">Geographic heat map of Africa showing COVID-19 growth rates in different countries</figcaption></figure>



<p class="has-kb-palette-1-color has-text-color">In case you encounter an error with the mapclassify-package, you can try the following command to reinstall it: conda install -c conda-forge mapclassify</p>



<p>Voilá, now we only see the African continent. The map shows that the countries in Africa that currently report the highest total case numbers are South Africa, Algeria, Morocco, Kamerun, and Egypt. </p>



<p>Let&#8217;s take a look at the total cases per country in Africa: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Insert cases per population
# Alternative: africa_map_df2['cases_population'] = round(africa_map_df['cases_cum'] / africa_map_df['population'] * 100)
africa_map_df2 = africa_map_df.copy()
# Remove NAs
africa_map_df2.loc[: , 'cases_cum'].fillna(0, inplace=True)
# Show the data
africa_map_df2.head()
# Plot the map
title = 'Total COVID-19 Cases on the African Continent'
col = 'cases_cum'
source = 'Source: relataly.com '
vmin = africa_map_df2[col].min()
vmax = africa_map_df2[col].max()
fig, ax = plt.subplots(1, figsize=(20, 9))
ax.axis('off')
africa_map_df2.plot(column=col, ax=ax, edgecolor='1', linewidth=1, cmap=cmap)
ax.set_title(title, fontdict={'fontsize': '25', 'fontweight' : '3'})
ax.annotate(
    source, xy=(0.24, .08), xycoords='figure fraction', horizontalalignment='left', 
    verticalalignment='bottom', fontsize=10)
sm = plt.cm.ScalarMappable(norm=plt.Normalize(vmin=vmin, vmax=vmax), cmap=cmap)
cbaxes = fig.add_axes([0.35, 0.25, 0.01, 0.5])
cbar = fig.colorbar(sm, cax=cbaxes)</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="494" data-permalink="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/image-59/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/04/image-59.png" data-orig-size="701,557" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-59" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/04/image-59.png" src="https://www.relataly.com/wp-content/uploads/2020/04/image-59.png" alt="Geographic heat map of Africa showing COVID-19 total cases in different countries, created with geopandasin python" class="wp-image-494" width="553" height="440" srcset="https://www.relataly.com/wp-content/uploads/2020/04/image-59.png 701w, https://www.relataly.com/wp-content/uploads/2020/04/image-59.png 300w" sizes="(max-width: 553px) 100vw, 553px" /></figure>



<p>The highest growth rate was reported by South Sudan, followed by Botswana and Niger.</p>



<h3 class="wp-block-heading" id="h-step-7-saving-a-geo-heat-maps-to-png">Step #7 Saving a Geo-Heat Maps to PNG</h3>



<p>If you want to save the map, you can do this with the following command.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Safe the map to a png
fig.savefig('map_export.png', dpi=300)</pre></div>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>This article showed how to create geographic heat maps using the Geopandas library in Python. It showed how to read in a shapefile and create a choropleth map using the data from a dataframe. Additionally, the article explained how to filter the data to display maps of specific regions, in this case Africa. We showed how to prepare spatial data and color-code the maps using COVID-19 data. In addition, we filtered the DataFrame to create maps for specific regions, zoom in on specific areas, and alter the color style using different color maps. </p>



<p>Geographic heat maps can provide valuable insights into the distribution of data and help to identify patterns and trends. The technique of creating heat maps with Geopandas is a powerful tool for data visualization and can be applied to a wide range of geographical data.</p>



<p>I hope this article was helpful. If you have any questions or remarks, please write them in the comments.</p>



<p>Looking for more exciting map visualizations? Consider this relataly tutorial on <a href="https://www.relataly.com/predicting-crime-types-in-san-francisco-creatingsf-crime-map-using-xgboost/2960/" target="_blank" rel="noreferrer noopener">predicting and visualizing crimes on a map of San Francisco.</a></p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<p><a href="https://geopandas.org/en/stable/getting_started.html">https://geopandas.org/en/stable/getting_started.html</a></p>
<p>The post <a href="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/">Geographic Heat Maps with GeoPandas: Visualizing COVID-19 Data in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">291</post-id>	</item>
		<item>
		<title>Correlation Matrix in Python: How Correlated are COVID-19 Cases and Different Financial Assets?</title>
		<link>https://www.relataly.com/stock-market-correlation-matrix-in-python/103/</link>
					<comments>https://www.relataly.com/stock-market-correlation-matrix-in-python/103/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sun, 05 Apr 2020 16:08:00 +0000</pubDate>
				<category><![CDATA[Correlation]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Seaborn]]></category>
		<category><![CDATA[Stock Market Forecasting]]></category>
		<category><![CDATA[Yahoo Finance API]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[Correlation Matrix]]></category>
		<category><![CDATA[Covid-19 Analytics]]></category>
		<category><![CDATA[Cryptocurrencies]]></category>
		<category><![CDATA[Pearson Correlation]]></category>
		<category><![CDATA[Time Series Correlation]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=103</guid>

					<description><![CDATA[<p>Correlation analysis is a powerful tool in financial market analysis, helping investors to better understand the interdependence of different assets. But what happens when an unprecedented global pandemic like COVID-19 shakes up the market? In this tutorial, we will show you how to create a correlation matrix in Python that will help you visualize the ... <a title="Correlation Matrix in Python: How Correlated are COVID-19 Cases and Different Financial Assets?" class="read-more" href="https://www.relataly.com/stock-market-correlation-matrix-in-python/103/" aria-label="Read more about Correlation Matrix in Python: How Correlated are COVID-19 Cases and Different Financial Assets?">Read more</a></p>
<p>The post <a href="https://www.relataly.com/stock-market-correlation-matrix-in-python/103/">Correlation Matrix in Python: How Correlated are COVID-19 Cases and Different Financial Assets?</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Correlation analysis is a powerful tool in financial market analysis, helping investors to better understand the interdependence of different assets. But what happens when an unprecedented global pandemic like COVID-19 shakes up the market? In this tutorial, we will show you how to create a correlation matrix in Python that will help you visualize the relationship between COVID-19 and various financial assets.</p>



<p>First, we will delve into the nitty-gritty of correlation coefficients and how to interpret them. We&#8217;ll focus specifically on the Pearson Correlation Coefficient, a popular measure used to quantify the strength of the relationship between two variables.</p>



<p>Next, we&#8217;ll dive right into the practical part of this tutorial and create a stock market correlation matrix in Python. Our matrix will measure the correlation between COVID-19 cases and various financial assets such as gold, Bitcoin, and other popular investments. With this matrix, investors can identify the extent to which COVID-19 has impacted different asset classes and make more informed investment decisions.</p>



<p>Whether you&#8217;re a seasoned investor or just starting out, this tutorial will equip you with the knowledge and tools you need to analyze the correlation between COVID-19 and financial markets. So, let&#8217;s dive in and start exploring the fascinating world of correlation analysis!</p>



<p>Also: <a href="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/" target="_blank" rel="noreferrer noopener">Color-coded Cryptocurrency Price Charts with Python</a> </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image is-resized"><img decoding="async" src="https://www.relataly.com/wp-content/uploads/2020/05/image-45.png" alt="A correlation matrix, as we will create it in this article" width="376" height="335"/><figcaption class="wp-element-caption">A correlation matrix, as we will create it in this article.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Different Types of Correlation Coefficients</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>There are various types of correlation coefficients used to measure the strength and direction of the relationship between two variables. The most common is the Pearson correlation coefficient, which measures the linear relationship between two variables. This is the correlation coefficient on which we will focus in this article. However, if the relationship between two variables is more complex, other coefficients are a better choice for the analysis.  </p>



<p>For example, in situations where the data is not normally distributed or when there are outliers, the Spearman correlation coefficient is used. This coefficient measures the relationship between two variables using ranks instead of the actual data. It is also known as the rank correlation coefficient. For ordinal data, the Kendall correlation coefficient is used. This coefficient measures the strength and direction of the relationship between two variables, taking into account the order of the data points. Finally, the Point-Biserial and Biserial correlation coefficients are used when one variable is dichotomous and the other is continuous. These coefficients measure the strength and direction of the relationship between these variables.</p>



<p>Let&#8217;s take a closer look at Pearson Correlation. </p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading" id="h-pearson-correlation">Pearson Correlation</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The Pearson correlation coefficient r is a standard measure for quantifying a linear relationship between two variables. In other words, r is a measure of how strongly two continuous variables (for example, price or volume) tend to make similar changes. For the Pearson correlation coefficient to return a meaningful value, the following conditions must be met:</p>



<ul class="wp-block-list">
<li>Both variables, x and y, are metrically scaled and continuous.</li>



<li>The relationship between the two variables is approximately linear.</li>



<li>The two samples of the variables x and y are independent of each other.</li>
</ul>



<p>Correlation measures how much two variables are associated. The Pearson correlation is calculated by dividing the covariance of two variables (x, y) by their standard deviations.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<div class="wp-block-mathml-mathmlblock">\[r = \frac{s_{xy}}{s_x\ast s_y}\ =\ \frac{\sum{x_iy_i\ -\ n\bar{x}\bar{y}}}{\sqrt{\sum{x_i^2\ -\ n{\bar{x}}^2}}\sqrt{\sum{y_i^{2\ }-\ n{\bar{y}}^2}}}\]<script src="https://www.relataly.com/wp-includes/js/dist/hooks.min.js?ver=dd5603f07f9220ed27f1" id="wp-hooks-js"></script>
<script src="https://www.relataly.com/wp-includes/js/dist/i18n.min.js?ver=c26c3dc7bed366793375" id="wp-i18n-js"></script>
<script id="wp-i18n-js-after">
wp.i18n.setLocaleData( { 'text direction\u0004ltr': [ 'ltr' ] } );
//# sourceURL=wp-i18n-js-after
</script>
<script  async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML" id="mathjax-js"></script>
</div>
</div>
</div>



<h2 class="wp-block-heading" id="h-interpreting-the-pearson-correlation-coefficient">Interpreting the Pearson Correlation Coefficient</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The value of r is restricted to the range between 1 and -1. Interpreting r requires us to differentiate the following cases:</p>



<ul class="wp-block-list">
<li>The closer r is to 1, the stronger the relationship is, and the better the points (Xi / Yi) fit on the regression line.</li>



<li>The closer r is to 0, the weaker the correlation is, and the more widely are the points spread around the regression line.</li>



<li>The extreme cases r = 1 or r = -1 result from a functional relation, defined by a linear equation of y = a + b*x can be described exactly. In this case, all points (xi / Yi) is located on the regression line.</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="1205" data-permalink="https://www.relataly.com/stock-market-correlation-matrix-in-python/103/correlation-representation/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation.png" data-orig-size="1919,439" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="correlation-representation" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation.png" src="https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation-1024x234.png" alt="correlation matrix, pearson correlation, Python" class="wp-image-1205" width="792" height="181" srcset="https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation.png 1024w, https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation.png 300w, https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation.png 768w, https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation.png 1536w, https://www.relataly.com/wp-content/uploads/2020/05/correlation-representation.png 1919w" sizes="(max-width: 792px) 100vw, 792px" /><figcaption class="wp-element-caption">Graphical representation of different correlation coefficients</figcaption></figure>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Be aware that the correlation coefficient is often subject to misinterpretation. For example, an empirical correlation coefficient whose value is &gt; 0 merely states that we can prove a relation based on a sample. However, it does not explain why this relationship exists. In addition, if r ~ 0 does not mean that the two variables are independent. Instead, it only means that we cannot prove a linear relation.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading" id="h-implementing-a-correlation-matrix-in-python">Implementing a Correlation Matrix in Python</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>In the following, we&#8217;ll dig deep into the data and analyze the spread of COVID-19 cases and casualties. To create this correlation matrix, we&#8217;ll utilize the Pandas library, a fantastic tool for data analysis that enables us to work with data in a variety of formats.</p>



<p>First, we&#8217;ll load our data into a Pandas DataFrame, allowing us to manipulate and calculate correlations with ease. We&#8217;ll then use the corr() method to compute the correlation coefficients between the different asset classes and COVID-19. This generates a matrix that provides a clear view of the correlations between our variables.</p>



<p>To make this information more visually appealing, we&#8217;ll create a heatmap using the Seaborn library. This heatmap will enable us to easily identify which asset classes are strongly correlated with COVID-19 and which are not.</p>



<p>By creating a correlation matrix in Python, we can gain invaluable insights into the relationship between COVID-19 and the financial market. This knowledge can help us make informed investment decisions by identifying patterns and trends. So let&#8217;s dive in and create a correlation matrix that reveals the connection between COVID-19 and the financial market!</p>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_9ba519-0b"><a class="kb-button kt-button button kb-btn_1acaaa-9e kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/00%20Data%20Visualization/112%20Correlation%20Matrix%20-%20COVID-19%20and%20Financial%20Assets.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_1bc280-ef kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p>Before starting the coding part, make sure that you have set up your <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer noopener">Python 3</a> environment and required packages. If you don’t have an environment set up yet, you can follow&nbsp;<a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a>&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>. Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><a href="https://docs.python.org/3/library/math.html" target="_blank" rel="noreferrer noopener">math</a></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p>In addition, we will be using the <a href="https://pandas-datareader.readthedocs.io/en/latest/" target="_blank" rel="noreferrer noopener">pandas-DataReader</a> package and <a href="https://seaborn.pydata.org/" target="_blank" rel="noreferrer noopener">Seaborn</a> for visualization. You can install packages using console commands:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">pip install &lt;package name&gt;
conda install &lt;package name&gt; (if you are using the anaconda packet manager)</pre></div>



<h3 class="wp-block-heading" id="h-step-1-load-data">Step #1 Load Data</h3>



<p>We begin by loading data about historic COVID-19 cases and price Information on different financial assets. </p>



<h4 class="wp-block-heading" id="h-1-1-load-historic-covid-19-data">1.1 Load Historic COVID-19 Data</h4>



<p>We begin by downloading the COVID-19 data. For this purpose, we will use the Statworx API. It provides historical time series data on the number of COVID-19 cases in different countries. In addition, the data contains the number of casualties. If you are not yet familiar with APIs, consider my recent <a href="https://www.relataly.com/access-data-sources-using-apis/278/" target="_blank" rel="noreferrer noopener">tutorial on working with APIs in Python.</a></p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># A tutorial for this file is available at www.relataly.com

# Imports
import pandas as pd
import pandas_datareader as web
import numpy as np
from datetime import datetime
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import requests
import json
from pandas.plotting import register_matplotlib_converters

# Load second Dataset with Corona Cases
payload = {&quot;code&quot;: &quot;ALL&quot;}
URL = &quot;https://api.statworx.com/covid&quot;
response = requests.post(url=URL, data=json.dumps(payload))
df_covid = pd.DataFrame.from_dict(json.loads(response.text))
# df_covid = df_covid[df_covid['code'] == 'US']

# Add the date column as variable
df_covid[&quot;Date&quot;] = pd.to_datetime(df_covid[&quot;date&quot;])

# Delete some columns that we won't use
df_covid.drop(
    [&quot;day&quot;, &quot;month&quot;, &quot;year&quot;, &quot;country&quot;, &quot;code&quot;, &quot;population&quot;, &quot;date&quot;],
    axis=1,
    inplace=True,
)

# Summarize cases over all countries
df_covid = df_covid.groupby([&quot;Date&quot;]).sum()
df_covid.head()</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">			cases	deaths	cases_cum	deaths_cum
Date				
2019-12-31	27		0		27			0
2020-01-01	0		0		27			0
2020-01-02	0		0		27			0
2020-01-03	17		0		44			0
2020-01-04	0		0		44			0</pre></div>



<h4 class="wp-block-heading" id="h-1-2-loading-data-on-selected-financial-assets">1.2 Loading Data on Selected Financial Assets</h4>



<p>We continue by downloading historical price data on different financial assets. For this purpose, we use the Yahoo Finance API. We limit the period to the time after the first documented COVID-19 cases. When you execute the code of this tutorial as it is, you will receive price information for the following financial assets: </p>



<div class="wp-block-columns are-vertically-aligned-top is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-vertically-aligned-top is-layout-flow wp-block-column-is-layout-flow">
<p><strong>Stock Market Indexes</strong></p>



<ul class="wp-block-list">
<li>S&amp;P500</li>



<li>DAX </li>



<li>Niki</li>



<li>N225</li>



<li>S&amp;P500 Futures </li>
</ul>
</div>



<div class="wp-block-column is-vertically-aligned-top is-layout-flow wp-block-column-is-layout-flow">
<p><strong>Stocks: Online Services</strong></p>



<ul class="wp-block-list">
<li>Amazon</li>



<li>Netflix</li>



<li>Apple</li>



<li>Google</li>



<li>Microsoft</li>
</ul>



<p><strong>Stocks: Airlines</strong></p>



<ul class="wp-block-list">
<li>Lufthansa Stock</li>



<li>American Airlines</li>
</ul>
</div>



<div class="wp-block-column is-vertically-aligned-top is-layout-flow wp-block-column-is-layout-flow">
<p><strong>Resource</strong> <strong>Futures</strong></p>



<ul class="wp-block-list">
<li>Crude Oil Price</li>



<li>Gold </li>



<li>Soybean Price </li>
</ul>



<p></p>



<p><strong>Treasury Bonds</strong> <strong>Futures</strong></p>



<ul class="wp-block-list">
<li>US Treasury Bonds</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p><strong>Exchange Rates</strong></p>



<ul class="wp-block-list">
<li>EUR-USD</li>



<li>CHF-EUR</li>



<li>GBP-USD</li>



<li>GBP-EUR</li>



<li><br></li>
</ul>



<p><strong>Crypto Currencies</strong></p>



<ul class="wp-block-list">
<li>BTC-USD</li>



<li>ETH-USD</li>
</ul>
</div>
</div>



<p>Be aware that stock symbols can change from time to time. If the API does not find a specific stock symbol, you have to look up the current Symbol on Yahoo Finance.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">df_covid_new = df_covid.copy()

# Read the data for different assets
today_date = datetime.today().strftime(&quot;%Y-%m-%d&quot;)
start_date = &quot;2020-01-01&quot;
asset_dict = {
    &quot;^GSPC&quot;: &quot;SP500&quot;,
    &quot;DAX&quot;: &quot;DAX&quot;,
    &quot;^N225&quot;: &quot;N225&quot;,
    &quot;ES=F&quot;: &quot;SP500FutJune20&quot;,
    &quot;LHA.DE&quot;: &quot;Lufthansa&quot;,
    &quot;AAL&quot;: &quot;AmericanAirlines&quot;,
    &quot;NFLX&quot;: &quot;Netflix&quot;,
    &quot;AMZN&quot;: &quot;Amazon&quot;,
    &quot;AAPL&quot;: &quot;Apple&quot;,
    &quot;MSFT&quot;: &quot;Microsoft&quot;,
    &quot;GOOG&quot;: &quot;Google&quot;,
    &quot;BTC-USD&quot;: &quot;BTCUSD&quot;,
    &quot;ETH-USD&quot;: &quot;ETHUSD&quot;,
    &quot;CL=F&quot;: &quot;Oil&quot;,
    &quot;GC=F&quot;: &quot;Gold&quot;,
    #&quot;SM=F&quot;: &quot;Soybean&quot;,
    &quot;ZB=F&quot;: &quot;UsTreasuryBond&quot;,
    &quot;GBPEUR=X&quot;: &quot;GBPEUR&quot;,
    &quot;EURUSD=X&quot;: &quot;EURUSD&quot;,
    &quot;CHFEUR=X&quot;: &quot;CHFEUR&quot;,
    &quot;GBPUSD=X&quot;: &quot;GBPUSD&quot;}

col_list = []
# Join the dataframes
for key, value in asset_dict.items():
    print(key, value)    
    try:
        df_temp = web.DataReader(
            key, start=start_date, end=today_date, data_source=&quot;yahoo&quot;)
    except ValueError: 
        print(f' {key} symbol not found')
    # convert index to Date Format
    df_temp.index = pd.to_datetime(df_temp.index) 
    df_temp.rename(columns={&quot;Close&quot;: value}, inplace=True) # Rename Close Column       
    df_covid_new = pd.merge(
        left=df_covid_new,
        right=df_temp[value],
        how=&quot;inner&quot;,
        left_index=True, right_index=True)     

df_covid_new.head()</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">	cases	deaths	cases_cum	deaths_cum	SP500	DAX			N225		SP500FutJune20	Lufthansa		AmericanAirlines	...	Google		BTCUSD		ETHUSD		Oil	Gold	UsTreasuryBond	GBPEUR	EURUSD	CHFEUR	GBPUSD
Date																					
2020-01-06	0		0			59			0		3246.280029	28.004999	23204.859375	3243.50	15.340	27.320000			...	1394.209961	7769.219238	144.304153	63.270000	1566.199951		157.84375	1.17169	1.116196	0.922110	1.308010
2020-01-07	0		0			59			0		3237.179932	27.955000	23575.720703	3235.25	15.365	27.219999			...	1393.339966	8163.692383	143.543991	62.700001	1571.800049		157.40625	1.17635	1.119799	0.922212	1.317003
2020-01-08	0		0			59			0		3253.050049	28.260000	23204.759766	3260.25	15.540	27.840000			...	1404.319946	8079.862793	141.258133	59.610001	1557.400024		156.37500	1.17551	1.115474	0.925181	1.311372
2020-01-09	0		0			59			0		3274.699951	28.450001	23739.869141	3276.00	16.160	27.950001			...	1419.829956	7879.071289	138.979202	59.560001	1551.699951		156.81250	1.17912	1.111321	0.924505	1.310513
2020-01-10	0		0			59			0		3265.350098	28.500000	23850.570312	3264.75	15.815	27.320000			...	1429.729980	8166.554199	143.963776	59.040001	1557.500000		157.62500	1.17620	1.111111	0.924796	1.307019
5 rows × 24 columns</pre></div>



<p>You can add assets of your choice to the asset list if you want. You can find the respective symbols on <a href="https://finance.yahoo.com/" target="_blank" rel="noreferrer noopener">finance.yahoo.com</a>. </p>



<h3 class="wp-block-heading" id="h-step-2-exploring-the-data"> Step #2 Exploring the Data</h3>



<p>Next, we will visualize the historical data using line charts.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Create lineplots
list_length = df_covid_new.shape[1]
ncols = 6
nrows = int(round(list_length / ncols, 0))
height = list_length/3 if list_length &gt; 30 else 16

fig, axs = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, figsize=(20, height))

for i, ax in enumerate(fig.axes):
        if i &lt; list_length:
            sns.lineplot(data=df_covid_new, x=df_covid_new.index, y=df_covid_new.iloc[:, i], ax=ax)
            ax.set_title(df_covid_new.columns[i])
            ax.tick_params(labelrotation=45)

plt.show()</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="826" data-attachment-id="8516" data-permalink="https://www.relataly.com/stock-market-correlation-matrix-in-python/103/lineplots-1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/05/lineplots-1.png" data-orig-size="1186,957" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="lineplots-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/05/lineplots-1.png" src="https://www.relataly.com/wp-content/uploads/2022/05/lineplots-1-1024x826.png" alt="lineplots, correlation matrix python" class="wp-image-8516" srcset="https://www.relataly.com/wp-content/uploads/2022/05/lineplots-1.png 1024w, https://www.relataly.com/wp-content/uploads/2022/05/lineplots-1.png 300w, https://www.relataly.com/wp-content/uploads/2022/05/lineplots-1.png 768w, https://www.relataly.com/wp-content/uploads/2022/05/lineplots-1.png 1186w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>We can easily spot pairs that seem to have experienced similar price developments. This does not mean, however, that these pairs are correlated.</p>



<h3 class="wp-block-heading" id="h-step-3-correlation-matrix">Step #3 Correlation Matrix </h3>



<p>Next, we will calculate the correlation matrix. Various Python libraries make this an easy task that only requires a few lines of code. We will use the standard math package for this purpose. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Plotting a diagonal correlation matrix
sns.set(style=&quot;white&quot;)

# Compute the correlation matrix
df = pd.DataFrame(df_covid_new, columns=col_list)
corr = df_covid_new.corr()
corr</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">					cases	deaths	cases_cum	deaths_cum	SP500	DAX	N225	SP500FutJune20	Lufthansa	AmericanAirlines	...	Google	BTCUSD	ETHUSD	Oil	Gold	UsTreasuryBond	GBPEUR	EURUSD	CHFEUR	GBPUSD
cases				1.000000	0.853512	0.972691	0.966481	0.663638	0.519676	0.660547	0.659832	-0.451801	-0.413463	...	0.796671	0.898456	0.899876	0.073393	0.719520	0.147347	-0.566227	0.843788	-0.538949	0.513913
deaths				0.853512	1.000000	0.778833	0.804270	0.399756	0.259080	0.400126	0.395697	-0.590251	-0.589090	...	0.567708	0.705201	0.718329	-0.228573	0.664476	0.399694	-0.574079	0.628463	-0.291254	0.245614
cases_cum			0.972691	0.778833	1.000000	0.974553	0.714616	0.571317	0.711905	0.711552	-0.379420	-0.325739	...	0.812816	0.922179	0.932026	0.142586	0.682001	0.059693	-0.516654	0.865846	-0.584541	0.584691
deaths_cum			0.966481	0.804270	0.974553	1.000000	0.712595	0.587606	0.681964	0.709312	-0.498761	-0.441631	...	0.808086	0.875724	0.925765	0.097746	0.805602	0.193165	-0.626253	0.902159	-0.603867	0.529622
SP500				0.663638	0.399756	0.714616	0.712595	1.000000	0.960100	0.956142	0.999766	0.140961	0.205127	...	0.944084	0.806056	0.801970	0.623960	0.553991	-0.359058	-0.043646	0.738902	-0.791377	0.853893
DAX					0.519676	0.259080	0.571317	0.587606	0.960100	1.000000	0.934535	0.960816	0.246646	0.304234	...	0.860881	0.678125	0.688038	0.715992	0.500840	-0.387279	-0.002362	0.685518	-0.844509	0.826270
N225				0.660547	0.400126	0.711905	0.681964	0.956142	0.934535	1.000000	0.956710	0.240638	0.281306	...	0.922091	0.829050	0.761729	0.655562	0.425364	-0.436453	-0.005655	0.673853	-0.790071	0.810057
SP500FutJune20		0.659832	0.395697	0.711552	0.709312	0.999766	0.960816	0.956710	1.000000	0.147155	0.211133	...	0.943475	0.804529	0.799886	0.627447	0.549565	-0.363198	-0.039701	0.736997	-0.792258	0.855152
Lufthansa			-0.451801	-0.590251	-0.379420	-0.498761	0.140961	0.246646	0.240638	0.147155	1.000000	0.964624	...	-0.006089	-0.135931	-0.296115	0.629831	-0.665533	-0.853762	0.815127	-0.388975	-0.107357	0.262015
AmericanAirlines	-0.413463	-0.589090	-0.325739	-0.441631	0.205127	0.304234	0.281306	0.211133	0.964624	1.000000	...	0.026610	-0.115151	-0.245080	0.658176	-0.603162	-0.877327	0.790366	-0.312451	-0.143469	0.330665
Netflix				0.750950	0.701806	0.721492	0.840104	0.601819	0.523924	0.493603	0.596449	-0.637187	-0.578967	...	0.672056	0.614683	0.749042	-0.027917	0.914606	0.438247	-0.652950	0.766065	-0.460004	0.338608
Amazon				0.801935	0.710040	0.776041	0.887487	0.669833	0.597223	0.564001	0.665996	-0.591990	-0.528531	...	0.732905	0.672651	0.809639	0.049571	0.936733	0.365580	-0.664869	0.848771	-0.562987	0.428907
Apple				0.840178	0.631516	0.862322	0.917166	0.843786	0.765495	0.750124	0.841533	-0.357089	-0.275023	...	0.860493	0.800416	0.906042	0.295665	0.851025	0.081060	-0.499164	0.927081	-0.719334	0.673724
Microsoft			0.772067	0.647593	0.751721	0.849898	0.792196	0.723458	0.689305	0.788468	-0.416892	-0.354098	...	0.833358	0.723236	0.819949	0.206249	0.871319	0.209342	-0.496853	0.807662	-0.598330	0.529434
Google				0.796671	0.567708	0.812816	0.808086	0.944084	0.860881	0.922091	0.943475	-0.006089	0.026610	...	1.000000	0.902355	0.866670	0.492750	0.593879	-0.219884	-0.174525	0.765421	-0.713271	0.770065
BTCUSD				0.898456	0.705201	0.922179	0.875724	0.806056	0.678125	0.829050	0.804529	-0.135931	-0.115151	...	0.902355	1.000000	0.942019	0.315591	0.568836	-0.099474	-0.285379	0.777073	-0.620303	0.685506
ETHUSD				0.899876	0.718329	0.932026	0.925765	0.801970	0.688038	0.761729	0.799886	-0.296115	-0.245080	...	0.866670	0.942019	1.000000	0.242502	0.740186	0.068097	-0.419289	0.886153	-0.644605	0.696074
Oil					0.073393	-0.228573	0.142586	0.097746	0.623960	0.715992	0.655562	0.627447	0.629831	0.658176	...	0.492750	0.315591	0.242502	1.000000	-0.035808	-0.685471	0.344647	0.261168	-0.615400	0.626496
Gold				0.719520	0.664476	0.682001	0.805602	0.553991	0.500840	0.425364	0.549565	-0.665533	-0.603162	...	0.593879	0.568836	0.740186	-0.035808	1.000000	0.485554	-0.672429	0.815864	-0.489188	0.381673
UsTreasuryBond		0.147347	0.399694	0.059693	0.193165	-0.359058	-0.387279	-0.436453	-0.363198	-0.853762	-0.877327	...	-0.219884	-0.099474	0.068097	-0.685471	0.485554	1.000000	-0.667468	0.154001	0.278546	-0.412731
GBPEUR				-0.566227	-0.574079	-0.516654	-0.626253	-0.043646	-0.002362	-0.005655	-0.039701	0.815127	0.790366	...	-0.174525	-0.285379	-0.419289	0.344647	-0.672429	-0.667468	1.000000	-0.586152	0.230223	0.187170
EURUSD				0.843788	0.628463	0.865846	0.902159	0.738902	0.685518	0.673853	0.736997	-0.388975	-0.312451	...	0.765421	0.777073	0.886153	0.261168	0.815864	0.154001	-0.586152	1.000000	-0.756216	0.686032
CHFEUR				-0.538949	-0.291254	-0.584541	-0.603867	-0.791377	-0.844509	-0.790071	-0.792258	-0.107357	-0.143469	...	-0.713271	-0.620303	-0.644605	-0.615400	-0.489188	0.278546	0.230223	-0.756216	1.000000	-0.711504
GBPUSD				0.513913	0.245614	0.584691	0.529622	0.853893	0.826270	0.810057	0.855152	0.262015	0.330665	...	0.770065	0.685506	0.696074	0.626496	0.381673	-0.412731	0.187170	0.686032	-0.711504	1.000000
24 rows × 24 columns</pre></div>



<p>The matrix shows the Pearson correlation coefficients of all the pairs (X, Y) in our dataset.</p>



<h3 class="wp-block-heading" id="h-step-4-visualizing-the-correlation-matrix-in-a-heatmap">Step #4 Visualizing the Correlation Matrix in a Heatmap </h3>



<p>Heatmaps are an excellent choice for visualizing a correlation matrix. The heatmap applies a color palette to represent numeric values on a scale in different colors. This makes it easier to capture differences and similarities among the correlation coefficients. In Python, we can create heatmaps using the <a href="https://seaborn.pydata.org/" target="_blank" rel="noreferrer noopener">Seaborn package</a>. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=np.bool))

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))

# Generate a custom diverging colormap
cmap = &quot;RdBu&quot;

# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(
    corr,
    mask=mask,
    cmap=cmap,
    center=0,
    square=True,
    linewidths=0.5,
    cbar_kws={&quot;shrink&quot;: 0.5},
)</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="672" height="598" data-attachment-id="1240" data-permalink="https://www.relataly.com/stock-market-correlation-matrix-in-python/103/image-45-2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/image-45.png" data-orig-size="672,598" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-45" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/image-45.png" src="https://www.relataly.com/wp-content/uploads/2020/05/image-45.png" alt="Visualization of the Correlation Matrix in Form of a Heatmap" class="wp-image-1240" srcset="https://www.relataly.com/wp-content/uploads/2020/05/image-45.png 672w, https://www.relataly.com/wp-content/uploads/2020/05/image-45.png 300w" sizes="(max-width: 672px) 100vw, 672px" /><figcaption class="wp-element-caption">Visualization of the Correlation Matrix in the form of a Heatmap</figcaption></figure>



<p>The correlation matrix is symmetric. This is because the correlation between a pair of variables X and Y is the same as between Y and X.</p>



<h3 class="wp-block-heading" id="h-step-5-interpretation">Step #5 Interpretation</h3>



<p>The heatmap uses a color palette that ranges from blue (positive correlation) over white (no correlation) to red (negative correlation). The different shades of the three colors visualize the extent of the correlation. We can distinguish between correlated pairs, uncorrelated pairs, and negatively correlated pairs. We will compare the different asset classes step by step in the following.</p>



<h4 class="wp-block-heading" id="h-5-1-stock-market-indices-covid-19">5.1 Stock Market Indices / COVID-19</h4>



<p>Let us start with the pairs of Stock market indices and COVID-19 data. The heatmap signals a negative correlation between the indices (DAX, S&amp;P500, NIKI) and COVID-19. In other words, when the number of cases rises, stock market indices tend to fall in value. If we look precisely, the total number of new cases seems more correlated than the number of cases (cases_cum) or deaths (deaths_cum). In addition, one can observe that the stock market indices are correlated.</p>



<h4 class="wp-block-heading" id="h-5-2-stock-market-indices-online-service-provider-stocks">5.2 Stock Market Indices / Online Service Provider Stocks</h4>



<p>The situation is heterogeneous when we compare the stock markets with the shares of online service providers. There is a positive correlation between the shares of Microsoft and Google and the overall development of the markets. On the other hand, the shares of Netflix, Amazon, and Apple are hardly correlated with market development.</p>



<h4 class="wp-block-heading" id="h-5-3-stock-market-indices-airline-stocks">5.3 Stock Market Indices / Airline Stocks </h4>



<p>Airlines are heavily affected by the pandemic. Thus it is plausible that we observe a strong positive correlation between airline stocks and the general stock market indices. </p>



<h4 class="wp-block-heading" id="h-5-4-stock-market-indices-crypto-currencies">5.4 Stock Market Indices / Crypto-Currencies</h4>



<p>Next, we compare Cryptocurrencies with the stock market indices. The results are surprising. BTC-USD correlates surprisingly strong positive with the general development of the stock markets. However, the correlation is only slightly positive for ETH-USD and the markets.</p>



<h4 class="wp-block-heading" id="h-5-5-covid-19-currency-exchange-rates">5.5 COVID-19 / Currency Exchange Rates</h4>



<p>The correlation between exchange rates and COVID-19 cases is relatively weak. Only GBP/EUR, EUR/USD, and GBP/USD show a slightly negative correlation. An exception is CHF/EUR, which positively correlates to the number of COVID-19 cases. </p>



<h4 class="wp-block-heading" id="h-5-6-treasury-bonds-resources">5.6 Treasury Bonds / Resources</h4>



<p>Looking at the coefficients of resources and US Treasury Bonds, we can observe a strong negative correlation between COVID-19 cases and the oil price and a strong positive correlation with the gold price.</p>



<h4 class="wp-block-heading" id="h-5-7-crypto-currencies-resources">5.7 Crypto-Currencies / Resources</h4>



<p>Finally, let us consider the coefficients of resources and cryptocurrencies. It is noticeable that BTCUSD correlates with the oil price. Based on the absence of a correlation with gold, one might conclude that BTC-USD is not a comparable crisis currency. However, the correlation between market indices and cryptocurrencies such as ETH-USD is relatively low. Thus, they were less affected by the recent market slump.</p>



<p>Also: <a href="https://www.relataly.com/stock-market-prediction-using-multivariate-time-series-in-python/1815/" target="_blank" rel="noreferrer noopener">Stock Market Prediction using Multivariate Data</a> </p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>Congratulation, you have reached the end of this tutorial! In this article, we have load data on COVID-19 and financial assets via an API. We have created a correlation matrix in Python that shows the linear correlation between financial assets and COVID-19 cases. Finally, we have visualized the matrix in a heatmap and concluded the correlation of different asset pairs. However, we must remember that we may still be unaware of potential non-linear correlations.</p>



<p>Please show your appreciation by leaving a like or comment if you found this article helpful. </p>



<p>And if you are interested to learn more about an advanced use case for correlation analysis, please take a look at <a href="https://www.relataly.com/crypto-market-cluster-analysis-using-affinity-propagation-python/8114/" target="_blank" rel="noreferrer noopener">this article on clustering cryptocurrencies</a>.</p>



<h2 class="wp-block-heading" id="h-sources-and-further-reading"><strong>Sources and Further Reading</strong></h2>



<ul class="wp-block-list">
<li><a href="https://www.youtube.com/watch?v=qtaqvPAeEJY&amp;t=117s" target="_blank" rel="noreferrer noopener">YouTube tutorial that explains the math behind the correlation</a></li>



<li><a href="https://amzn.to/3MAy8j5" target="_blank" rel="noreferrer noopener">Andriy Burkov (2020) Machine Learning Engineering</a></li>



<li><a href="https://www.relataly.com/crypto-market-cluster-analysis-using-affinity-propagation-python/8114/" target="_blank" rel="noreferrer noopener">Uncover Hidden Patterns in Financial Markets using Affinity Propagation Clustering in Python</a></li>
</ul>



<p>Images created with Midjourney.</p>
<p>The post <a href="https://www.relataly.com/stock-market-correlation-matrix-in-python/103/">Correlation Matrix in Python: How Correlated are COVID-19 Cases and Different Financial Assets?</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/stock-market-correlation-matrix-in-python/103/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">103</post-id>	</item>
		<item>
		<title>Accessing Remote Data Sources via REST APIs in Python</title>
		<link>https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/</link>
					<comments>https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sun, 01 Mar 2020 13:15:00 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Sources]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Statworx COVID-19 API]]></category>
		<category><![CDATA[Tech]]></category>
		<category><![CDATA[Yahoo Finance API]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Covid-19 Analytics]]></category>
		<category><![CDATA[Requesting Data via REST APIs]]></category>
		<category><![CDATA[Transaction Data]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=278</guid>

					<description><![CDATA[<p>REST APIs provide straightforward access to remote data sources. Data scientists should learn about REST APIs because APIs (Application Programming Interfaces) are an important way for data scientists to access data from other sources. By using REST APIs, data scientists can access data from a wide range of sources, including databases, web services, and other ... <a title="Accessing Remote Data Sources via REST APIs in Python" class="read-more" href="https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/" aria-label="Read more about Accessing Remote Data Sources via REST APIs in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/">Accessing Remote Data Sources via REST APIs in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%"></div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<p>REST APIs provide straightforward access to remote data sources. Data scientists should learn about REST APIs because APIs (Application Programming Interfaces) are an important way for data scientists to access data from other sources. By using REST APIs, data scientists can access data from a wide range of sources, including databases, web services, and other applications. This allows data scientists to easily integrate data from different sources and use it in their analysis and modeling. Additionally, knowing how to use REST APIs can also be useful for data scientists who want to share their own data or models with others by building APIs that can be accessed by other applications. This article briefly describes how to access remote data sources via REST APIs in Python.</p>



<p>The article proceeds as follows: We begin with a brief introduction to RESTful APIs. Then,  we will look at two examples of how to access remote APIs. We will define API requests, learn about parameters, and request data from an API. We will handle the response and save it to a dataframe or a local CSV file. </p>



<p>Also: <a href="https://www.relataly.com/accessing-twitter-data-via-the-twitter-rest-api/1976/" target="_blank" rel="noreferrer noopener">Streaming Tweets and Images via the Twitter API in Python</a></p>



<h2 class="wp-block-heading" id="h-what-is-an-api">What is an API?</h2>



<p>In Data Science, REST APIs are often used as a modern shortcut to consume remote data sources and services on the internet or make them available to others. Whether these sources are publicly available or reside in corporate networks, data scientists need to understand how to work with API. In the broader sense, an API is a contract between the provider and the consumer of a web service, who communicate and exchange data. The agreement is necessary because communication can lead to misunderstandings, for example, when one party sends information that is not as expected. The contract avoids such misunderstandings by defining standards for what the parties communicate and how it is communicated. </p>



<h2 class="wp-block-heading" id="h-what-are-restful-apis">What are RESTful APIs?</h2>



<p>A popular architectural style used to design APIs is the Representational State Transfer (REST) standard. REST has become very popular in recent years and is often considered a more straightforward and modern alternative to the traditional Simple Object Access Protocol (SOAP). Both SOAP and REST are based on established rules, compliance with which is the basis of automated information exchange. However, in data science, REST is now the most common.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" data-attachment-id="1145" data-permalink="https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/rest-apis/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/REST-APIs.png" data-orig-size="1241,689" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="REST-APIs" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/REST-APIs.png" src="https://www.relataly.com/wp-content/uploads/2020/05/REST-APIs-1024x569.png" alt="Working with REST APIs in Python " class="wp-image-1145" width="609" height="337" srcset="https://www.relataly.com/wp-content/uploads/2020/05/REST-APIs.png 1024w, https://www.relataly.com/wp-content/uploads/2020/05/REST-APIs.png 300w, https://www.relataly.com/wp-content/uploads/2020/05/REST-APIs.png 768w, https://www.relataly.com/wp-content/uploads/2020/05/REST-APIs.png 1241w" sizes="(max-width: 609px) 100vw, 609px" /><figcaption class="wp-element-caption">Communication via an API</figcaption></figure>
</div>


<p>If you work with public APIs in Python, you will most likely use the REST protocol. A service provider that operates a REST API exposes an URL that receives requests. Requests to the resource URL can have a JSON, HTML, or XML format payload. A REST API will typically return the response in JSON format, but other formats, such as comma-separated values (CSV), are also possible. REST defines different HTTP methods (GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS and TRACE). However, the most important ones are:</p>



<ul class="wp-block-list">
<li><strong>GET: </strong>Used to request data from a data provider.</li>



<li><strong>POST</strong>: Typically used to send new data to the service provider. Sometimes also used to define the data that the APIs returns in response to subsequent requests.</li>



<li><strong>PUT: </strong>Used to update data at the service provider.</li>
</ul>



<p>Next, let&#8217;s look at how we can interact with RET APIs in Python. </p>



<h2 class="wp-block-heading">How can we interact with REST APIs in Python?</h2>



<p>There are several ways to access REST APIs in Python, including:</p>



<ol class="wp-block-list">
<li>Using the requests library: The requests library is a popular Python library for making HTTP requests. It provides a simple, intuitive API for sending and receiving requests, and supports a wide range of HTTP methods, such as GET, POST, and DELETE.</li>



<li>Using the urllib library: The urllib library is a built-in Python library for working with URLs and HTTP requests. It provides a lower-level API than the requests library but is still relatively easy to use and allows you to customize your requests in more detail.</li>



<li>Using the HTTP.client library: The HTTP.client library is another built-in Python library for working with HTTP requests. It provides a more comprehensive and robust set of tools for working with HTTP requests but may require more programming effort to use than the other options.</li>



<li>Service-specific libraries: Many popular online services can be accessed using Python libraries that offer built-in functionality for interacting with REST-based APIs. For example, Twitter, Reddit, or Yahoo Finance offer libraries that make interacting with their REST APIs much easier. </li>
</ol>



<p>The choice of which Python library to use for accessing REST APIs will depend on your specific needs and preferences. You may want to try out a few different options and see which one works best for your project. In the following tutorial, we will work with the requests library.</p>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading" id="h-requesting-historical-covid-19-data-from-the-statworx-api-with-the-request-library">Requesting historical COVID-19 Data from the Statworx API with the Request Library</h3>



<p>There are many APIs out there that provide more or less reliable data on COVID-19 cases. A good one to use is <a href="https://api.statworx.com/covid" target="_blank" rel="noreferrer noopener">api.statworx.com/covid</a>. This API offers historical data on the number of COVID-19 cases. The API is very accessible since it does not require an authentication key. </p>



<p>In the following, we will go through two different cases on how to request data from REST APIs in Python. First, we use the <a href="https://pypi.org/project/requests/" target="_blank" rel="noreferrer noopener">Requests library</a> to request COVID-19 data from the statworx library. We will call this API using the request package, a standard package to interact with APIs in Python. An alternative would be to use a Python package that provides API-specific functions to interact with the API. We will look at this case in the second example. </p>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_8e4103-8f"><a class="kb-button kt-button button kb-btn_640363-e3 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials/blob/main/101%20Pulling%20COVID-19%20Data%20via%20the%20Statworx%20API%20to%20a%20DataFrame.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_43b657-b3 kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p>Before starting the coding part, ensure you have set up your <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer noopener">Python 3</a> environment and required libraries. If you don&#8217;t have an environment, follow&nbsp;the steps in <a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a>&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>.</p>



<p>Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><a href="https://docs.python.org/3/library/math.html" target="_blank" rel="noreferrer noopener">math</a></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p>You can install packages using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>



<li><em>conda install &lt;package name&gt;</em>&nbsp;(if you are using the anaconda packet manager)</li>
</ul>



<p>In addition, we will be working with the <a href="https://github.com/psf/requests" target="_blank" rel="noreferrer noopener">Requests library</a>. The requests library is a standard HTTP library that interacts with REST APIs. It provides functionality to send an HTTP request to an API and receive a response. Since the requests library is a native Python, you usually won&#8217;t need to install it.</p>



<h4 class="wp-block-heading" id="h-step-1-define-the-payload">Step #1 Define the Payload</h4>



<p>In order to make a request to an API, it is necessary to specify the URL that the request should be sent to. This URL is typically provided by the API documentation and may include certain parameters or queries to specify the specific data that you want to retrieve. For example, you might want to specify a specific date range or filter the results by a certain category.</p>



<p>In the following, we send a post request to the statworx.com API and get back COVID-19 data in JSON format as a response. We can then convert the response into a dataframe. With the following code, we can send an HTTP request to the URL provided and will get the requested data back in JSON format:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># the data is provided from the european centre for disease prevention and control
from datetime import date
import requests
import json
import pandas as pd
# import matplotlib.pyplot as plt

# define the payload that will be sent to the api endpoint, and the endpoint url
# code defines the countries for which we will retrieve data
# to retrieve data for specific countries use e.g. {'country': 'Germany'}
payload = {&quot;code&quot;: &quot;ALL&quot;}  
URL = &quot;https://api.statworx.com/covid&quot;</pre></div>



<p>We can change the data to get back in the response by altering the parameters in our request. For example, we have specified the country code as &#8220;US&#8221; in the payload. Thus, the response contains only COVID-19 data for the US. If we want data for all countries, we need to set the code to ALL. </p>



<h4 class="wp-block-heading" id="h-step-2-call-the-rest-api-endpoint">Step #2 Call the REST API Endpoint</h4>



<p>Once you have defined the URL, you can use Python&#8217;s built-in &#8220;requests&#8221; library to send an HTTP request to the API and retrieve the data. This can be done using the &#8220;get&#8221; method, which sends a GET request to the specified URL and returns a response object containing the data returned by the API.</p>



<p>It is also important to consider any authentication or authorization requirements that the API may have. The statworx API does not require authentication. However, some APIs may require you to provide a valid API key or other credentials in order to access the data. These requirements will also be specified in the API documentation.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># call the api
response = requests.post(url=URL, data=json.dumps(payload))
response # if the request was successful, you should see a response code 200</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">&lt;Response [200]&gt;</pre></div>



<h4 class="wp-block-heading" id="h-step-3-convert-the-data-to-a-dataframe">Step #3 Convert the Data to a DataFrame</h4>



<p>When making an API request using Python, the API will typically return a response in JSON format. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is often used as a default data format in REST APIs because it is easy to work with and can be easily converted into other data formats such as CSV or Pandas DataFrames.</p>



<p>A common way to handle the response from an API is to convert it into a DataFrame using the &#8220;JSON&#8221; method of the Pandas library. This method takes a JSON object or a list of JSON objects and converts it into a DataFrame. Once the data is in a DataFrame, it can be easily processed and analyzed using the various tools and functions provided by Pandas.</p>



<p>It is also possible to directly parse the JSON response using Python&#8217;s built-in &#8220;JSON&#8221; module. This can be useful if you want to extract specific pieces of data from the response or if you want to perform additional processing on the data before converting it into a DataFrame.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># convert the response data to a data frame
df = pd.DataFrame.from_dict(json.loads(response.text))
df</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">	date		day	month	year	cases	deaths	country		code	population	continent	cases_cum	deaths_cum
0	2019-12-31	31	12		2019	0		0		Afghanistan	AF		38041757.0	Asia		0			0
1	2020-01-01	01	01		2020	0		0		Afghanistan	AF		38041757.0	Asia		0			0
2	2020-01-02	02	01		2020	0		0		Afghanistan	AF		38041757.0	Asia		0			0
3	2020-01-03	03	01		2020	0		0		Afghanistan	AF		38041757.0	Asia		0			0
4	2020-01-04	04	01		2020	0		0		Afghanistan	AF		38041757.0	Asia		0			0
...	...			...	...		...		...		...		...			...		...			...			...			...</pre></div>



<h4 class="wp-block-heading" id="h-step-4-filter-the-data">Step #4 Filter the Data</h4>



<p>Now let&#8217;s make something out of the data and create a simple plot. Our goal is to create a lineplot that shows how cases have developed for different countries. As part of the data preprocessing, we will reduce the data to include a smaller number of selected countries. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># convert date column to date format
df.loc[:, &quot;date&quot;] = pd.to_datetime(df[&quot;date&quot;], format=&quot;%Y-%m-%d&quot;)

# filter specific countries
list_of_countries = [&quot;Germany&quot;, &quot;Switzerland&quot;, &quot;France&quot;, &quot;Spain&quot;, &quot;Canada&quot;]
df_1 = df[df[&quot;country&quot;].isin(list_of_countries)]

# filter the data to a specific timeframe
df_new = df_1[df_1[&quot;date&quot;] &gt; &quot;2020-01-15&quot;]
df_new.head()</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">		date		day	month	year	cases	deaths	country	code	population	continent	cases_cum	deaths_cum
10332	2020-01-16	16	01		2020	0		0		Canada	CA		37411038.0	America		0			0
10333	2020-01-17	17	01		2020	0		0		Canada	CA		37411038.0	America		0			0
10334	2020-01-18	18	01		2020	0		0		Canada	CA		37411038.0	America		0			0
10335	2020-01-19	19	01		2020	0		0		Canada	CA		37411038.0	America		0			0
10336	2020-01-20	20	01		2020	0		0		Canada	CA		37411038.0	America		0			0</pre></div>



<h4 class="wp-block-heading" id="h-step-5-plot-the-case-counts">Step #5 Plot the Case Counts</h4>



<p>Finally, we use Matplotlib to create a lineplot that visualizes the data that we have received from the API. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># create separate plot lines for each country in the dataset
fig, ax1 = plt.subplots(figsize=(12, 8))
plt.ylabel(&quot;Total Cases&quot;, fontsize=20, color=&quot;black&quot;)
for countryname in list_of_countries:
    x = df_new[df_new[&quot;country&quot;] == countryname][&quot;date&quot;]
    y = df_new[df_new[&quot;country&quot;] == countryname][&quot;cases_cum&quot;]
    plt.plot(x, y, label=countryname)

plt.legend(list_of_countries, loc=&quot;upper left&quot;)
plt.show()</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="729" height="477" data-attachment-id="3817" data-permalink="https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/image-44-3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/04/image-44.png" data-orig-size="729,477" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-44" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/04/image-44.png" src="https://www.relataly.com/wp-content/uploads/2021/04/image-44.png" alt="" class="wp-image-3817" srcset="https://www.relataly.com/wp-content/uploads/2021/04/image-44.png 729w, https://www.relataly.com/wp-content/uploads/2021/04/image-44.png 300w" sizes="(max-width: 729px) 100vw, 729px" /></figure>



<p>If your chart looks similar to the one above, you can be confident that you have successfully loaded the data into our project. </p>



<div style="height:16px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>In conclusion, this tutorial has demonstrated how to use REST APIs in Python to access and retrieve data from remote sources. We used the statworx API to fetch COVID-19 data and used the Pandas library to convert the data into a DataFrame. We also created a small sample plot to visualize the number of COVID-19 cases in different countries.</p>



<p>By following the steps outlined in this tutorial, you should now be able to use Python to access and work with data from a variety of sources using REST APIs. This can be a powerful tool for data scientists and analysts, allowing them to easily retrieve and analyze data from a wide range of sources in order to gain insights and make informed decisions.</p>



<p>I hope this post was helpful. If you have any remarks or questions, let me know.</p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<ol class="wp-block-list">
<li><a href="https://www.statworx.com/en/content-hub/blog/making-of-a-free-api-for-covid-19-data/"></a><a href="https://www.statworx.com/en/content-hub/blog/making-of-a-free-api-for-covid-19-data/" target="_blank" rel="noreferrer noopener">statworx API</a></li>



<li><a href="https://pypi.org/project/requests/" target="_blank" rel="noreferrer noopener">https://pypi.org/project/requests/</a></li>
</ol>



<p><strong>Relataly API Tutorials</strong></p>


<ul class="wp-block-kadence-posts kb-posts kadence-posts-list kb-posts-id-_91f1a0-a4 content-wrap grid-cols kb-posts-style-boxed grid-sm-col-1 grid-lg-col-3 item-image-style-above"><li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-12143 post type-post status-publish format-standard has-post-thumbnail hentry category-language-generation category-machine-learning-marketing-automation category-natural-language-processing-nlp category-openai category-python-programming category-rest-apis tag-api-tutorials tag-beginner-tutorials tag-deep-learning">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-inherit" href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" aria-label="Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="382" src="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="OpenAI Dall-E ChatGPT Prompt Design Detailed Images Combining ChatGPT and Dall-E Midjourney" srcset="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 1530w, https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="13511" data-permalink="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-copy-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png" data-orig-size="1530,762" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546 &amp;#8211; Copy-min" data-image-description="&lt;p&gt;OpenAI Dall-E ChatGPT Prompt Design Detailed Images Combining ChatGPT and Dall-E Midjourney&lt;/p&gt;
" data-image-caption="&lt;p&gt;OpenAI Dall-E ChatGPT Prompt Design Detailed Images Combining ChatGPT and Dall-E Midjourney&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/01/Flo7up_a_robot_painting_a_picture_with_data_technology_and_ai_i_5e7ffa5e-06c3-436b-b4fa-3fc5af58e546-Copy-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/automated-prompt-generation-for-dall-e-using-chatgpt-in-python-a-step-by-step-api-tutorial/12143/" rel="bookmark">Generating Detailed Images with OpenAI DALL-E and ChatGPT in Python: A Step-By-Step API Tutorial</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-12068 post type-post status-publish format-standard has-post-thumbnail hentry category-natural-language-processing-nlp category-openai category-rest-apis tag-api-tutorials tag-beginner-tutorials tag-chatgpt tag-deep-learning">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-inherit" href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" aria-label="Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="300" src="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="unleashing the power of openai super hero robot gpt python ai value proposition chatgpt" srcset="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 1614w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png 1536w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="13197" data-permalink="https://www.relataly.com/openai-gpt-chatgpt-in-a-business-context-whats-the-value-proposition/12282/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png" data-orig-size="1614,631" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="unleashing the power of openai super hero robot gpt python ai-min" data-image-description="&lt;p&gt;unleashing the power of openai super hero robot gpt python ai value proposition chatgpt&lt;/p&gt;
" data-image-caption="&lt;p&gt;unleashing the power of openai super hero robot gpt python ai value proposition chatgpt&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/unleashing-the-power-of-openai-super-hero-robot-gpt-python-ai-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/using-chatgpt-and-other-openai-models-via-apis-in-python/12068/" rel="bookmark">Unleashing the Power of ChatGPT and Other OpenAI GPT Language Models in Python A Guide to Using APIs</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-10351 post type-post status-publish format-standard has-post-thumbnail hentry category-cryptocompare-api category-facebook-prophet category-finance category-python-programming category-rest-apis category-seaborn category-stock-market-forecasting category-time-series-forecasting category-use-case category-yahoo-finance-api tag-ai-in-finance tag-intermediate-tutorials tag-supervised-learning">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-inherit" href="https://www.relataly.com/time-series-forecasting-using-facebook-prophet-in-python/10351/" aria-label="Univariate Stock Market Forecasting using Facebook Prophet in Python">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="307" src="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="Univariate Stock Market Forecasting using Facebook Prophet in Python" srcset="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 1455w, https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="13377" data-permalink="https://www.relataly.com/stock-market-forecasting-python-relataly-midjourney-3-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png" data-orig-size="1455,582" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="stock market forecasting python relataly midjourney 3-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/stock-market-forecasting-python-relataly-midjourney-3-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/time-series-forecasting-using-facebook-prophet-in-python/10351/" rel="bookmark">Univariate Stock Market Forecasting using Facebook Prophet in Python</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-10098 post type-post status-publish format-standard has-post-thumbnail hentry category-blockchain-crypto-analytics category-correlation-machine-learning category-crypto-exchange-apis category-cryptocompare-api category-data-science category-finance category-python-programming category-rest-apis category-seaborn category-use-case tag-ai-in-finance tag-intermediate-tutorials">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-inherit" href="https://www.relataly.com/seven-metrics-for-on-chain-analysis-in-python/10098/" aria-label="On-Chain Analytics: Metrics for Analyzing Blockchains in Python">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="314" src="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="onchain-analysis - tutorial blockchain data in python CryptoCompare api" srcset="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 1262w, https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 1024w, https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="12339" data-permalink="https://www.relataly.com/blockchain-analysis-python-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png" data-orig-size="1262,516" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="blockchain analysis python-min" data-image-description="&lt;p&gt;onchain-analysis &amp;#8211; tutorial blockchain data in python  CryptoCompare api&lt;/p&gt;
" data-image-caption="&lt;p&gt;onchain-analysis &amp;#8211; tutorial blockchain data in python  CryptoCompare api&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/02/blockchain-analysis-python-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/seven-metrics-for-on-chain-analysis-in-python/10098/" rel="bookmark">On-Chain Analytics: Metrics for Analyzing Blockchains in Python</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-3982 post type-post status-publish format-standard has-post-thumbnail hentry category-finance category-gate-io-api category-python-programming category-rest-apis tag-ai-in-finance tag-api-tutorials tag-beginner-tutorials tag-bitcoin tag-cryptocurrencies">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-inherit" href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" aria-label="Requesting Crypto Price Data from the Gate.io REST API in Python">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="305" src="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="gatio cryptocurrency data api midjourney relataly-min" srcset="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 1358w, https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 512w, https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="12769" data-permalink="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/gatio-cryptocurrency-data-api-midjourney-relataly-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png" data-orig-size="1358,540" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="gatio cryptocurrency data api midjourney relataly-min" data-image-description="&lt;p&gt;gatio cryptocurrency data api midjourney relataly-min&lt;/p&gt;
" data-image-caption="&lt;p&gt;gatio cryptocurrency data api midjourney relataly-min&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/gatio-cryptocurrency-data-api-midjourney-relataly-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" rel="bookmark">Requesting Crypto Price Data from the Gate.io REST API in Python</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-3925 post type-post status-publish format-standard has-post-thumbnail hentry category-rest-apis category-twitter-api tag-ai-in-e-commerce tag-api-tutorials tag-automated-twitter-posts tag-beginner-tutorials tag-social-media-data tag-tweepy">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-inherit" href="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/" aria-label="Posting Tweets On Twitter using Python and Tweepy">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="306" src="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="twitter api gate to social mediadata relataly tutorial python" srcset="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 1390w, https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="12599" data-permalink="https://www.relataly.com/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png" data-orig-size="1390,554" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="twitter api gate to social mediadata relataly tutorial python" data-image-description="&lt;p&gt;twitter api gate to social mediadata relataly tutorial python&lt;/p&gt;
" data-image-caption="&lt;p&gt;twitter api gate to social mediadata relataly tutorial python&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/twitter-api-gate-to-social-mediadata-relataly-tutorial-python-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/posting-tweets-on-twitter-using-python-and-tweepy/3925/" rel="bookmark">Posting Tweets On Twitter using Python and Tweepy</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
<li class="kb-post-list-item">
	<article class="entry content-bg loop-entry post-3474 post type-post status-publish format-standard has-post-thumbnail hentry category-coinmarketcap-api category-rest-apis category-sqlite category-stock-market-forecasting tag-api-tutorials tag-beginner-tutorials tag-bitcoin tag-cryptocurrencies tag-peewee">
				<a aria-hidden="true" tabindex="-1" role="presentation" class="post-thumbnail kadence-thumbnail-ratio-inherit" href="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/" aria-label="Requesting Crypto Prices from the Coinmarketcap API using Python">
			<div class="post-thumbnail-inner">
				<img decoding="async" width="768" height="303" src="https://www.relataly.com/wp-content/uploads/2023/03/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min.png" class="attachment-medium_large size-medium_large wp-post-image" alt="coinmarketcap rest api python tutorial relataly midjourney" srcset="https://www.relataly.com/wp-content/uploads/2023/03/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min.png 1363w, https://www.relataly.com/wp-content/uploads/2023/03/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min.png 768w" sizes="(max-width: 768px) 100vw, 768px" data-attachment-id="12600" data-permalink="https://www.relataly.com/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min.png" data-orig-size="1363,538" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="coinmarketcap rest api python tutorial relataly midjourney" data-image-description="&lt;p&gt;coinmarketcap rest api python tutorial relataly midjourney&lt;/p&gt;
" data-image-caption="&lt;p&gt;coinmarketcap rest api python tutorial relataly midjourney&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/gateio-api-tutorial-relataly-machine-learning-gate-to-cryptocurrency-data-min.png" />			</div>
		</a><!-- .post-thumbnail -->
				<div class="entry-content-wrap">
			<header class="entry-header">
	<h2 class="entry-title"><a href="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/" rel="bookmark">Requesting Crypto Prices from the Coinmarketcap API using Python</a></h2></header><!-- .entry-header -->
<footer class="entry-footer">
	</footer><!-- .entry-footer -->		</div>
	</article>
</li>
</ul><p>The post <a href="https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/">Accessing Remote Data Sources via REST APIs in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/access-remote-data-sources-using-rest-apis-in-python/278/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">278</post-id>	</item>
	</channel>
</rss>
