Skip to main content

The Lightweight Charts Jupyter extension

Project description

QCharts

A Jupyter stock charting extension built on TradingView Lightweight Charts. Create interactive candlestick charts, technical indicators, and volume charts in Jupyter Notebook via a Python API.

中文文档


Features

  • 6 Chart Types — Candlestick, Line, Area, Bar, Baseline, Histogram
  • Multi-Pane Support — Stack multiple panels in a single chart (main chart + volume + MACD + KDJ, etc.)
  • Built-in Technical Indicatorsplot_ma() Moving Averages, plot_macd() MACD, plot_kdj() KDJ
  • Batch Linesplot_lines() draws multiple lines at once via a column list or column→style mapping
  • Rectangle Bandsplot_rectangle() draws horizontal price bands for support/resistance or ranges
  • Volume — Auto-colored by up/down, compressed at the bottom of the candlestick pane
  • Trade Markers — Annotate buy/sell signals on the chart via set_markers()
  • Interactive Legend — Real-time OHLC, price change %, and volume on crosshair hover
  • Responsive Sizing — Fixed dimensions or auto-fill container
  • Multiple Display Modes — Embedded Jupyter widget, IPython rich output, or browser for scripts

Installation

pip install qcharts
# or with uv
uv add qcharts

Dependencies:

  • Python >= 3.12
  • anywidget >= 0.11.0
  • pandas >= 3.0.3
  • JupyterLab >= 4.5 (for widget display)

Quick Start

import pandas as pd
from qcharts import Chart

# Load stock data
df = pd.read_csv("stock.csv", parse_dates=["date"])

# Create chart and set data
chart = Chart(height=400)
chart.plot_stock(df, "603629")
chart  # Display in Jupyter (widget)

In a plain script (no Jupyter kernel), use show() to open a self-contained HTML in the browser:

chart.show()

Usage Guide

1. Basic Candlestick + Volume

plot_stock() creates candlestick and volume in one step, setting the pane label to the stock code:

chart = Chart(height=400)
chart.plot_stock(df, "603629")
chart

Or build step by step:

chart = Chart(height=400)
chart.plot_candles(df)                  # Candlestick
chart.plot_volume(df, pane_name="vol")  # Volume (separate pane)
chart

DataFrame requirements: Must contain a datetime (or date) column plus open, high, low, close columns; volume also requires a volume column. The datetime/date column may also be supplied as the DataFrame index.

2. Moving Averages

plot_ma() auto-detects columns matching prefix + number:

df_ma = df[["date", "close"]].copy()
df_ma["ma5"] = df_ma["close"].rolling(5).mean()
df_ma["ma10"] = df_ma["close"].rolling(10).mean()
df_ma["ma20"] = df_ma["close"].rolling(20).mean()

chart.plot_ma(df_ma, prefix="ma")

Custom colors:

chart.plot_ma(df_ma, prefix="ma", colors=["#2962FF", "#FF6D00", "#7B1FA2"])

3. MACD Indicator

plot_macd() creates MACD line, signal line, and histogram (with 4-color auto styling):

ema12 = df["close"].ewm(span=12, adjust=False).mean()
ema26 = df["close"].ewm(span=26, adjust=False).mean()

df_macd = df[["date"]].copy()
df_macd["macd"] = ema12 - ema26
df_macd["signal"] = df_macd["macd"].ewm(span=9, adjust=False).mean()
df_macd["hist"] = df_macd["macd"] - df_macd["signal"]

chart.plot_macd(df_macd)

DataFrame requirements: Must contain datetime (or date), macd, signal, hist columns.

4. KDJ Indicator

chart.plot_kdj(df_kdj)

DataFrame requirements: Must contain datetime (or date), k, d, j columns.

5. Batch Lines

plot_lines() draws multiple lines at once, accepting a column list or a column → style mapping:

# Column list: colors cycle through the default palette
chart.plot_lines(df, ["close", "ma5", "ma10"])

# Mapping: value is a color string, or a full config dict passed to add_line
chart.plot_lines(df, {
    "close": "#2962FF",
    "ma20": {"color": "#FF6D00", "line_width": 2},
})

6. Rectangle Bands

plot_rectangle() draws a horizontal price band, useful for marking support/resistance or ranges:

chart.plot_rectangle(
    t1="2024-01-01", t2="2024-03-01",
    high=10.5, low=9.5,
    color="#2962FF", alpha=0.2,
)

alpha controls the fill transparency; color sets the top/bottom edge lines.

7. Trade Signal Markers

markers = [
    {"time": 1704067200, "position": "belowBar", "shape": "arrowUp",
     "color": "#26a69a", "text": "Buy"},
    {"time": 1704153600, "position": "aboveBar", "shape": "arrowDown",
     "color": "#ef5350", "text": "Sell"},
]

# Get candlestick series and set markers
candle = chart.series["default_candlestick"]
candle.set_markers(markers)

Supported position: aboveBar, belowBar, inBar. Supported shape: arrowUp, arrowDown, circle, square, etc.

8. Multi-Pane Management

All series go into the main pane by default. Technical indicators (MACD, KDJ) auto-create new panes. You can also manage panes manually:

chart.add_pane("volume", label="Volume", height=20)
chart.plot_volume(df, pane_name="volume")

chart.add_pane("rsi", label="RSI", height=15)
chart.add_line("rsi", pane_name="rsi", color="#7B1FA2")

height is a proportional weight (not pixels), controlling the relative height of each pane.

9. Chart Sizing

# Fixed size
chart = Chart(width=800, height=500)

# Auto-fill container
chart = Chart(auto_size=True)

# Resize dynamically
chart.set_size(width=1000, height=600)

10. Custom Styling

All add_* methods accept Lightweight Charts style options. Parameters support both snake_case and camelCase:

chart.add_line("ma20", color="#FF6D00", line_width=2, line_style=2)
chart.add_candlestick("kline", up_color="#ef5350", down_color="#26a69a",
                       border_visible=True)

Data Format

All methods accept either a pandas.DataFrame or a pre-formatted list[dict].

DataFrame Format

Method Required Columns
plot_stock / plot_candles datetime (or date), open, high, low, close
plot_volume datetime (or date), volume, close, open
plot_ma datetime (or date), ma{N} columns (e.g. ma5, ma10)
plot_macd datetime (or date), macd, signal, hist
plot_kdj datetime (or date), k, d, j
plot_lines datetime (or date), plus the columns specified in lines

The time column may be datetime or date, or supplied as the DataFrame index; dtypes datetime64[ns], datetime64[us], datetime64[ms] are auto-converted to Unix timestamps (seconds).

list[dict] Format

# Candlestick data
[{"time": 1704067200, "open": 10.0, "high": 10.5, "low": 9.8, "close": 10.3}]

# Line/Area data
[{"time": 1704067200, "value": 10.3}]

# Histogram data (per-bar color supported)
[{"time": 1704067200, "value": 12345, "color": "#ef535080"}]

API Reference

Chart(width=0, height=300, auto_size=False)

Business-layer methods (plot_*):

Method Description
plot_stock(data, code, pane_name=None, up_color, down_color) One-step candlestick + volume, sets pane label to code
plot_candles(data, pane_name=None, up_color, down_color) Set candlestick data
plot_volume(data, pane_name=None, up_color, down_color) Set volume data (colored by up/down)
plot_lines(data, lines, pane_name=None) Batch-draw lines (column list or column → style mapping)
plot_ma(data, pane_name=None, prefix='ma', colors=None) Add moving averages
plot_macd(data, pane_name='macd', macd_color, signal_color) Add MACD (line + signal + histogram)
plot_kdj(data, pane_name='kdj', k_color, d_color, j_color) Add KDJ (K/D/J lines)
plot_rectangle(t1, t2, high, low, color, pane_name=None, alpha=0.2) Draw a horizontal price band

Low-level series methods (add_*):

Method Description
add_line(name, pane_name=None, color='#2962FF', **kwargs) Add line series
add_area(name, pane_name=None, **kwargs) Add area series
add_bar(name, pane_name=None, **kwargs) Add bar series
add_baseline(name, pane_name=None, **kwargs) Add baseline series
add_histogram(name, pane_name=None, **kwargs) Add histogram series
add_candlestick(name, pane_name=None, **kwargs) Add candlestick series (custom name)

Chart management:

Method Description
add_pane(name, label=None, height=30) Add a new pane
get_pane(name) Get a pane object
set_size(width=0, height=300) Resize the chart
show(open_browser=True) Display: rich output in a kernel, otherwise open self-contained HTML in browser

Series Methods

Each add_* method returns a Series object with:

Method Description
set_data(data) Update series data
set_markers(markers) Set trade markers

Development

# Python environment
uv sync

# JS build
cd js
pnpm install
pnpm run build        # Build ESM bundle
pnpm run dev          # Watch mode

# Formatting
cd js
pnpm run format       # Prettier formatting

After modifying JS code, rebuild with pnpm run build and restart the Jupyter kernel to see changes.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

qcharts-1.3.2.tar.gz (162.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

qcharts-1.3.2-py3-none-any.whl (84.0 kB view details)

Uploaded Python 3

File details

Details for the file qcharts-1.3.2.tar.gz.

File metadata

  • Download URL: qcharts-1.3.2.tar.gz
  • Upload date:
  • Size: 162.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for qcharts-1.3.2.tar.gz
Algorithm Hash digest
SHA256 2274cedae34ccdff66c284c6af157f484993374e1e0f7833bbb4967262b7bd47
MD5 8ade59d93dc34ccbbfa510d98999311d
BLAKE2b-256 d52887b90deb4d4e59fdec394854925f52d69f2c97579f0bf542b7a050b24ca1

See more details on using hashes here.

File details

Details for the file qcharts-1.3.2-py3-none-any.whl.

File metadata

  • Download URL: qcharts-1.3.2-py3-none-any.whl
  • Upload date:
  • Size: 84.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for qcharts-1.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c4158d114893051525aa4f0b2830710926e23550581a53bbe9a35afb232f91c4
MD5 13e2fb5d7ff9f4ce65f5a0f7c5ec9b9f
BLAKE2b-256 ed66551a345e0d5c6094e37eeb8581597eff49ce4c587228c6f1107d6efaf2d4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page