Create classic technical analysis stock charts in Python with minimal code.
The library is built around matplotlib
and pandas.
Charts can be defined using a declarative interface,
based on a set of drawing primitives like Candleststicks, Volume
and technical indicators like SMA, EMA, RSI, ROC, MACD, etc ...
Warning The interface has changed. You must pass
pricesas the first parameter ofChart.
Warning This project is experimental and the interface is likely to change. For a related project with a mature api you may want to look into mplfinance.
# Candlesticks chart with SMA, RSI and MACD indicators
import yfinance as yf
from mplchart.chart import Chart
from mplchart.primitives import Candlesticks, Volume
from mplchart.indicators import SMA, EMA, ROC, RSI, MACD
ticker = 'AAPL'
prices = yf.Ticker(ticker).history('5y')
Chart(prices, title=ticker, max_bars=250).plot(
Candlesticks(),
Volume(),
SMA(50),
SMA(200),
).plot(
RSI(), target="above"
).plot(
MACD(), target="below"
).show()Prices data is expected to be presented as a pandas DataFrame
with columns open, high, low, close volume
and a datetime index named date or datetime.
Even though the chart object automatically converts price column names to lower case before calling any indicator, if you intend on using indicators independently from the chart object, you must use prices dataframes with all lower case column names!
The library contains drawing primitives that can be used like an indicator in the plot api. Primitives are classes and must be instantiated as objects before being used with the plot api.
# Candlesticks chart
from mplchart.chart import Chart
from mplchart.primitives import Candlesticks
chart = Chart(prices.title=title, max_bars=250).plot(
Candlesticsk()
).show()The main drawing primitives are :
Candlesticksfor candlestick plotsOHLCfor open, high, low, close bar plotsPricefor price line plotsVolumefor volume bar plotsLinePlotdraw an indicator as line plotAreaPlotdraw an indicator as area plotBarPlotdraw an indicator as bar plotZigZaglines between pivot pointsPeaksto mark peaks and valleys
The libary includes some standard technical analysis indicators implemented in pandas/numpy. Indicators are classes and must be instantiated as objects before being used with the plot api.
Some of the indicators included are:
SMASimple Moving AverageEMAExponential Moving AverageWMAWeighted Moving AverageHMAHull Moving AverageROCRate of ChangeRSIRelative Strength IndexATRAverage True RangeATRPAverage True Range PercentADXAverage Directional IndexDMIDirectional Movement IndexMACDMoving Average Convergence DivergencePPOPrice Percentage OscillatorCCICommodity Channel IndexBOPBalance of PowerCMFChaikin Money FlowMFIMoney Flow IndexSLOPESlope (linear regression)STOCHStochastic OscillatorBBANDSBollinger BandsKELTNERKeltner ChannelDEMADouble Exponential Moving AverageTEMATriple Exponential Moving Average
If you have ta-lib installed you can use its abstract functions as indicators. The indicators are created by calling Function with the name of the indicator and its parameters.
# Candlesticks chart with talib indicators
from mplchart.primitives import Candlesticks
from talib.abstract import Function
indicators = [
Candlesticks(),
Function('SMA', 50),
Function('SMA', 200),
]
Chart(prices).plot(indicators).show()Most indicators are drawn as line plots with default colors and settings. You can override the rendering of an indicator by piping it with the | operator into a primitive like LinePlot, AreaPlot or BarPlot as in the example below. If the indicator returns a dataframe instead of a series you need to specify an item (column name) in the primitive.
# Customizing indicator style with LinePlot
from mplchart.indicators import SMA, EMA, ROC
from mplchart.primitives import Candlesticks, LinePlot
indicators = [
Candlesticks(),
SMA(20) | LinePlot(style="dashed", color="red", alpha=0.5, width=3)
]
Chart(prices).plot(indicators)Any callable that accepts a prices dataframe and returns a series or dataframe can be used as an indicator.
You can also implement a custom indicator as a subclass of Indicator.
# Custom Indicator Example
from mplchart.model import Indicator
from mplchart.library import calc_ema
class DEMA(Indicator):
"""Double Exponential Moving Average"""
same_scale: bool = True
# boolean, whether the indicator can be drawn
# on the same axes as the prices
def __init__(self, period: int = 20):
self.period = period
def __call__(self, prices):
series = self.get_series(prices)
ema1 = calc_ema(series, self.period)
ema2 = calc_ema(ema1, self.period)
return 2 * ema1 - ema2You can find example notebooks and scripts in the examples folder.
You can install this package with pip
pip install mplchart- python >= 3.10
- matplotlib
- pandas
- numpy
- stockcharts.com - Classic stock charts and technical analysis reference
- mplfinance - Matplotlib utilities for the visualization, and visual analysis, of financial data
- matplotlib - Matplotlib: plotting with Python
- pandas - Flexible and powerful data analysis / manipulation library for Python
- yfinance - Download market data from Yahoo! Finance's API