Classic Stock Charts in Python
Reason this release was yanked:
broken on matplotlib >= 3.11
Project description
Classic Stock Charts in Python
Create classic technical analysis stock charts in Python with minimal code.
The library is built around matplotlib
and supports both pandas
and polars DataFrames.
Charts can be defined using a declarative interface,
based on a set of drawing primitives like Candlesticks, Volume
and technical indicators like SMA, EMA, RSI, ROC, MACD, etc ...
📖 Documentation: tutorials and a chart gallery at furechan.github.io/mplchart
[!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.
Typical Usage
# Candlesticks chart with SMA, RSI and MACD indicators
import yfinance as yf
from mplchart.chart import Chart
from mplchart.primitives import Candlesticks, Volume, Pane, LinePlot
from mplchart.indicators import SMA, RSI, MACD
ticker = 'AAPL'
prices = yf.Ticker(ticker).history('5y')
Chart(prices, title=ticker, max_bars=250, normalize=True).plot(
Candlesticks(), Volume(), SMA(50), SMA(200),
Pane("above", yticks=(30, 50, 70)),
LinePlot(RSI(14), overbought=70, oversold=30),
Pane("below"),
MACD(),
).show()
Styles
Charts are styled via the style= option — a builtin style, any matplotlib stylesheet name, or a custom style dict. Styles are total: ambient matplotlib settings never affect a chart.
from mplchart.styles import available_styles
available_styles()
# ['chartist', 'modern', 'mplchart', 'nightclouds']
# builtin style
Chart(prices, title=ticker, style="nightclouds").plot(Candlesticks()).show()
# any matplotlib stylesheet
Chart(prices, title=ticker, style="ggplot").plot(Candlesticks()).show()
# custom style dict
MY_STYLE = {
"stylesheet": "dark_background",
"settings": {
"candle.up.color": "#26a69a",
"candle.down.color": "#ef5350",
},
}
Chart(prices, title=ticker, style=MY_STYLE).plot(Candlesticks()).show()
Conventions
Prices data is expected to be a dataframe with columns open, high, low, close, volume in lower case and a datetime column named date or datetime (or a datetime index for pandas).
If your data has column names in different capitalization (like data from yfinance) use the normalize option Chart(..., normalize=True) or call normalize_prices explicitely to normalize the dataframe.
# Normalize prices to lower case column names
import yfinance as yf
from mplchart.utils import normalize_prices
prices = normalize_prices(yf.Ticker(ticker).history('5y'))
Drawing Primitives
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(prices, title=title, max_bars=250).plot(
Candlesticks()
).show()
The main drawing primitives are :
Candlesticksfor candlestick plotsOHLCfor open, high, low, close bar plotsVolumefor volume bar plotsPaneto switch to a different pane (above or below)LinePlotdraw an indicator as line plotAreaPlotdraw an indicator as area plotBarPlotdraw an indicator as bar plotStripesto shade background areas where a condition is activeMarkersto mark signal crossings with symbolsZigZaglines between pivot pointsSwingsto mark local peaks and valleys (swing highs/lows)TrendLinesto fit support and resistance trend lines (experimental)HLineto draw a horizontal reference line on the current paneVLineto draw a vertical line across all panes at a given date
Builtin Indicators
The library includes some standard technical analysis indicators for pandas DataFrames.
Indicators are classes and must be instantiated as objects before being used with the plot api.
Instantiated they are callables, you can apply them like calling a function SMA(50)(prices).
Some of the indicators included are:
SMASimple Moving AverageEMAExponential Moving AverageWMAWeighted Moving AverageHMAHull Moving AverageRMARolling Moving Average (Wilder's)DEMADouble Exponential Moving AverageTEMATriple Exponential Moving AverageMOMMomentumROCRate of ChangeRSIRelative Strength IndexADXAverage Directional IndexDMIDirectional Movement IndexMACDMoving Average Convergence DivergencePPOPrice Percentage OscillatorBOPBalance of PowerCMFChaikin Money FlowMFIMoney Flow IndexSTOCHStochastic OscillatorTRANGETrue RangeATRAverage True RangeNATRNormalized Average True RangeBBANDSBollinger BandsBBPBollinger Bands PercentBBWBollinger Bands WidthKELTNERKeltner ChannelDONCHIANDonchian ChannelMEDPRICEMedian PriceTYPPRICETypical PriceWCLPRICEWeighted Close PriceAVGPRICEAverage Price
Pass an indicator to a rendering primitive to customize display — the @ binding operator is an equivalent alternative:
# Customizing indicator style with LinePlot
from mplchart.indicators import SMA, EMA, ROC
from mplchart.primitives import Candlesticks, LinePlot
indicators = [
Candlesticks(),
LinePlot(SMA(20), style="dashed", color="red", alpha=0.5, width=3)
]
Chart(prices).plot(indicators)
Polars Expressions
For polars DataFrames, the expressions subpackage provides polars Expr factories
as an alternative to the indicator pattern.
These can be used directly with chart.plot().
# Candlesticks chart with polars expressions
from mplchart.chart import Chart
from mplchart.primitives import Candlesticks, Volume, Pane, LinePlot
from mplchart.expressions import SMA, EMA, RSI, MACD
Chart(prices, title=ticker, max_bars=250).plot(
Candlesticks(), Volume(), SMA(50), SMA(200),
Pane("above", yticks=(30, 50, 70)),
LinePlot(RSI(), overbought=70, oversold=30),
Pane("below"),
MACD(),
).show()
Expressions are plain polars.Expr values — they can be composed with standard polars operators,
passed to df.select(), or used anywhere polars expressions are accepted.
Pass an expression to a rendering primitive to customize display — the @ binding operator is an equivalent alternative:
from mplchart.primitives import LinePlot, AreaPlot
from mplchart.expressions import SMA, RSI
LinePlot(SMA(50), color="red") # expression → primitive
AreaPlot(RSI(14), color="blue") # expression → primitive
SMA(50) @ LinePlot(color="red") # operator form
Talib Functions
If you have ta-lib installed you can use its abstract functions as indicators. They are created by calling the Function factory with the name of the function and its parameters. Ta-lib functions work with both pandas and polars backends.
# Candlesticks chart with talib functions
from mplchart.primitives import Candlesticks
from talib.abstract import Function
indicators = [
Candlesticks(),
Function('SMA', 50),
Function('SMA', 200),
]
Chart(prices).plot(indicators).show()
Examples
Example notebooks live in the examples folder.
Installation
pip install mplchart
The indicators module requires pandas; the expressions module requires polars.
If either is already in your environment, mplchart will use it automatically.
The [pandas], [polars], and [all] extras are just a convenience — they
install pandas or polars alongside mplchart, nothing more:
pip install mplchart[pandas]
pip install mplchart[polars]
pip install mplchart[all]
Dependencies
Required:
- python >= 3.10
- matplotlib
- numpy
- pyarrow
Optional extras:
[pandas]— pandas[polars]— polars[all]— pandas and polars
Related Projects
- mplfinance - Matplotlib utilities for the visualization, and visual analysis, of financial data
- cufflinks - Productivity Tools for Plotly + Pandas
- matplotlib - Matplotlib: plotting with Python
- pandas - Flexible and powerful data analysis / manipulation library for Python
- polars - Fast DataFrame library for Python
- yfinance - Download market data from Yahoo! Finance's API
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mplchart-0.0.41-py3-none-any.whl.
File metadata
- Download URL: mplchart-0.0.41-py3-none-any.whl
- Upload date:
- Size: 624.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ba8635d0f72757c26d0f49ac163c4953a627bc5dc9a997322bce635c4b891460
|
|
| MD5 |
786a1c96797b1082f70c8af3ae55de7c
|
|
| BLAKE2b-256 |
98a255fe4f99e4d5710e1735f723cb5eceede0755301c224c2ff6e3633a28076
|