Chapter 3: Visualization with Matplotlib: Python for traders Series
This is a continuation of my series Python for traders
In this chapter, we will introduce Matplotlib, a Python library that is widely used for data visualization. We will cover how to create various types of plots, such as line charts, bar charts, and scatter plots, and how to customize these plots to make them more informative. We will also provide trading examples to showcase how to apply these plots in the finance industry.
Getting Started with Matplotlib
Matplotlib is a third-party library that needs to be installed before it can be used. It can be installed using the pip package manager by running the following command:
pip install matplotlib
Once you have installed Matplotlib, you can import it in your Python code using the following command:
import matplotlib.pyplot as plt
This imports the pyplot module, which provides a simple interface for creating and customizing plots.
Line Chart
A line chart is a simple plot that shows the trend of a variable over time. It is created using the plot()
function provided by Matplotlib. Let's create a simple line chart to show the stock price variation of Apple Inc. (AAPL) over time.
import pandas as pd
import matplotlib.pyplot as plt
# Load data
data = pd.read_csv('AAPL.csv')
# Create plot
plt.plot(data['Date'], data['Close'])
# Customize plot
plt.title('AAPL Stock Price Variation')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
# Display plot
plt.show()
In this example, we load the stock price data of AAPL from a CSV file using the Pandas library. We then create a line chart using the plot()
function and customize it using the title()
, xlabel()
, and ylabel()
functions. Finally, we display the plot using the show()
function.
Bar Chart
A bar chart is a chart that represents categorical data with rectangular bars. The height or length of each bar represents the value of the data. Let’s create a bar chart to show the revenue of some top technology companies in 2020.
import matplotlib.pyplot as plt
# Data
companies = ['Apple', 'Microsoft', 'Amazon', 'Alphabet', 'Facebook']
revenue = [274.5, 143.015, 386.064, 182.527, 70.7]
# Create plot
plt.bar(companies, revenue)
# Customize plot
plt.title('Top Technology Companies Revenue in 2020')
plt.xlabel('Company')
plt.ylabel('Revenue (Billion USD)')
# Display plot
plt.show()
In this example, we create a bar chart using the bar()
function and pass the companies as the categorical data and the revenue as the numerical data. We customize the plot using the title()
, xlabel()
, and ylabel()
functions and display the plot using the show()
function.
Scatter Plot
A scatter plot is a plot that displays the relationship between two variables. Each point on the plot represents a data point with its x and y coordinates. Let’s create a scatter plot to show the relationship between the stock price of AAPL and the stock price of Microsoft Corporation (MSFT) over time.
import pandas as pd
import matplotlib.pyplot as plt
# Load data
aapl_data = pd.read_csv('AAPL.csv')
msft_data = pd.read_csv('MSFT.csv')
# Create plot
plt.scatter(aapl_data['Close'], msft_data['Close'])
# Customize plot
plt.title('AAPL vs MSFT Stock Price')
plt.xlabel('AAPL Stock Price (USD)')
plt.ylabel('MSFT Stock Price (USD)')
# Display plot
plt.show()
In this example, we load the stock price data of AAPL and MSFT from CSV files using the Pandas library. We then create a scatter plot using the scatter()
function and pass the Close
price of AAPL as the x-axis data and the Close
price of MSFT as the y-axis data. We customize the plot using the title()
, xlabel()
, and ylabel()
functions and display the plot using the show()
function.
Customizing Plots
Matplotlib provides several options for customizing plots to make them more informative. Let’s see how we can customize the line chart that we created earlier.
import pandas as pd
import matplotlib.pyplot as plt
# Load data
data = pd.read_csv('AAPL.csv')
# Create plot
plt.plot(data['Date'], data['Close'], color='blue', linewidth=2, linestyle='--', marker='o', markersize=4, markerfacecolor='red')
# Customize plot
plt.title('AAPL Stock Price Variation')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.grid(True)
# Display plot
plt.show()
In this example, we customize the line chart using the following options:
color
: Changes the color of the line to bluelinewidth
: Increases the thickness of the line to 2 pixelslinestyle
: Changes the style of the line to dashedmarker
: Adds circular markers to the data pointsmarkersize
: Changes the size of the markers to 4 pixelsmarkerfacecolor
: Changes the color of the markers to redgrid
: Adds a grid to the plot to make it easier to read
Trading Examples
Now that we have learned how to create different types of plots and customize them, let’s see some trading examples that showcase how to use these plots in the finance industry.
Example 1: Moving Averages
Moving averages are commonly used in technical analysis to smooth out price fluctuations and identify trends. Let’s create a line chart to show the moving averages of AAPL stock price.
import pandas as pd
import matplotlib.pyplot as plt
# Load data
data = pd.read_csv('AAPL.csv')
# Calculate moving averages
data['MA20'] = data['Close'].rolling(window=20).mean()
data['MA50'] = data['Close'].rolling(window=50).mean()
# Create plot
plt.plot(data['Date'], data['Close'], label='Price')
plt.plot(data['Date'], data['MA20'], label='MA20')
plt.plot(data['Date'], data['MA50'], label='MA50')
# Customize plot
plt.title('AAPL Stock Price with Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
# Display plot
plt.show()
In this example, we calculate the moving averages of AAPL stock price using the rolling()
function provided by Pandas. We then create a line chart using the plot()
function and pass the Close
price as the y-axis data and the dates as the x-axis data. We also plot the moving averages using the plot()
function and add a legend to the plot using the legend()
function.
Example 2: Candlestick Chart
Candlestick charts are commonly used in technical analysis to show the price movements of an asset over time. Let’s create a candlestick chart to show the daily price movements of AAPL stock.
import pandas as pd
import matplotlib.pyplot as plt
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
# Load data
data = pd.read_csv('AAPL.csv')
# Convert dates to matplotlib format
data['Date'] = pd.to_datetime(data['Date'])
data['Date'] = data['Date'].apply(mdates.date2num)
# Prepare data for candlestick chart
ohlc = data[['Date', 'Open', 'High', 'Low', 'Close']].values
# Create plot
fig, ax = plt.subplots()
candlestick_ohlc(ax, ohlc, width=0.6, colorup='green', colordown='red')
# Customize plot
plt.title('AAPL Candlestick Chart')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.grid(True)
# Format x-axis dates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
# Display plot
plt.show()
In this example, we first load the stock price data of AAPL from a CSV file using the Pandas library. We then convert the dates to the matplotlib format using the date2num()
function provided by the matplotlib.dates
module. Next, we prepare the data for the candlestick chart by extracting the Open
, High
, Low
, and Close
prices of AAPL.
We then create the candlestick chart using the candlestick_ohlc()
function provided by the mpl_finance
module. This function takes an axis object, the OHLC data, and several customization options such as the width of the candlestick bars and the colors of the bars for up and down days.
Finally, we customize the plot by adding a title, labels to the x-axis and y-axis, and a grid. We also format the x-axis dates using the DateFormatter()
function and rotate the dates for better readability using the autofmt_xdate()
function.
Conclusion
Matplotlib is a powerful Python library for creating various types of plots and visualizations. In this chapter, we covered the basics of Matplotlib and demonstrated how to create line charts, bar charts, scatter plots, and candlestick charts. We also showed how to customize these plots to make them more informative and demonstrated some trading examples using these plots. With these skills, you should be able to create informative visualizations of financial data and use them to gain insights into the markets.
In Next Chapter we will learn about algorithmic trading with python
Chapter 4: Algorithmic Trading with Python
If you liked my content , buy me a coffee.
Note:This article is curated using AI-assisted tools.