Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Plot candlestick chart using mplfinance module in python
In the world of financial analysis, candlestick charts are an essential tool for visualizing stock price data. They provide valuable insights into market trends and patterns, showing open, high, low, and close prices for each time period.
The mplfinance module in Python makes it easy to create professional-looking candlestick charts with minimal code. Let's explore how to create these charts step by step.
What is mplfinance?
The mplfinance module is a Python library specifically designed for visualizing financial market data. It provides an intuitive interface for creating highly customizable candlestick charts with features like volume bars, moving averages, and technical indicators.
Key features include:
Multiple chart types OHLC, candlestick, line plots
Volume integration Display trading volume alongside price data
Customization options Colors, fonts, gridlines, annotations
Technical indicators Moving averages and other overlays
Installation
Install mplfinance using pip ?
pip install mplfinance pandas
Understanding Candlestick Charts
A candlestick chart displays four key price points for each time period:
Open Starting price of the period
High Highest price reached
Low Lowest price reached
Close Ending price of the period
The candlestick body shows the range between open and close prices, while the wicks (shadows) represent the high and low extremes.
Creating Sample Data
Let's create sample stock data to demonstrate candlestick plotting ?
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import mplfinance as mpf
# Create sample stock data
dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
np.random.seed(42)
# Generate realistic price movements
base_price = 100
prices = []
for i in range(len(dates)):
if i == 0:
open_price = base_price
else:
open_price = prices[i-1]['Close']
# Random daily movement
high = open_price + np.random.uniform(1, 8)
low = open_price - np.random.uniform(1, 6)
close = open_price + np.random.uniform(-4, 4)
# Ensure high > low and both contain open/close
high = max(high, open_price, close)
low = min(low, open_price, close)
volume = np.random.randint(100000, 1000000)
prices.append({
'Open': round(open_price, 2),
'High': round(high, 2),
'Low': round(low, 2),
'Close': round(close, 2),
'Volume': volume
})
# Create DataFrame
data = pd.DataFrame(prices, index=dates)
print(data.head())
Open High Low Close Volume
2024-01-01 100.00 105.31 95.66 102.49 374540
2024-01-02 102.49 108.13 99.65 105.21 950714
2024-01-03 105.21 111.85 102.40 107.63 731993
2024-01-04 107.63 111.36 103.89 105.84 598658
2024-01-05 105.84 113.21 102.07 107.96 156019
Basic Candlestick Chart
Create a simple candlestick chart ?
import mplfinance as mpf # Basic candlestick chart mpf.plot(data, type='candle', title='Basic Candlestick Chart', ylabel='Price ($)')
Candlestick Chart with Volume
Add volume bars below the price chart ?
# Candlestick chart with volume
mpf.plot(data,
type='candle',
volume=True,
title='Stock Price with Volume',
ylabel='Price ($)',
ylabel_lower='Volume')
Customized Candlestick Chart
Create a fully customized chart with styling and additional features ?
# Create custom style
custom_style = mpf.make_mpf_style(
base_mpl_style='dark_background',
marketcolors=mpf.make_marketcolors(
up='g', # Green for up candles
down='r', # Red for down candles
edge='inherit',
wick={'up':'green', 'down':'red'},
volume='blue'
),
gridstyle='-',
y_on_right=True
)
# Create the plot with custom styling
mpf.plot(data,
type='candle',
volume=True,
style=custom_style,
title='Customized Stock Chart',
ylabel='Price ($)',
ylabel_lower='Volume',
figsize=(12, 8))
Adding Moving Averages
Include moving averages as overlays on the candlestick chart ?
# Calculate moving averages
data['MA5'] = data['Close'].rolling(window=5).mean()
data['MA10'] = data['Close'].rolling(window=10).mean()
# Plot with moving averages
mpf.plot(data,
type='candle',
volume=True,
mav=(5, 10), # Moving averages
title='Candlestick Chart with Moving Averages',
ylabel='Price ($)',
ylabel_lower='Volume',
figsize=(12, 8))
Saving Charts
Save the chart as an image file ?
# Save chart to file
mpf.plot(data,
type='candle',
volume=True,
title='Stock Price Chart',
ylabel='Price ($)',
savefig='candlestick_chart.png',
figsize=(10, 6))
print("Chart saved as 'candlestick_chart.png'")
Chart saved as 'candlestick_chart.png'
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
type |
Chart type | 'candle', 'ohlc', 'line' |
volume |
Show volume bars | True, False |
mav |
Moving averages | (5, 10, 20) |
style |
Visual styling | Custom style object |
figsize |
Figure dimensions | (12, 8) |
Conclusion
The mplfinance module provides a powerful and flexible way to create professional candlestick charts in Python. With its extensive customization options and built-in financial indicators, you can create insightful visualizations for stock market analysis and trading decisions.
