<?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>Bitcoin Archives - relataly.com</title>
	<atom:link href="https://www.relataly.com/tag/bitcoin/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.relataly.com/tag/bitcoin/</link>
	<description>The Business AI Blog</description>
	<lastBuildDate>Sat, 27 May 2023 10:28:40 +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>Bitcoin Archives - relataly.com</title>
	<link>https://www.relataly.com/tag/bitcoin/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">175977316</site>	<item>
		<title>Requesting Crypto Price Data from the Gate.io REST API in Python</title>
		<link>https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/</link>
					<comments>https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Tue, 11 May 2021 09:17:14 +0000</pubDate>
				<category><![CDATA[Finance]]></category>
		<category><![CDATA[Gate.io API]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[REST APIs]]></category>
		<category><![CDATA[AI in Finance]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[Cryptocurrencies]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=3982</guid>

					<description><![CDATA[<p>In this tutorial, we will demonstrate how to use the Gate.io spot market API to stream cryptocurrency prices in real-time using Python. Streaming prices is crucial for implementing use cases such as analyzing an incoming stream of price data in real-time for generating trading signals or conducting price analytics. One of the benefits of using ... <a title="Requesting Crypto Price Data from the Gate.io REST API in Python" class="read-more" href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" aria-label="Read more about Requesting Crypto Price Data from the Gate.io REST API in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/">Requesting Crypto Price Data from the Gate.io REST API 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>In this tutorial, we will demonstrate how to use the Gate.io spot market API to stream cryptocurrency prices in real-time using Python. Streaming prices is crucial for implementing use cases such as analyzing an incoming stream of price data in real-time for generating trading signals or conducting price analytics. One of the benefits of using Gate.io for streaming prices is that it features many smaller cryptocurrencies that may not be available on larger exchanges like Coinbase or Binance. These smaller, more volatile cryptocurrencies can make for an interesting platform for price analysis and algorithmic trading. Despite being a smaller player in the cryptocurrency exchange market, ranking within the top 20, Gate.io offers a unique set of assets for traders to consider.</p>



<p>In the following, we take a quick look at the Gate.io <a href="https://www.gate.io/docs/apiv4/en/index.html#gate-api-v4" target="_blank" rel="noreferrer noopener">API documentation</a>. Then we will write a short Python script that pulls price information in regular intervals. We store the price data for each cryptocurrency in a Pandas DataFrame, with which you can then continue to work on your projects. </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 fetchpriority="high" decoding="async" data-attachment-id="7186" data-permalink="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/gate-io-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png" data-orig-size="1600,719" 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="gate.io-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png" src="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min-1024x460.png" alt="Crypto REST API Python Gate.io Tutorial" class="wp-image-7186" width="355" height="159" srcset="https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 1024w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 768w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 1536w, https://www.relataly.com/wp-content/uploads/2022/04/gate.io-min.png 1600w" sizes="(max-width: 355px) 100vw, 355px" /><figcaption class="wp-element-caption">Gate.io API provides access to historical prices for a wide range of cryptocurrencies.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading" id="h-about-the-gate-io-spotmarket-api">About the Gate.io Spotmarket API</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>Before we look at the market endpoint, it is crucial to understand that Gate.io offers multiple markets for different ways of trading cryptocurrencies. For example, there is a futures market, a spot market, and a margin market. Each of these markets has its HTTP REST API endpoint, which provides different operations. For example, there are operations for submitting buy and sell orders at the marketplace and retrieving price and order data. The <a href="https://www.gate.io/docs/apiv4/en/index.html#gate-api-v4" target="_blank" rel="noreferrer noopener">official API documentation</a> provides a complete list of these operations.</p>



<p id="h-gate-io-offers-several-apis">This tutorial will only work with the spot market API endpoint and the list_tickers operation. Unlike most other functions, the list_tickers operation does not require authentication. So, we don&#8217;t need to register as long we only want to retrieve price data. Another advantage is that there is no limit to API requests due to the lack of authentication.</p>



<p>The list_ticker operation returns a list of data fields for cryptocurrency pairs. Examples of price pairs are BTC_USD, BTC_ETH, BTC_ADA, etc. If we limit the returned data to a specific price pair (e.g., BTC_USD), we can pass a single pair as a variable in the API call. However, it is not possible to restrict multiple pairs. So, we either retrieve data for a single pair or all pairs. For each request, the API returns a list with the following data fields:</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-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" data-attachment-id="3994" data-permalink="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/image-5-12/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/05/image-5.png" data-orig-size="1030,584" 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-5" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/05/image-5.png" src="https://www.relataly.com/wp-content/uploads/2021/05/image-5-1024x581.png" alt="Crypto REST API Python Gate.io Tutorial: Response returned by the Gate.io API list_tickers operation" class="wp-image-3994" width="362" height="205" srcset="https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 1024w, https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 300w, https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 768w, https://www.relataly.com/wp-content/uploads/2021/05/image-5.png 1030w" sizes="(max-width: 362px) 100vw, 362px" /><figcaption class="wp-element-caption">The response returned by the Gate.io API list_tickers operation</figcaption></figure>
</div></div>
</div>



<h2 class="wp-block-heading" id="h-implementation-retrieving-regular-price-ticker-data-from-gate-io-with-python">Implementation: Retrieving Regular Price Ticker Data from Gate.io with Python</h2>



<p>Let&#8217;s start by implementing a short Python script that will periodically call the gate.io spot market endpoint and return a response. Each time we receive a response, we will process it. We will extract multiple price fields and append them as new records to a set of DataFrames. To do this, we use a separate DataFrame per crypto price pair. </p>



<p>We use a separate DataFrame per price pair to ease working with the data later. An alternative would be to store all price data in a single DataFrame. However, we usually want to work with price data for specific price pairs and do Analytics on them. It is easier to have all the corresponding data in one place and not have to filter it beforehand.</p>



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



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_ea7ba1-49"><a class="kb-button kt-button button kb-btn_79d52f-b1 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/126%20Getting%20Real-Time%20Price%20Data%20via%20the%20Gate.io%20API.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_a0bdc1-04 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>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>
</ul>



<p>In addition, we will be using the gate.io package (<a href="https://github.com/gateio/gateapi-python" target="_blank" rel="noreferrer noopener">package name gate-API</a>) to pull price data from the crypto exchange gate.io.</p>



<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>



<h3 class="wp-block-heading" id="h-step-1-connect-to-the-gate-io-api">Step #1: Connect to the Gate.io API</h3>



<p>First, we establish a connection to the API. We do this by creating a new api_client object and then using it as an argument to the spot API function. As a result, the gate_api library returns an api_instance that provides access to several API functions.  </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;}">import gate_api
from gate_api.exceptions import ApiException, GateApiException
import pandas as pd
import time
import datetime as dt

# Defining the host is optional and defaults to https://api.gateio.ws/api/v4
# See configuration.py for a list of all supported configuration parameters.
configuration = gate_api.Configuration(host = &quot;https://api.gateio.ws/api/v4&quot;)
api_client = gate_api.ApiClient(configuration)

# Create an instance of the API class
api_instance = gate_api.SpotApi(api_client)</pre></div>



<h3 class="wp-block-heading" id="h-step-2-define-functions-for-calling-the-api-and-handling-the-response">Step #2: Define Functions for Calling the API and Handling the Response</h3>



<p>Next, we create two functions. The first function contains a loop that calls the gate.io spot market list_tickers API. Every time we contact this endpoint, it will return a list with price information. We handle this data in a dictionary that contains a separate DataFrame for each cryptocurrency price pair. Managing the data means iterating through the response and extracting the price data per cryptocurrency pair. Each price data is handed over to our second function, &#8220;append_data_to_df,&#8221; which stores the data in its respective DataFrame.</p>



<p>The request_data function takes three arguments:</p>



<ul class="wp-block-list">
<li><strong>runs: </strong>this is how often we should call the API. </li>



<li>s: the interval in seconds in which we call the API</li>



<li>currency_pair: you can alternatively define a specific currency pair for which you want to retrieve price information. If none is specified, the API endpoint will return the complete list of all price pairs (currently ~ 270).</li>
</ul>



<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;}"># this function starts calling the Gate.io API
# the response will contains price data for multiple cryptocurrencies
# the price information of each cryptocurrency will be stored in its own dataframe
def request_data(runs, currency_pair, s):
    currency_dfs = {}
    for t in range(runs):

        try:
            api_response = api_instance.list_tickers(currency_pair=currency_pair)
        except GateApiException as ex:
            print(&quot;Gate api exception, label: %s, message: %s\n&quot; % (ex.label, ex.message))
        except ApiException as e:
            print(&quot;Exception when calling SpotApi-&gt;list_tickers: %s\n&quot; % e)

        ts = dt.datetime.now()
        currency_response_dict = {resp.currency_pair: resp for resp in api_response
                                if &quot;USDT&quot; in resp.currency_pair and &quot;BEAR&quot; not in resp.currency_pair}
                  
        for currency_name, response in currency_response_dict.items():
            try:
                currency_dfs[currency_name]
            except KeyError:
                # Create new dataframe if currency does not have one yet
                currency_dfs[currency_name] = pd.DataFrame(columns=[
                    'Symbol', 
                    'Timestamp', 
                    'Volume', 
                    'Price', 
                    'Price_Delta', 
                    'Price_Delta_Percent'])
            
            # get the price of the currency at the last price point
            if len(currency_dfs[currency_name]) &gt; 1:
                #print(currency_dfs[currency_name])
                price_before = currency_dfs[currency_name]['Price'].iloc[-1]
            else:
                price_before = 0
            
            # append a new record the dataframe of this currency
            new_data_as_dict = append_data_to_df(price_before, response, ts)
            
            # add this dataframe to the list of currency_dataframe. there are separate dfs per currency.
            currency_dfs[currency_name] = currency_dfs[currency_name].append(new_data_as_dict, ignore_index=True)
                
        # wait s seconds until the next request
        time.sleep(s)
    return currency_dfs

# this function is called for each cryptocurrency and everytime the gate.io API returns price data
# the function extracts price information from a single API response and adds it to a dataframe 
# example: the API response contains data for 270 cryptocurrency price pairs -&gt; the function is called 270 time per API response
def append_data_to_df(price_before, data, ts):
    volume = data.base_volume
    price = pd.to_numeric(data.last)
    price_delta = price - price_before
    
    if price &gt; 0:
        price_delta_p = price_delta / price 
    else:
        price_delta_p = 0
    
    new_record = {
                  'Symbol': data.currency_pair, 
                  'Timestamp': ts, 
                  'Volume': volume, 
                  'Price': price,
                  'Price_Delta': price_delta,
                  'Price_Delta_Percent': price_delta_p
                 }
    return new_record</pre></div>



<h3 class="wp-block-heading" id="h-step-3-start-calling-the-gate-io-market-api">Step #3: Start Calling the Gate.io Market API</h3>



<p>Once we have defined the functions to request and handle the price data, we can start calling the API. In the code below, we use a request interval of 10 seconds. We stop calling the API for test purposes stop after four runs. Afterward, we print the list of DataFrames to inspect the collected data.</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;}">s = 10 # API request interval in seconds
currency_pair = '' # currency pair (optional)
runs = 4 # number of data points to fetch

df_list = request_data(runs, currency_pair, s)

df_list # list that contains one dataframe per currency</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;}">Output exceeds the size limit. Open the full output data in a text editor
{'MKR3S_USDT':        Symbol                  Timestamp             Volume    Price  \
 0  MKR3S_USDT 2021-05-15 15:36:59.449017  240761.4473870418  0.03816   
 1  MKR3S_USDT 2021-05-15 15:37:13.762682  240830.5653870418  0.03820   
 2  MKR3S_USDT 2021-05-15 15:37:27.148195  240830.5653870418  0.03820   
 3  MKR3S_USDT 2021-05-15 15:37:40.406192  240830.5653870418  0.03820   
 
    Price_Delta  Price_Delta_Percent  
 0      0.03816                  1.0  
 1      0.03820                  1.0  
 2      0.00000                  0.0  
 3      0.00000                  0.0  ,
 'BANK_USDT':       Symbol                  Timestamp           Volume   Price  Price_Delta  \
 0  BANK_USDT 2021-05-15 15:36:59.449017  162.21144309298  719.97       719.97   
 1  BANK_USDT 2021-05-15 15:37:13.762682  162.21144309298  720.92       720.92   
 2  BANK_USDT 2021-05-15 15:37:27.148195  162.22547024346  720.92         0.00   
 3  BANK_USDT 2021-05-15 15:37:40.406192  162.22547024346  720.92         0.00   
 
    Price_Delta_Percent  
 0                  1.0  
 1                  1.0  
 2                  0.0  
 3                  0.0  ,
 'COOK_USDT':       Symbol                  Timestamp           Volume    Price  \
 0  COOK_USDT 2021-05-15 15:36:59.449017  5336969.0918761  0.05500   
 1  COOK_USDT 2021-05-15 15:37:13.762682  5338396.2698761  0.05517   
...
    Price_Delta_Percent  
 0                  1.0  
 1                  1.0  
 2                  0.0  
 3                  0.0  }</pre></div>



<p>As shown above, we have created a list of DataFrames. It contains one DataFrame with price points per cryptocurrency price pair. You can now use these historical price data to conduct analytics or visualize price movements in real time. </p>



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



<p>This tutorial demonstrated how to query cryptocurrency price data via the Gate.io API. We have queried the API and stored historical crypto prices in a DataFrame. Now that you are familiar with the concepts of the Gate.io API, you can tackle exciting projects. For example, you could use the data to display price information on a website or create analytics applications. </p>



<p>In another relataly tutorial, we trained a crypto trading bot that acts upon automated trading signals. If you are interested in developing trading bots, consider my recent <a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" target="_blank" rel="noreferrer noopener">tutorials on Gate.io crypto trading bots</a>.</p>



<p>Of course, Gate.io is not the only crypto API in the market. So if you are looking for an API for crypto market data, you might also consider the Coinmarketcap API. I have recently covered it in <a href="https://www.relataly.com/category/apis/coinmarketcap-api/" target="_blank" rel="noreferrer noopener">a separate coinmarket API tutorial</a>.</p>



<p>I hope you liked this post. If you have questions, let me know in the comments.</p>



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



<p>If you are interested in stock-market Prediction, check out the following articles:</p>



<ul class="wp-block-list">
<li><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 Time Series and Recurrent Neural Networks in Python</a></li>



<li><a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" target="_blank" rel="noreferrer noopener">Building a Twitter Bot for Crypto Trading Signals using Python and Gate.io</a></li>
</ul>



<p></p>
<p>The post <a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/">Requesting Crypto Price Data from the Gate.io REST API in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3982</post-id>	</item>
		<item>
		<title>Requesting Crypto Prices from the Coinmarketcap API using Python</title>
		<link>https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/</link>
					<comments>https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Sun, 18 Apr 2021 21:11:29 +0000</pubDate>
				<category><![CDATA[Coinmarketcap API]]></category>
		<category><![CDATA[REST APIs]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[Stock Market Forecasting]]></category>
		<category><![CDATA[API Tutorials]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[Cryptocurrencies]]></category>
		<category><![CDATA[Peewee]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=3474</guid>

					<description><![CDATA[<p>You can do various things with cryptocurrency price data, such as creating forecasting models, illustrating historical prices, or performing chart analysis. But first, you need to get hold of the data. Nowadays, several APIs provide access to cryptocurrency price data. One of the most important and trusted sources is Coinmarketcap.com. The website offers multiple API ... <a title="Requesting Crypto Prices from the Coinmarketcap API using Python" class="read-more" href="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/" aria-label="Read more about Requesting Crypto Prices from the Coinmarketcap API using Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/">Requesting Crypto Prices from the Coinmarketcap API using 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>You can do various things with cryptocurrency price data, such as creating forecasting models, illustrating historical prices, or performing chart analysis. But first, you need to get hold of the data. Nowadays, several APIs provide access to cryptocurrency price data. One of the most important and trusted sources is Coinmarketcap.com. The website offers multiple API endpoints that provide access to historical price data for various cryptocurrencies like Bitcoin, Ethereum, etc. In addition, Coinmarketap offers meta information about coins and crypto exchanges, including listing and halving dates, circulating supply, or the current market cap. This tutorial gives an overview of the coinmarketcap API and shows how to use the API with Python. We will request historical price data and store them in a local SQLite database using the Pewee SQL framework.</p>



<p>The rest of this article is a Python hands-on tutorial: First, we lay the groundwork for working with the Coinmarketcap API by signing up for a free API key. Subsequently, we store this in a YAML file and use it to query bitcoin quotes from the Coinmarketcap API endpoint. Our goal is to store the data with Peewee in an SQLite DB. We will first define a schema to store the data. Finally, we will learn how to query the obtained rates from our local database and use them later, for example, to train a price prediction model.</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>
</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"><img decoding="async" width="1024" height="794" data-attachment-id="7921" data-permalink="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/image-30/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/image-30.png" data-orig-size="1385,1074" 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-30" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/image-30.png" src="https://www.relataly.com/wp-content/uploads/2022/04/image-30-1024x794.png" alt="Coinmarketcap offers a REST API through which we can access Crypto Price data." class="wp-image-7921" srcset="https://www.relataly.com/wp-content/uploads/2022/04/image-30.png 1024w, https://www.relataly.com/wp-content/uploads/2022/04/image-30.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/image-30.png 768w, https://www.relataly.com/wp-content/uploads/2022/04/image-30.png 1385w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Coinmarketcap offers a REST API through which we can access Crypto Price data.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">The Coinmarketcap API </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>CoinMarketCap is one of the world&#8217;s most referenced crypto asset price tracking websites. The website provides high-quality and accurate information to private and business users so they can draw their own informed conclusions. In April 2020, CoinMarketCap was acquired by Binance &#8211; the largest cryptocurrency exchange in the world. </p>



<p>Generally, all relevant coins are listed on Coinmarketcap &#8211; however, some are scam coins and coins whose further development was abandoned long ago. The CoinMarketCap API is a set of powerful RESTful JSON endpoints. According to the website, these APIs are designed to meet the mission-critical needs of application developers, data scientists, and enterprise platforms.</p>



<p>Let&#8217;s look at some of the available REST endpoints. </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"><img decoding="async" width="1024" height="393" data-attachment-id="11465" data-permalink="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/api-documentation-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png" data-orig-size="3720,1429" 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="api-documentation-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png" src="https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min-1024x393.png" alt="Coinmarketcap API documentation provides a comprehensive overview of the available API functions.  " class="wp-image-11465" srcset="https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png 1024w, https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png 300w, https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png 768w, https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png 1536w, https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png 2048w, https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png 2475w, https://www.relataly.com/wp-content/uploads/2022/12/api-documentation-min.png 3712.5w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Coinmarketcap API documentation provides a comprehensive overview of the available API functions.  </figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Endpoints</h2>



<p>Coinmarketcap offers several API endpoints for various crypto-related data, including prices, exchanges, and other information. </p>



<p>Below is a selection of API endpoints:</p>



<figure class="wp-block-table"><table><thead><tr><th>Endpoint </th><th>When to Use?</th></tr></thead><tbody><tr><td><a href="https://coinmarketcap.com/api/documentation/v1/#tag/cryptocurrency">/cryptocurrency/*</a></td><td>To retrieve price and volume data (aggregated over all exchanges) or cryptocurrency-related price data.</td></tr><tr><td><a href="https://coinmarketcap.com/api/documentation/v1/#tag/exchange">/exchange/*</a></td><td>To return exchange-specific data such as ordered exchange lists and market pair data.</td></tr><tr><td><a href="https://coinmarketcap.com/api/documentation/v1/#tag/global-metrics">/global-metrics/*</a></td><td>To return, obtain aggregate statistics such as global market cap and BTC dominance.</td></tr><tr><td><a href="https://coinmarketcap.com/api/documentation/v1/#tag/blockchain">/blockchain/*</a></td><td>For obtaining blockchain analytics data, e.g., transaction volume, etc.</td></tr><tr><td><a href="https://coinmarketcap.com/api/documentation/v1/#tag/key">/key/*</a></td><td>For managing and monitoring API key usage.</td></tr></tbody></table><figcaption class="wp-element-caption">Some of the API endpoints available via coinmarketcap</figcaption></figure>



<p>A big advantage of the Coinmarketcap API is that the data goes way back. For example, the historical price data for Bitcoin ranges back to 2013.</p>



<h3 class="wp-block-heading">Acquiring an API Key from the Developer Portal</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>All requests to the coinmarketcap API require authentication with an API key. Authentication can be achieved in two ways:</p>



<ul class="wp-block-list">
<li>Send the API key in the custom header of the HTTP request with the attribute &#8216;X-CMC_PRO_API_KEY&#8217; (Prefered).</li>



<li>Provide the key in the URL path. </li>
</ul>



<p>Before requesting data from the coinmarketcap API, you must acquire your API key by registering on the coinmarketcap <a href="https://coinmarketcap.com/api/" target="_blank" rel="noreferrer noopener">API developer portal</a>. You will choose from one of several pricing plans during the registration process. </p>



<p>The Free basic plan provides access to most data and is sufficient for this tutorial. However, it has severe limitations, such as a limited number of requests you can make daily and monthly. After the registration, you can log in to your account and display the API key in the &#8220;Overview&#8221; section.</p>



<p>Each call to the Coinmarketcap API consumes API credits. The number of calls and data we can retrieve via API is limited to 100 credits for the free plan. You can see how many of your daily and monthly credits are still available on the overview page.</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="3527" data-permalink="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/image-32-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/04/image-32.png" data-orig-size="1721,939" 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-32" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/04/image-32.png" src="https://www.relataly.com/wp-content/uploads/2021/04/image-32-1024x559.png" alt="coinmarketcap api pricing plans, python rest api tutorial" class="wp-image-3527" width="363" height="198" srcset="https://www.relataly.com/wp-content/uploads/2021/04/image-32.png 1024w, https://www.relataly.com/wp-content/uploads/2021/04/image-32.png 300w, https://www.relataly.com/wp-content/uploads/2021/04/image-32.png 768w, https://www.relataly.com/wp-content/uploads/2021/04/image-32.png 1536w, https://www.relataly.com/wp-content/uploads/2021/04/image-32.png 1721w" sizes="(max-width: 363px) 100vw, 363px" /><figcaption class="wp-element-caption">Different pricing plans of the Coinmarketcap API</figcaption></figure>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="431" data-attachment-id="3487" data-permalink="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/image-30-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/04/image-30.png" data-orig-size="1676,706" 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-30" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/04/image-30.png" src="https://www.relataly.com/wp-content/uploads/2021/04/image-30-1024x431.png" alt="coinmarketcap api key" class="wp-image-3487" srcset="https://www.relataly.com/wp-content/uploads/2021/04/image-30.png 1024w, https://www.relataly.com/wp-content/uploads/2021/04/image-30.png 300w, https://www.relataly.com/wp-content/uploads/2021/04/image-30.png 768w, https://www.relataly.com/wp-content/uploads/2021/04/image-30.png 1536w, https://www.relataly.com/wp-content/uploads/2021/04/image-30.png 1676w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Overview page of the coinmarketcap API</figcaption></figure>
</div>
</div>



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



<h3 class="wp-block-heading">Storing the API Key</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>It would be best never to store an API key directly in the code for security reasons. A better practice is to import and access the API key from a separate YAML file. Create the file with the name &#8220;api_config_coinmarketcap.yml&#8221; and insert your API key into this file as follow: </p>



<p>api_<em>key: &#8220;your coinmarketcap api key&#8221;</em></p>
</div>



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



<p></p>



<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:100%">
<h2 class="wp-block-heading">Obtaining Bitcoin Prices via the Coinmarketcap API</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 this tutorial, we demonstrate how to use Python to send periodic requests to the Coinmarketcap API to obtain cryptocurrency prices for the top-ranked digital asset by market capitalization. Since each request to the Coinmarketcap API consumes credits, we utilize a local SQLite database to store the price data. This allows us to retrieve the data without the need for additional API requests and preserves credits for future use.</p>



<p>To efficiently manage the SQLite database, we employ the PeeWee framework, which offers a robust and user-friendly interface for interacting with SQL databases in Python. This approach enables users to easily create, modify, and query data within the SQLite database.</p>



<p>Overall, this tutorial provides a valuable resource for anyone looking to automate the collection and storage of cryptocurrency price data using the Coinmarketcap API and SQLite database with the Pewee framework.</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"><img decoding="async" width="512" height="512" data-attachment-id="12618" data-permalink="https://www.relataly.com/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min/" data-orig-file="https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min.png" data-orig-size="1024,1024" 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="bitcoin and other cryptocurrencies relataly midjourney python tutorial coinmarketcap-min" data-image-description="&lt;p&gt;bitcoin and other cryptocurrencies relataly midjourney python tutorial coinmarketcap-min&lt;/p&gt;
" data-image-caption="&lt;p&gt;bitcoin and other cryptocurrencies relataly midjourney python tutorial coinmarketcap-min&lt;/p&gt;
" data-large-file="https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min.png" src="https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min-512x512.png" alt="bitcoin and other cryptocurrencies relataly midjourney python tutorial coinmarketcap " class="wp-image-12618" srcset="https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min.png 512w, https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min.png 300w, https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min.png 140w, https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min.png 768w, https://www.relataly.com/wp-content/uploads/2023/03/bitcoin-and-other-cryptocurrencies-relataly-midjourney-python-tutorial-coinmarketcap-min.png 1024w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">In this tutorial, we demonstrate how to use Python to send periodic requests to the Coinmarketcap API to obtain cryptocurrency prices for the top-ranked digital asset by market capitalization. Image created with <a href="http://www.midjourney.com" target="_blank" rel="noreferrer noopener">Midjourney</a>.</figcaption></figure>
</div>
</div>
</div>
</div>



<p></p>



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



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_591d07-56"><a class="kb-button kt-button button kb-btn_80078d-b9 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/125%20Pulling%20Historic%20Crypto%20Data%20via%20the%20Coinmarketcap%20API.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_4632f0-7a 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">Prerequisites</h3>



<p>Before beginning the coding part, please ensure 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 a Python environment available yet, you can follow&nbsp;<a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">the steps in this article</a>&nbsp;to set up the <a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda</a> Python environment.</p>



<p>Also, make sure you install the 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><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>



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



<p>In addition, we will use&nbsp;<em><a href="https://pypi.org/project/mplleaflet/" target="_blank" rel="noreferrer noopener">Peewee</a></em>, a lightweight Object-Relational-Mapper (ORM) framework that lets us interact with SQLite in an object-oriented and more convenient way. </p>



<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>



<h3 class="wp-block-heading" id="h-step-1-create-a-relational-model-in-sqlite">Step #1 Create a Relational Model in SQLite</h3>



<p>We begin by defining a relational data model in SQlite using Pewee. We will then use this model to persist the crypto price data from the API and make them available for later reuse. Our model will contain two tables:</p>



<ul class="wp-block-list">
<li>Run: A table where we will store an ID and a timestamp makes identifying past runs easier. We start querying data from the API, we will add a new runid to this table.</li>



<li>The second table is called price and contains the price quotes for a predetermined interval. We will store the price quotes in this table and reference the runid via a foreign key. </li>
</ul>



<p>Running the code below creates empty tables.</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;}">from peewee import *
from datetime import date, timedelta, datetime
import numpy as np 
import pandas as pd
import seaborn as sns
import time
import json
import yaml
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
from pandas.plotting import register_matplotlib_converters

import matplotlib.dates as mdates
import matplotlib.pyplot as plt

# persist information
db = SqliteDatabase('assets.db')

class BaseModel(Model):
    class Meta:
        database = db

class Run(BaseModel): # This model uses the &quot;assets.db&quot; database.
    timestamp = DateTimeField(unique=True)
    symbol = CharField()
    id = AutoField()

class Price(BaseModel): # This model uses the &quot;assets.db&quot; database.
    datetime = DateTimeField(unique=True)
    volume_24 = FloatField()
    price = FloatField()
    runid = ForeignKeyField(Run, backref='prices')
         
# By default, Peewee includes an IF NOT EXISTS clause when creating tables. 
def create_tables():
    with db:
        db.create_tables([Price])
        db.create_tables([Run])

def drop_tables():
    with db:
        db.drop_tables([Price])
        db.drop_tables([Run])
        
create_tables()

#drop_tables()    </pre></div>



<p>If you want to drop the tables again, you can call our custom drop_tables function.</p>



<h3 class="wp-block-heading" id="h-step-2-streaming-price-quotes">Step #2 Streaming Price Quotes</h3>



<p>Now that we have created the relational data model, we can define a request to the Coinmarketcap API and initiate the stream of price data. For this purpose, we will call the coinmarketcap REST endpoint &#8220;<strong>cryptocurrency/listings/latest</strong>.&#8221; This endpoint returns a JSON response that contains the latest price data for a specific number of cryptocurrencies based on their market capitalization rank. The response contains the following information for each cryptocurrency included:</p>



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



<li>The timestamp</li>



<li>The trading volume</li>



<li>The cost of the request in credits</li>
</ul>



<p>Before querying the API, we need to define basic API parameters:</p>



<ul class="wp-block-list">
<li>Conversion_Currency: The currency in which the API will return the prices.</li>



<li>Start: The position in the market cap ranking from which the API will include cryptocurrencies in the result.</li>



<li>Limit: The number of cryptocurrencies for which the API will return prices based on the start position in the current market cap ranking.</li>
</ul>



<p>We will select USD as &#8220;conversion_currency,&#8221; set the limit, and start to &#8220;one.&#8221; As a result, the API will return only the price of Bitcoin. We use a query interval of 10 seconds. You can change the interval, but be aware that you will deplete your free credits quickly if you request data by the second. We will therefore limit the requests to 200. You can increase the timeframe to retrieve price quotes for more extended periods. </p>



<p>We will store and load our API key from a YAML file. Be sure to replace the api_key_path in the code below with the path where you placed the api_config_coinmarketcap.yml file. Once you have made this adjustment, you can start the API requests by running the code below.</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;}">symbol='BTCUSD'
query_interval = 10 # in seconds
query_number = 100 # the number of queries after which the API stops

# load the API key from our local file
with open(r'API Keys/api_config_coinmarketcap.yml') as file:
    apikey = yaml.load(file, Loader=yaml.FullLoader)['api_key']

# Define some essential API parameters
# Coinmarketcap API for latest market ticker quotes and averages for cryptocurrencies and exchanges.
# https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
  'start':'1',
  'limit':'1',
  'convert':'USD'
}
headers = {
  'Accepts': 'application/json',
  'X-CMC_PRO_API_KEY': apikey,
}

session = Session()
session.headers.update(headers)

# create a new run and save it to our local SQLite DB
run_timestamp = datetime.now()
run = Run(symbol=symbol, timestamp = run_timestamp)
run.save()
current_run_id = run.id 
print(f'run_id: {current_run_id} - timestamp: {run_timestamp} - interval: {query_interval} - number of queries: {query_number}')

# query the coinmarketcap API every x seconds
for s in range(0, query_number):
    try:
        response = session.get(url, params=parameters)
        data = json.loads(response.text)
        #print(data)
        
        # response - quote
        data_quote = data['data'][0]['quote']['USD']
        price = np.round(data_quote['price'], 1) # the price
        volume_24 = np.round(data_quote['volume_24h'], 1) # the volume in the last 24 hours
        
        # response - status
        data_status = data['status']
        api_timestamp = data_status['timestamp'] # the timestamp of the pricepoint
        api_credits = data_status['credit_count'] # the number of credits spent on the last request
        
        # create a new pricepoint and save it to the SQLite db
        new_pricepoint = Price(datetime=api_timestamp, price=price, volume_24=volume_24, runid=current_run_id)
        id = new_pricepoint.save()

        # display what we have just saved
        print(f'request number: {s} - added {price} at {api_timestamp} - 24 hour volume: {volume_24} - credits used: {api_credits}')      

    except (ConnectionError, Timeout, TooManyRedirects) as e:
        print(e)
    time.sleep(query_interval)
print('finished')</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;}">run_id: 2 - timestamp: 2021-05-03 22:03:01.172363 - interval: 5 - number of queries: 200
request number: 0 - added 57487.7 at 2021-05-03T20:03:02.587Z - 24 hour volume: 48962167377.0 - credits used: 1
request number: 1 - added 57487.7 at 2021-05-03T20:03:08.059Z - 24 hour volume: 48962167377.0 - credits used: 1
request number: 2 - added 57487.7 at 2021-05-03T20:03:13.256Z - 24 hour volume: 48962167377.0 - credits used: 1
request number: 3 - added 57453.4 at 2021-05-03T20:03:18.470Z - 24 hour volume: 48948337250.5 - credits used: 1</pre></div>



<h3 class="wp-block-heading" id="h-step-3-querying-the-data-from-our-sql-table">Step #3 Querying the Data from Our SQL Table</h3>



<p>We now have the price data persisted in our local SQLite DB. From there, we can query the data using the peewee &#8220;select&#8221; SQL command. For example, we will query the run table and retrieve the number of requests made to the coinmarketcap 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;}">query = Run.select().where(Run.id==current_run_id)
run_overview = pd.DataFrame(list(query.dicts()))
run_overview</pre></div>



<p>Next, select the price quotes for this specific run-id and display them in a line plot. </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;}">query = Price.select().where(Price.runid==current_run_id)
df_prices = pd.DataFrame(list(query.dicts()))
print(df_prices)

register_matplotlib_converters()
fig, ax = plt.subplots(figsize=(10, 8))
plt.title('BTC prices from the coinmarketcap API', fontsize=14)
datetimes = pd.to_datetime(df_prices['datetime'])

sns.lineplot(data=df_prices, x=datetimes, y=&quot;price&quot;)
#ax.set_xlim([df_prices['datetime'].min(),df_prices['datetime'].max()])
#ax.xaxis.set_major_locator(mdates.MinuteLocator())
plt.xticks(rotation=75)</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="625" height="532" data-attachment-id="3509" data-permalink="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/image-31-4/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/04/image-31.png" data-orig-size="625,532" 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-31" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/04/image-31.png" src="https://www.relataly.com/wp-content/uploads/2021/04/image-31.png" alt="price quotes obtained from the coinmarketcap api " class="wp-image-3509" srcset="https://www.relataly.com/wp-content/uploads/2021/04/image-31.png 625w, https://www.relataly.com/wp-content/uploads/2021/04/image-31.png 300w" sizes="(max-width: 625px) 100vw, 625px" /></figure>



<p>And voila, the line plot shows the last data received from the API. We now have stored this data in our SQLite database. </p>



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



<p>This article gave a quick overview of the Coinmarketcap API &#8211; one of the most referenced APIs in the crypto space. You have learned to request historical price data from a Coinmarketcap API endpoint with Python. We wrote a short Python script that queries one of several REST endpoints (cryptocurrency/listings/latest) in regular intervals. To ensure that we can later reuse the requested data, we stored the response from the API in an SQLite database using the Pewee framework. </p>



<p>I am always happy to receive feedback from my readers. So if the tutorial helped you, or if you have any comments, please write them in the comments. </p>



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



<div style="display: inline-block;">
  <iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=3030181162&amp;asins=3030181162&amp;linkId=669e46025028259138fbb5ccec12dfbe&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1999579577&amp;asins=1999579577&amp;linkId=91d862698bf9010ff4c09539e4c49bf4&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1839217715&amp;asins=1839217715&amp;linkId=356ba074068849ff54393f527190825d&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1492032646&amp;asins=1492032646&amp;linkId=2214804dd039e7103577abd08722abac&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
</div>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>



<p>If you are not sure yet, if the coinmarketcap API is for you, consider these other ways of obtaining cryptocurrency price data:</p>



<ul class="wp-block-list">
<li><a href="https://www.relataly.com/category/apis/crypto-exchange-apis/coinbase-api/" target="_blank" rel="noreferrer noopener">Working with the Coinbase API</a></li>



<li><a href="https://www.relataly.com/category/apis/yahoo-finance-api/" target="_blank" rel="noreferrer noopener">Using the Yahoo Finance API to obtain Cryptocurrency Price Data</a></li>



<li><a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" target="_blank" rel="noreferrer noopener">Streaming Crypto Prices via the Gate.io API</a></li>
</ul>



<p>For more Python tutorials on stock-market prediction, check out the following articles:</p>



<ul class="wp-block-list">
<li><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 Time Series and Recurrent Neural Networks in Python</a></li>



<li><a href="https://www.relataly.com/time-series-forecasting-multi-step-regression-using-neural-networks-with-multiple-outputs-in-python/5800/" target="_blank" rel="noreferrer noopener">Stock-Market prediction using Neural Networks for Multi-Output Regression in Python</a></li>



<li><a href="https://www.relataly.com/stock-market-prediction-using-a-recurrent-neural-network/122/" target="_blank" rel="noreferrer noopener">Stock Market Prediction using Univariate Time Series Models based on Recurrent Neural Networks with Python</a></li>



<li><a href="https://www.relataly.com/time-series-forecasting-changing-prediction-horizon/169/" target="_blank" rel="noreferrer noopener">Stock Market Prediction – Adjusting Time Series Prediction Intervals in Python</a></li>



<li><a href="https://www.relataly.com/feature-engineering-for-multivariate-time-series-models-with-python/1813/" target="_blank" rel="noreferrer noopener">Feature Engineering for Multivariate Time Series Prediction with Python</a></li>



<li><a href="https://www.relataly.com/building-a-twitter-bot-for-trading-signals-using-python/3974/" target="_blank" rel="noreferrer noopener">Building a Twitter Bot for Crypto Trading Signals using Python and Gate.io</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/">Requesting Crypto Prices from the Coinmarketcap API using Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/requesting-crypto-price-data-from-the-coinmarketcap-api-using-python/3474/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3474</post-id>	</item>
		<item>
		<title>Color-Coded Cryptocurrency Price Charts in Python</title>
		<link>https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/</link>
					<comments>https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/#respond</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Tue, 19 Jan 2021 21:03:16 +0000</pubDate>
				<category><![CDATA[Coinbase API]]></category>
		<category><![CDATA[Correlation]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Sources]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Seaborn]]></category>
		<category><![CDATA[Stock Market Forecasting]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[Chart Analysis]]></category>
		<category><![CDATA[Cryptocurrencies]]></category>
		<category><![CDATA[Financial Analysis]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=2820</guid>

					<description><![CDATA[<p>Are you intrigued by the fascinating world of cryptocurrency and looking to visually decipher its price trends? Welcome aboard! In this comprehensive tutorial, we will explore creating color-coded line charts using Python and Matplotlib, a powerful tool for effective analysis of changes along a third dimension. The past few years have witnessed a meteoric rise ... <a title="Color-Coded Cryptocurrency Price Charts in Python" class="read-more" href="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/" aria-label="Read more about Color-Coded Cryptocurrency Price Charts in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/">Color-Coded Cryptocurrency Price Charts 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><br>Are you intrigued by the fascinating world of cryptocurrency and looking to visually decipher its price trends? Welcome aboard! In this comprehensive tutorial, we will explore creating color-coded line charts using Python and Matplotlib, a powerful tool for effective analysis of changes along a third dimension.</p>



<p>The past few years have witnessed a meteoric rise in the prices of cryptocurrencies, underscoring the need for accurate analysis and visualization of their price trends. An outstanding illustration of this is the color-coded Bitcoin stock-to-flow chart, a popular choice in the crypto space that uses color differentiation to denote time until the next Bitcoin halving event.</p>



<p>Drawing inspiration from this, our tutorial will guide you to create a similar dynamic color-coded line chart, tracing the price trends of two leading cryptocurrencies &#8211; Bitcoin and Ethereum. This visual aid will provide a deeper insight into their price trajectories over time, enabling you to make informed investment decisions.</p>



<p>As we dive in, we&#8217;ll break down the process into digestible chunks, making it easier for beginners to follow along. By the end of this tutorial, you&#8217;ll not only have a profound understanding of how to create and interpret such color-coded charts but also gain valuable insights into the world of cryptocurrency price trends.</p>



<p class="has-accent-color has-blush-light-purple-gradient-background has-text-color has-background"><strong>Disclaimer</strong>: This article does not constitute financial advice. Stock markets can be very volatile and are generally difficult to predict. Predictive models and other forms of analytics applied in this article only illustrate machine learning use cases.</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-what-are-color-coded-price-charts">What are Color-coded Price Charts?</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>Color coding is beneficial for visualizing trading signals and statistical indicators in technical chart analysis. The idea of color-coding in chart analysis is to create visually comprehensible charts that let the user quickly interpret how price develops under certain conditions. A simple example is a candlestick chart, which uses color to signal whether the price moves up (green) or down (red). Candlestick charts visualize more as regular line charts, providing additional information on the opening and closing prices. </p>



<p>We can use color codings in line plots to visualize conditions of various types. We can derive them from the price itself and, for example, illustrate the price development independence of oscillation indicators or moving averages. Or they can be independent of the price and represent some other conditions, such as, for example, the spread of COVID-19 cases worldwide. These are just a few examples, and there are no limits to your creativity in choosing the conditions. </p>



<p>Also: <a href="https://www.relataly.com/streaming-crypto-prices-via-the-gate-io-api-with-python/3982/" target="_blank" rel="noreferrer noopener">Requesting Crypto Price Data from the Gate.io REST API in Python</a></p>



<h2 class="wp-block-heading">Use Cases for Color-coded Price Charts</h2>



<p>There are various use cases for color-coded line plots in the crypto space. For example, crypto enthusiasts employ them to visualize relationships between the price of bitcoin and statistical indicators, including momentum indicators such as the RSI. Color-coded line plots have also been used to show dependencies between price and specific events that develop parallel to the bitcoin price. For example, we can use color-coding to highlight the lag between the price and the bitcoin halving every four years.</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-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" data-attachment-id="8060" data-permalink="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/image-3-3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/05/image-3.png" data-orig-size="1410,819" 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-3" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/05/image-3.png" src="https://www.relataly.com/wp-content/uploads/2022/05/image-3-1024x595.png" alt="Example of a color-coded line plot that shows the Bitcoin stock to flow model. In this article, we will create a similar chart using Python." class="wp-image-8060" width="416" height="241" srcset="https://www.relataly.com/wp-content/uploads/2022/05/image-3.png 1024w, https://www.relataly.com/wp-content/uploads/2022/05/image-3.png 300w, https://www.relataly.com/wp-content/uploads/2022/05/image-3.png 768w, https://www.relataly.com/wp-content/uploads/2022/05/image-3.png 1410w" sizes="(max-width: 416px) 100vw, 416px" /><figcaption class="wp-element-caption">The Stock to Flow Model is an example of a Color-coded price chart (Source: <a href="https://www.lookintobitcoin.com/charts/stock-to-flow-model/" target="_blank" rel="noreferrer noopener">lookintobitcoin.com</a>)</figcaption></figure>
</div></div>
</div>



<h2 class="wp-block-heading" id="h-implementing-color-coded-price-charts-in-python">Implementing Color-coded Price Charts 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>Are you ready to elevate your data visualization skills and create visually striking price charts with Python? In this tutorial, we&#8217;ll be walking you through the creation of two dynamic line charts that use color to reveal intriguing trends and patterns. The first chart will feature a color overlay on the price line to showcase how Bitcoin prices fluctuate based on RSI. The second chart will unveil the shifting correlation between Bitcoin and Ethereum over time. Buckle up, and let&#8217;s dive in!</p>



<p>We&#8217;ll start by using the Coinbase Pro API to download historical price data on BTC and ETH. We&#8217;ll then calculate two well-established indicators in financial analysis: the Relative Strength Index (RSI) and the Pearson Correlation between Bitcoin and Ethereum. Finally, we&#8217;ll use Matplotlib to create stunning color-coded line charts that highlight the changes in the indicators over extended periods.</p>



<p>Also: <a href="https://www.relataly.com/visualize-covid-19-data-on-a-geographic-heat-maps/291/" target="_blank" rel="noreferrer noopener">Geographic Heat Maps with GeoPandas: Visualizing COVID-19</a></p>



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



<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_2cdf46-d5"><a class="kb-button kt-button button kb-btn_1609d5-b1 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/071%20Color-Coded%20Cryptocurrency%20Price%20Charts.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_d58e18-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" 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 Python 3 environment and required packages. If you don&#8217;t have an environment, you can follow&nbsp;this tutorial&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><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></li>



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



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



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



<p>In addition, we will be using the <a href="https://github.com/David-Woroniuk/Historic_Crypto" target="_blank" rel="noreferrer noopener">Historic-Crypto Python Package</a>, which lets us easily interact with the <a href="https://pro.coinbase.com/" target="_blank" rel="noreferrer noopener">Coinbase Pro</a> API.</p>



<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>



<h3 class="wp-block-heading" id="h-step-1-load-the-price-data-via-the-coinbase-api">Step #1 Load the Price Data via the Coinbase API</h3>



<p>We begin by downloading the historical price data on Bitcoin (BTC-USD) and Ethereum (BTC-USD) from Coinbase Pro. Don&#8217;t worry; you don&#8217;t need to download the data manually. Instead, we will use the Historic_Crypto Python package to access the data via an API. </p>



<p>Accessing the data via the Coinbase Pro API requires us to specify several API parameters. We define a frequency of 21600 seconds so that we will obtain price points on a 6-hour basis. In addition, we define a from_date of &#8220;2017-01-01&#8221; and add &#8220;ETH-USD&#8221; and &#8220;BTC-USD&#8221; to a list of coins for which we want to obtain the historical price data. </p>



<p>We query the API separately for each of the two coins in our coin list. Depending on your internet connection, this can take several minutes. The response contains three different price values:</p>



<ul class="wp-block-list">
<li><strong>high</strong>: the daily price high</li>



<li><strong>low</strong>: the daily price low</li>



<li><strong>close</strong>: the daily closing price</li>
</ul>



<p>Later in this article, we will require all three variables to calculate the indicator values. We will therefore add the variables as columns to a new 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;}"># Tested with Python 3.8.8, Matplotlib 3.5, Seaborn 0.11.1, numpy 1.19.5

from Historic_Crypto import HistoricalData
import pandas as pd 
from scipy.stats import pearsonr
import matplotlib.pyplot as plt 
import matplotlib.colors as col 
import numpy as np 
import datetime

# the price frequency in seconds: 21600 = 6 hour price data, 86400 = daily price data
frequency = 21600

# The beginning of the period for which prices will be retrieved
from_date = '2017-01-01-00-00'
# The currency price pairs for which the data will be retrieved
coinlist = ['ETH-USD', 'BTC-USD']

# Query the data
for i in range(len(coinlist)):
    coinname = coinlist[i]
    pricedata = HistoricalData(coinname, frequency, from_date).retrieve_data()
    pricedf = pricedata[['close', 'low', 'high']]
    if i == 0:
        df = pd.DataFrame(pricedf.copy())
    else:
        df = pd.merge(left=df, right=pricedf, how='left', left_index=True, right_index=True)   
    df.rename(columns={&quot;close&quot;: &quot;close-&quot; + coinname}, inplace=True)
    df.rename(columns={&quot;low&quot;: &quot;low-&quot; + coinname}, inplace=True)
    df.rename(columns={&quot;high&quot;: &quot;high-&quot; + coinname}, inplace=True)
df.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;}">			time	close-ETH-USD	low-ETH-USD	high-ETH-USD	close-BTC-USD	low-BTC-USD	high-BTC-USD
2017-01-01 06:00:00	8.23			8.16		8.49			975.00			964.54		975.00
2017-01-01 12:00:00	8.33			8.20		8.44			994.42			974.01		994.97
2017-01-01 18:00:00	8.18			8.08		8.37			992.95			986.86		1000.00
2017-01-02 00:00:00	8.13			8.05		8.22			1003.64			990.52		1012.00
2017-01-02 06:00:00	8.10			8.09		8.20			1024.84			1002.92		102</pre></div>



<h3 class="wp-block-heading" id="h-step-2-visualizing-the-time-series">Step #2 Visualizing the Time Series</h3>



<p>At this point, we have created a dataframe that contains the price &#8220;close,&#8221; &#8220;low,&#8221; and &#8220;high&#8221; for BTC-USD and ETH-USD. Next, let&#8217;s take a quick look at what the data looks like:</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 a Price Chart on BTC and ETH
x = df.index
fig, ax1 = plt.subplots(figsize=(16, 8), sharex=False)

# Price Chart for BTC-USD Close
color = 'tab:blue'
y = df['close-BTC-USD']
ax1.set_xlabel('time (s)')
ax1.set_ylabel('BTC-Close in $', color=color, fontsize=18)
ax1.plot(x, y, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax1.text(0.02, 0.95, 'BTC-USD',  transform=ax1.transAxes, color=color, fontsize=16)

# Price Chart for ETH-USD Close
color = 'tab:red'
y = df['close-ETH-USD']
ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
ax2.set_ylabel('ETH-Close in $', color=color, fontsize=18)  # we already handled the x-label with ax1
ax2.plot(x, y, color=color)
ax2.tick_params(axis='y', labelcolor=color)
ax2.text(0.02, 0.9, 'ETH-USD',  transform=ax2.transAxes, color=color, fontsize=16)</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1021" height="480" data-attachment-id="11736" data-permalink="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/image-1-2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/12/image-1.png" data-orig-size="1021,480" 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-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/12/image-1.png" src="https://www.relataly.com/wp-content/uploads/2022/12/image-1.png" alt="Price charts of Bitcoin and Ethereum created in Python" class="wp-image-11736" srcset="https://www.relataly.com/wp-content/uploads/2022/12/image-1.png 1021w, https://www.relataly.com/wp-content/uploads/2022/12/image-1.png 300w, https://www.relataly.com/wp-content/uploads/2022/12/image-1.png 768w" sizes="(max-width: 1021px) 100vw, 1021px" /></figure>



<p>Next, we add two indicator values to our dataframe that we can later use to color the price chart. </p>



<h3 class="wp-block-heading" id="h-step-3-calculate-indicator-values">Step #3 Calculate Indicator Values</h3>



<p>The color overlay of the price chart is typically used to illustrate the relation between price and another variable, such as a statistical indicator. To demonstrate how this works, we will calculate two indicators and add them to our dataframe:</p>



<h4 class="wp-block-heading" id="h-3-1-the-relative-strength-index">3.1 The Relative Strength Index</h4>



<p>The Relative Strength Index (RSI) is a momentum indicator that signals the strength of a price trend. Its value range from 0 to 100%. A value above 70% signals that an asset is likely overbought. An overbought level is an area where the market is highly bullish and might decline. A value below 30% is typically a sign of an oversold condition. An oversold level is where the market is extremely bearish, and the price tends to reverse to the upper side.</p>



<h4 class="wp-block-heading" id="h-3-2-the-pearson-correlation-coefficient">3.2 The Pearson Correlation Coefficient</h4>



<p>Pearson Correlation Coefficient: This indicator measures the correlation between two sets of stochastic variables. Its values range from -1 to 1. A value of 1 would imply a perfect stochastic correlation. For example, if the price of BTC changes by X percentage in a given period, we can expect ETH to experience the exact price change. A value of -1 would imply a perfect inverse correlation. For example, if the price of BTC were to increase by Y percent, we would also expect the ETH price to decrease by Y percent. A value of 0 implies no correlation. To learn more about correlation, check out my article about <a href="https://www.relataly.com/category/data-science/pearson-correlation/" target="_blank" rel="noreferrer noopener">correlation in Python</a>.</p>



<p>We embed the logic for calculating the two indicators in a different method called &#8220;add_indicators.&#8221;</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;}">def add_indicators(df):
    # Calculate the 30 day Pearson Correlation 
    cor_period = 30 #this corresponds to a monthly correlation period
    columntobeadded = [0] * cor_period
    df = df.fillna(0) 
    for i in range(len(df)-cor_period):
        btc = df['close-BTC-USD'][i:i+cor_period]
        eth = df['close-ETH-USD'][i:i+cor_period]
        corr, _ = pearsonr(btc, eth)
        columntobeadded.append(corr)    
    # insert the colours into our original dataframe    
    df.insert(2, &quot;P_Correlation&quot;, columntobeadded, True)

    # Calculate the RSI
    # Moving Averages on high, lows, and std - different periods
    df['MA200_low'] = df['low-BTC-USD'].rolling(window=200).min()
    df['MA14_low'] = df['low-BTC-USD'].rolling(window=14).min()
    df['MA200_high'] = df['high-BTC-USD'].rolling(window=200).max()
    df['MA14_high'] = df['high-BTC-USD'].rolling(window=14).max()

    # Relative Strength Index (RSI)
    df['K-ratio'] = 100*((df['close-BTC-USD'] - df['MA14_low']) / (df['MA14_high'] - df['MA14_low']) )
    df['RSI'] = df['K-ratio'].rolling(window=3).mean() 

    # Replace nas 
    #nareplace = df.at[df.index.max(), 'close-BTC-USD']    
    df.fillna(0, inplace=True)    
    return df
    
dfcr = add_indicators(df)</pre></div>



<p>At this point, we have added the RSI and the Correlation Coefficient to our dataframe. Let&#8217;s quickly visualize the two indicators in a line chart. </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;}"># Visualize measures
fig, ax1 = plt.subplots(figsize=(22, 4), sharex=False)
plt.ylabel('ETH-BTC Price Correlation', color=color)  # we already handled the x-label with ax1
x = y = dfcr.index
ax1.plot(x, dfcr['P_Correlation'], color='black')
ax2 = ax1.twinx()
ax2.plot(x, dfcr['RSI'], color='blue')
plt.tick_params(axis='y', labelcolor=color)

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



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="193" data-attachment-id="2838" data-permalink="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/image-11-7/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2021/01/image-11.png" data-orig-size="1319,248" 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-11" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2021/01/image-11.png" src="https://www.relataly.com/wp-content/uploads/2021/01/image-11-1024x193.png" alt="RSI Cryptocurrency chart analysis created with Python" class="wp-image-2838" srcset="https://www.relataly.com/wp-content/uploads/2021/01/image-11.png 1024w, https://www.relataly.com/wp-content/uploads/2021/01/image-11.png 300w, https://www.relataly.com/wp-content/uploads/2021/01/image-11.png 768w, https://www.relataly.com/wp-content/uploads/2021/01/image-11.png 1319w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>You may have noticed that the indicators remain at 0 at the time series beginning. However, this is perfectly fine. Since both indicators are calculated retrospectively, no values are available initially. </p>



<h3 class="wp-block-heading" id="h-step-4-converting-indicator-values-to-color-codes">Step #4 Converting Indicator Values to Color Codes</h3>



<p>Before creating the price charts, we have to color code the indicator values. We normalize the values and then assign a color to each indicator value using a color scale. We attach the colors to our existing dataframe to quickly access them when creating the plots.</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;}"># function that converts a given set of indicator values to colors
def get_colors(ind, colormap):
    colorlist = []
    norm = col.Normalize(vmin=ind.min(), vmax=ind.max())
    for i in ind:
        colorlist.append(list(colormap(norm(i))))
    return colorlist

# convert the RSI                         
y = np.array(dfcr['RSI'])
colormap = plt.get_cmap('plasma')
dfcr['rsi_colors'] = get_colors(y, colormap)

# convert the Pearson Correlation
y = np.array(dfcr['P_Correlation'])
colormap = plt.get_cmap('plasma')
dfcr['cor_colors'] = get_colors(y, colormap)</pre></div>



<p>In our dataframe, two additional columns contain the color values for the two indicators. Now that we have all the data in our dataframe, the next step is creating the price charts.</p>



<h3 class="wp-block-heading" id="h-step-5-creating-color-coded-price-charts">Step #5 Creating Color-Coded Price Charts</h3>



<p>Next, we use the color values to create two different color-coded price charts.</p>



<h4 class="wp-block-heading" id="h-5-1-bitcoin-price-chart-colored-by-rsi">5.1 Bitcoin Price Chart Colored by RSI</h4>



<p>We color the chart with the strength of the correlation between Bitcoin and Ethereum. Light-colored fields signal phases of a strong correlation. Price points colored in dark blue indicate phases where the correlation between the price movements of the two cryptocurrencies was negative.</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 a Price Chart
pd.plotting.register_matplotlib_converters()
fig, ax1 = plt.subplots(figsize=(18, 10), sharex=False)
x = dfcr.index
y = dfcr['close-BTC-USD']
z = dfcr['rsi_colors']

# draw points
for i in range(len(dfcr)):
    ax1.plot(x[i], np.array(y[i]), 'o',  color=z[i], alpha = 0.5, markersize=5)
ax1.set_ylabel('BTC-Close in $')
ax1.tick_params(axis='y', labelcolor='black')
ax1.set_xlabel('Date')
ax1.text(0.02, 0.95, 'BTC-USD - Colored by RSI',  transform=ax1.transAxes, fontsize=16)

# plot the color bar
pos_neg_clipped = ax2.imshow(list(z), cmap='plasma', vmin=0, vmax=100, interpolation='none')
cb = plt.colorbar(pos_neg_clipped)</pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="682" data-attachment-id="9534" data-permalink="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/image-35/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/09/image.png" data-orig-size="1073,715" 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" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/09/image.png" src="https://www.relataly.com/wp-content/uploads/2022/09/image-1024x682.png" alt="color-coded bitcoin chart with halving dates; seaborn, python" class="wp-image-9534" srcset="https://www.relataly.com/wp-content/uploads/2022/09/image.png 1024w, https://www.relataly.com/wp-content/uploads/2022/09/image.png 300w, https://www.relataly.com/wp-content/uploads/2022/09/image.png 768w, https://www.relataly.com/wp-content/uploads/2022/09/image.png 1073w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>From the color overlay in the chart, we can tell that the RSI is low mainly (dark blue) when the Bitcoin price has seen a substantial decline and high (yellow) when the price has risen. </p>



<p></p>



<h4 class="wp-block-heading" id="h-5-2-bitcoin-price-chart-colored-by-btc-eth-correlation">5.2 Bitcoin Price Chart colored by BTC-ETH Correlation</h4>



<p>In this section, we will create another price chart for Bitcoin. This time we color code the price trend with the RSI. High RSI values are yellow, and low values are dark blue. Running the code below will create the color-coded bitcoin chart.</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 a price chart
pd.plotting.register_matplotlib_converters()
fig, ax1 = plt.subplots(figsize=(18, 10), sharex=False)
x = dfcr.index # datetime index
y = dfcr['close-BTC-USD'] # the price variable
z = dfcr['cor_colors'] # the color coded indicator values

# draw points
for i in range(len(dfcr)):
    ax1.plot(x[i], np.array(y[i]), 'o',  color=z[i], alpha = 0.5, markersize=5)
ax1.set_ylabel('BTC-Close in $')
ax1.tick_params(axis='y', labelcolor='black')
ax1.set_xlabel('Date')
ax1.text(0.02, 0.95, 'BTC-USD - Colored by 50-day ETH-BTC Correlation',  transform=ax1.transAxes, fontsize=16)

# plot the color bar
pos_neg_clipped = ax2.imshow(list(z), cmap='Spectral', vmin=-1, vmax=1, interpolation='none')
cb = plt.colorbar(pos_neg_clipped)</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="985" height="606" data-attachment-id="9537" data-permalink="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/image-2-5/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/09/image-2.png" data-orig-size="985,606" 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-2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/09/image-2.png" src="https://www.relataly.com/wp-content/uploads/2022/09/image-2.png" alt="line plot of bitcoin prices color coded by Bitcoin Ethereum correlation in Python" class="wp-image-9537" srcset="https://www.relataly.com/wp-content/uploads/2022/09/image-2.png 985w, https://www.relataly.com/wp-content/uploads/2022/09/image-2.png 300w, https://www.relataly.com/wp-content/uploads/2022/09/image-2.png 768w" sizes="(max-width: 985px) 100vw, 985px" /></figure>



<p>The chart shows that the correlation between Bitcoin and Ethereum (yellow color) was strong when the price of bitcoin rose. So when Bitcoin is in a bull market, Ethereum tends to follow a similar price logic. In contrast, the correlation was weak when the Bitcoin price declined (dark blue).</p>



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



<p>In this article, we demonstrated how to use Python and Seaborn to create a price chart that incorporates color as a third dimension. We used the Bitcoin price as an example and created two color-coded charts: one that highlights the RSI, and another that highlights the Pearson Correlation between Bitcoin and Ethereum.</p>



<p>By using color as an overlay, it is possible to highlight many interesting relationships in time-series data. A well-known example from the cryptocurrency world is the Bitcoin Rainbow Chart. This technique can be used to bring attention to various trends and patterns in the data.</p>



<p>I hope this article has helped to bring you closer to charts in Python. I am always interested to receive feedback from my audience. So, let me know if you liked this content, and if you have any questions, please post them in the comments.</p>



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



<div style="display: inline-block;">
  <iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=3030181162&amp;asins=3030181162&amp;linkId=669e46025028259138fbb5ccec12dfbe&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1999579577&amp;asins=1999579577&amp;linkId=91d862698bf9010ff4c09539e4c49bf4&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1839217715&amp;asins=1839217715&amp;linkId=356ba074068849ff54393f527190825d&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1492032646&amp;asins=1492032646&amp;linkId=2214804dd039e7103577abd08722abac&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
</div>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>



<p>And if you are interested in stock-market prediction, check out the following articles:</p>



<ul class="wp-block-list">
<li><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 Time Series and Recurrent Neural Networks in Python</a></li>



<li><a href="https://www.relataly.com/time-series-forecasting-multi-step-regression-using-neural-networks-with-multiple-outputs-in-python/5800/" target="_blank" rel="noreferrer noopener">Stock-Market prediction using Neural Networks for Multi-Output Regression in Python</a></li>



<li><a href="https://www.relataly.com/stock-market-prediction-using-a-recurrent-neural-network/122/" target="_blank" rel="noreferrer noopener">Stock Market Prediction using Univariate Time Series Models based on Recurrent Neural Networks with Python</a></li>
</ul>
<p>The post <a href="https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/">Color-Coded Cryptocurrency Price Charts in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/cryptocurrency-price-charts-with-color-overlay-python/2820/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2820</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>
	</channel>
</rss>
