avatarMario Rodriguez

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4496

Abstract

= data[[<span class="hljs-string">'Date'</span>, <span class="hljs-string">'Open'</span>, <span class="hljs-string">'High'</span>, <span class="hljs-string">'Low'</span>, <span class="hljs-string">'Close'</span>]].copy() ohlc[<span class="hljs-string">'Date'</span>] = ohlc[<span class="hljs-string">'Date'</span>].apply(mdates.date2num) candlestick_ohlc(ax, ohlc.values, width=<span class="hljs-number">0.6</span>, colorup=<span class="hljs-string">'green'</span>, colordown=<span class="hljs-string">'red'</span>)

<span class="hljs-comment"># plot moving averages</span> ax.plot(data[<span class="hljs-string">'Date'</span>], data[<span class="hljs-string">'MA20'</span>], label=<span class="hljs-string">'MA20'</span>) ax.plot(data[<span class="hljs-string">'Date'</span>], data[<span class="hljs-string">'MA50'</span>], label=<span class="hljs-string">'MA50'</span>)

<span class="hljs-comment"># add legend</span> ax.legend()

<span class="hljs-comment"># show plot</span> plt.show()</pre></div><p id="cd62">In this modified example, the <code>yfinance</code> library is used to download the stock prices data by passing in the stock symbol, start and end dates to the <code>download</code> function. In the example, IBEX 35 data from 2020 to the end of 2021 has been downloaded. The downloaded data is then reset the index as before. The <code>ohlc</code> DataFrame is created to extract the OHLC values and convert the date column to a numerical format that can be used with the <code>candlestick_ohlc</code> function. Finally, Moving Averate (MA) with windows of 20 and 50 are also computed and plotted.</p><figure id="46a8"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Mht0UzA-XwGgQt3kfjJPzw.png"><figcaption></figcaption></figure><h1 id="b4a3">Geographical Data Plotting</h1><p id="2273">Geographical data plotting is an essential task for many applications, such as climate studies, population analysis, and resource management. Matplotlib is a powerful Python library that provides various map projections and geographic coordinate systems to choose from, making it ideal for displaying data associated with a specific location. With Matplotlib, you can create choropleth maps, scatter plots, and other visualizations that represent data by shading or coloring different regions or areas. In this way, you can gain insights into spatial patterns and relationships that are not easily visible in tabular data. In the following sections, we will explore some examples of how Matplotlib can be used for geographical data plotting.</p><p id="7c4d">Below, an example of geographical data plotting using Matplotlib is showed. The code plots a Europe map with all countries colored in green appart from Spain, which is colored in blue. To do so, cartopy library is also used. Cartopy is a Python library that provides powerful tools for creating maps and working with geospatial data. It is built on top of the matplotlib library and integrates seamlessly with its data visualization capabilities. Cartopy supports a wide range of map projections and coordinate systems, allowing you to create maps that are tailored to your specific needs. In addition, Cartopy provides built-in support for accessing and working with data from popular geospatial data sources, such as Natural Earth and NASA.</p><div id="dca7"><pre><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt <span class="hljs-keyword">import</span> cartopy <span class="hljs-keyword">import</span> cartopy.io.shapereader <span class="hljs-keyword">as</span> shpreader <span class="hljs-keyword">import</span> cartopy.crs <span class="hljs-keyword">as</span> ccrs

ax = plt.axes(projection=ccrs.PlateCarree()) <span class="hljs-comment">#ax.add_feature(cartopy.feature.LAND)</span> ax.add_feature(cartopy.feature.OCEAN) <span class="hljs-comment">#ax.add_feature(cartopy.feature.COASTLINE)</span> <span class="hljs-comment">#ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)</span> <span class="hljs-comment">#ax.add_feature(cartopy.feature.LAKES, alpha=0.95)</span> <span class="hljs-comment">#ax.add_feature(cartopy.feature.RIVERS)</span> ax.set_extent([-<span class="hljs-number">150</span>, <span class="hljs-number">60</span>, -<span class="hljs-number">25</span>, <span class="hljs-number">60</span>])

shpfilename = shpreader.natural_earth(resolution=<span class="hljs-string">'110m'</span>, category

Options

=<span class="hljs-string">'cultural'</span>, name=<span class="hljs-string">'admin_0_countries'</span>) reader = shpreader.Reader(shpfilename) countries = reader.records()

<span class="hljs-keyword">for</span> country <span class="hljs-keyword">in</span> countries: <span class="hljs-keyword">if</span> country.attributes[<span class="hljs-string">'NAME_EN'</span>] == <span class="hljs-string">'Spain'</span>: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Spain"</span>) ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>), label=country.attributes[<span class="hljs-string">'NAME_EN'</span>]) <span class="hljs-keyword">else</span>: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Spain"</span>) ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>), label=country.attributes[<span class="hljs-string">'NAME_EN'</span>])

plt.show()</pre></div><p id="10ea">This code uses the Cartopy library to create a choropleth map of the Europ with countries colored based on a condition. First, the code imports the necessary libraries and defines a Plate Carree projection. Then, it sets the extent of the map to be displayed.</p><p id="2d33">The code reads the shapefile of the countries from the Natural Earth dataset and creates a Reader object. It then iterates through the countries and checks if the country name is Spain. If it is, the code adds the country’s geometry to the map with a blue color. Otherwise, it adds the country’s geometry with a green color.</p><p id="09b0">Finally, the code displays the map using the plt.show() function. The commented-out lines of code show how to add other features to the map, such as land, coastlines, and borders. By default, the map displays only the ocean feature.</p><figure id="3da4"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*NJtSgLTIIdEkG9UYYIhU-g.png"><figcaption></figcaption></figure><p id="363b">Course index:</p><div id="8d49" class="link-block"> <a href="https://mario-rodriguez.medium.com/python-course-76c3ed56eb24"> <div> <div> <h2>Python Course</h2> <div><h3>Learn the basics of Python</h3></div> <div><p>mario-rodriguez.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*R51-UHVJ6kUoylq4)"></div> </div> </div> </a> </div><p id="72cc">Have you spent your learning budget for this month, you can join Medium here:</p><div id="c0a1" class="link-block"> <a href="https://mario-rodriguez.medium.com/membership"> <div> <div> <h2>Join Medium with my referral link - Mario Rodriguez</h2> <div><h3>Read every story from Mario Rodriguez and thousands of other writers on Medium. Your membership fee directly supports…</h3></div> <div><p>mario-rodriguez.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*RUZGMqkOTUAc2L9H)"></div> </div> </div> </a> </div><h1 id="48c7">Level Up Coding</h1><p id="b93b">Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev">Newsletter</a></li></ul><p id="0dc0">🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><b>Join the Level Up talent collective and find an amazing job</b></a></p></article></body>

Matplotlib: Examples for Financial and Geographical Cases

Exploring the power of Matplotlib with some examples

Photo by AbsolutVision on Unsplash

The article shows two examples for financial and geographical applications. Matplotlib is commonly used for visualizing financial data, such as stock prices, exchange rates, and economic indicators, and provides a variety of chart types ideal for time series data, including line charts, bar charts, and scatter plots. The article provides an example of using Matplotlib to create a candlestick chart, which shows the opening, closing, high, and low prices of a security over a specific period of time, using the mpl_finance and yfinance libraries. The article also discusses how Matplotlib can be used for geographical data plotting, such as creating choropleth maps and scatter plots that represent data by shading or coloring different regions or areas. An example of creating a Europe map with all countries colored in green except for Spain, which is colored in blue, is provided using the Cartopy library. Cartopy is a powerful Python library that provides tools for creating maps and working with geospatial data.

Financial Data Plotting

Matplotlib is commonly used to plot financial data such as stock prices, exchange rates, and economic indicators. It provides a variety of chart types such as line charts, bar charts, and scatter plots, which are ideal for visualizing time series data.

For example, you can use Matplotlib to create candlestick charts, which show the opening, closing, high, and low prices of a security over a specific period of time. Additionally to matplotlib, mpl_finance and yfinance libraries are used for this example.

The mpl_finance library is used in this example to create a candlestick chart, which is a type of financial chart used to represent the opening, closing, high, and low prices of a security over a specific period of time.

The yfinance library is used in this example to download the stock prices data directly from Yahoo Finance. This library provides a simple and convenient way to access financial data from Yahoo

import matplotlib.pyplot as plt
from mpl_finance import candlestick_ohlc
import yfinance as yf
import matplotlib.dates as mdates
import pandas as pd

# set stock symbol and start and end dates
symbol = '^IBEX'
start_date = '2020-03-30'
end_date = '2022-03-30'

# download stock prices data from Yahoo Finance
data = yf.download(symbol, start=start_date, end=end_date)

# reset index and convert date column to datetime object
data = data.reset_index()

# create moving averages
data['MA20'] = data['Close'].rolling(window=20).mean()
data['MA50'] = data['Close'].rolling(window=50).mean()

# create figure and axis objects
fig, ax = plt.subplots()

# format x-axis as dates
ax.xaxis_date()

# set labels and title
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.set_title('Candlestick Chart of AAPL Stock Prices')

# create candlestick chart
ohlc = data[['Date', 'Open', 'High', 'Low', 'Close']].copy()
ohlc['Date'] = ohlc['Date'].apply(mdates.date2num)
candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red')

# plot moving averages
ax.plot(data['Date'], data['MA20'], label='MA20')
ax.plot(data['Date'], data['MA50'], label='MA50')

# add legend
ax.legend()

# show plot
plt.show()

In this modified example, the yfinance library is used to download the stock prices data by passing in the stock symbol, start and end dates to the download function. In the example, IBEX 35 data from 2020 to the end of 2021 has been downloaded. The downloaded data is then reset the index as before. The ohlc DataFrame is created to extract the OHLC values and convert the date column to a numerical format that can be used with the candlestick_ohlc function. Finally, Moving Averate (MA) with windows of 20 and 50 are also computed and plotted.

Geographical Data Plotting

Geographical data plotting is an essential task for many applications, such as climate studies, population analysis, and resource management. Matplotlib is a powerful Python library that provides various map projections and geographic coordinate systems to choose from, making it ideal for displaying data associated with a specific location. With Matplotlib, you can create choropleth maps, scatter plots, and other visualizations that represent data by shading or coloring different regions or areas. In this way, you can gain insights into spatial patterns and relationships that are not easily visible in tabular data. In the following sections, we will explore some examples of how Matplotlib can be used for geographical data plotting.

Below, an example of geographical data plotting using Matplotlib is showed. The code plots a Europe map with all countries colored in green appart from Spain, which is colored in blue. To do so, cartopy library is also used. Cartopy is a Python library that provides powerful tools for creating maps and working with geospatial data. It is built on top of the matplotlib library and integrates seamlessly with its data visualization capabilities. Cartopy supports a wide range of map projections and coordinate systems, allowing you to create maps that are tailored to your specific needs. In addition, Cartopy provides built-in support for accessing and working with data from popular geospatial data sources, such as Natural Earth and NASA.

import matplotlib.pyplot as plt
import cartopy
import cartopy.io.shapereader as shpreader
import cartopy.crs as ccrs

ax = plt.axes(projection=ccrs.PlateCarree())
#ax.add_feature(cartopy.feature.LAND)
ax.add_feature(cartopy.feature.OCEAN)
#ax.add_feature(cartopy.feature.COASTLINE)
#ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)
#ax.add_feature(cartopy.feature.LAKES, alpha=0.95)
#ax.add_feature(cartopy.feature.RIVERS)
ax.set_extent([-150, 60, -25, 60])

shpfilename = shpreader.natural_earth(resolution='110m',
                                      category='cultural',
                                      name='admin_0_countries')
reader = shpreader.Reader(shpfilename)
countries = reader.records()


for country in countries:
    if country.attributes['NAME_EN'] == 'Spain':
        print("Spain")
        ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                          facecolor=(0, 0, 1),
                          label=country.attributes['NAME_EN'])
    else:
        print("Spain")
        ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                          facecolor=(0, 1, 0),
                          label=country.attributes['NAME_EN'])

plt.show()

This code uses the Cartopy library to create a choropleth map of the Europ with countries colored based on a condition. First, the code imports the necessary libraries and defines a Plate Carree projection. Then, it sets the extent of the map to be displayed.

The code reads the shapefile of the countries from the Natural Earth dataset and creates a Reader object. It then iterates through the countries and checks if the country name is Spain. If it is, the code adds the country’s geometry to the map with a blue color. Otherwise, it adds the country’s geometry with a green color.

Finally, the code displays the map using the plt.show() function. The commented-out lines of code show how to add other features to the map, such as land, coastlines, and borders. By default, the map displays only the ocean feature.

Course index:

Have you spent your learning budget for this month, you can join Medium here:

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

Python Programming
Python
Finacial
Geography
Course
Recommended from ReadMedium