Convert Figma logo to code with AI

louisnw01 logolightweight-charts-python

Python framework for TradingView's Lightweight Charts JavaScript library.

1,637
331
1,637
105

Top Related Projects

Performant financial charts built with HTML5 canvas

18,847

The interactive graphing library for Python :sparkles:

matplotlib: plotting with Python

20,460

Interactive Data Visualization in the browser, from Python

1,358

A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews

Quick Overview

Lightweight-charts-python is a Python wrapper for the TradingView Lightweight Charts library. It allows users to create interactive financial charts in Python, leveraging the power and flexibility of the popular JavaScript charting library.

Pros

  • Easy integration of TradingView charts into Python projects
  • Supports various chart types including candlestick, line, and area charts
  • Provides real-time chart updates and interactivity
  • Customizable appearance and behavior of charts

Cons

  • Limited documentation compared to the original JavaScript library
  • May have performance limitations for very large datasets
  • Requires a web browser or WebView for rendering charts
  • Dependency on the original JavaScript library may lead to version compatibility issues

Code Examples

Creating a simple line chart:

from lightweight_charts import Chart

chart = Chart()
line_series = chart.create_line_series()
line_series.set_data([
    {'time': '2023-01-01', 'value': 10},
    {'time': '2023-01-02', 'value': 15},
    {'time': '2023-01-03', 'value': 12}
])
chart.show()

Adding a candlestick series to the chart:

from lightweight_charts import Chart

chart = Chart()
candlestick_series = chart.create_candlestick_series()
candlestick_series.set_data([
    {'time': '2023-01-01', 'open': 10, 'high': 12, 'low': 9, 'close': 11},
    {'time': '2023-01-02', 'open': 11, 'high': 15, 'low': 10, 'close': 14},
    {'time': '2023-01-03', 'open': 14, 'high': 16, 'low': 13, 'close': 15}
])
chart.show()

Customizing chart appearance:

from lightweight_charts import Chart

chart = Chart(width=800, height=400)
chart.set(
    layout_options={'background': {'type': 'solid', 'color': '#131722'}},
    grid_options={'vertLines': {'color': '#334158'}, 'horzLines': {'color': '#334158'}},
    watermark_options={'color': 'rgba(255, 255, 255, 0.1)', 'visible': True, 'text': 'Lightweight Charts Python'}
)
chart.show()

Getting Started

To get started with lightweight-charts-python, follow these steps:

  1. Install the library:

    pip install lightweight-charts
    
  2. Import and create a chart:

    from lightweight_charts import Chart
    
    chart = Chart()
    
  3. Add data series and customize as needed:

    line_series = chart.create_line_series()
    line_series.set_data([{'time': '2023-01-01', 'value': 10}, {'time': '2023-01-02', 'value': 15}])
    
  4. Display the chart:

    chart.show()
    

Competitor Comparisons

Performant financial charts built with HTML5 canvas

Pros of lightweight-charts

  • More mature and actively maintained project with a larger community
  • Offers a wider range of chart types and customization options
  • Better documentation and examples available

Cons of lightweight-charts

  • Requires more setup and configuration for Python integration
  • Steeper learning curve for Python developers unfamiliar with JavaScript

Code Comparison

lightweight-charts-python:

from lightweight_charts import Chart

chart = Chart()
chart.set(
    width=800,
    height=600,
    timeframe='1D'
)
chart.line_series(data=data, color='blue')
chart.show()

lightweight-charts:

import { createChart } from 'lightweight-charts';

const chart = createChart(document.body, {
    width: 800,
    height: 600,
});
const lineSeries = chart.addLineSeries();
lineSeries.setData(data);

The lightweight-charts-python repository provides a more Pythonic interface for creating charts, while lightweight-charts requires JavaScript knowledge and additional setup for Python integration. However, lightweight-charts offers more flexibility and features for advanced users willing to work with JavaScript or integrate it into their Python projects using tools like PyExecJS or a web framework.

18,847

The interactive graphing library for Python :sparkles:

Pros of plotly.py

  • More comprehensive and feature-rich, offering a wide range of chart types and customization options
  • Well-established library with extensive documentation and community support
  • Supports both static and interactive visualizations

Cons of plotly.py

  • Larger library size and potentially slower performance for simple charts
  • Steeper learning curve due to its extensive feature set

Code Comparison

lightweight-charts-python:

from lightweight_charts import Chart

chart = Chart()
chart.line_series(data=[
    {'time': '2019-04-11', 'value': 80.01},
    {'time': '2019-04-12', 'value': 96.63},
    {'time': '2019-04-13', 'value': 76.64}
])
chart.show()

plotly.py:

import plotly.graph_objects as go

fig = go.Figure(data=go.Scatter(x=['2019-04-11', '2019-04-12', '2019-04-13'],
                                y=[80.01, 96.63, 76.64]))
fig.show()

Both libraries offer simple ways to create line charts, but plotly.py provides more flexibility for complex visualizations. lightweight-charts-python focuses on simplicity and performance for financial charting, while plotly.py offers a broader range of chart types and customization options suitable for various data visualization needs.

matplotlib: plotting with Python

Pros of matplotlib

  • Extensive and versatile plotting library with support for a wide range of chart types
  • Large community and extensive documentation
  • Highly customizable with fine-grained control over plot elements

Cons of matplotlib

  • Steeper learning curve for beginners
  • Can be slower for rendering large datasets or interactive plots
  • More complex setup and dependencies compared to lightweight alternatives

Code Comparison

matplotlib:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()

lightweight-charts-python:

from lightweight_charts import Chart

chart = Chart()
line_series = chart.create_line_series()
line_series.set_data([{"time": i, "value": i**2} for i in range(10)])
chart.show()

The matplotlib example demonstrates a simple line plot using NumPy for data generation, while the lightweight-charts-python example shows how to create a basic line chart with minimal setup. Matplotlib offers more flexibility but requires more code for customization, whereas lightweight-charts-python provides a simpler API for quick charting tasks.

20,460

Interactive Data Visualization in the browser, from Python

Pros of Bokeh

  • More comprehensive and feature-rich library for interactive visualizations
  • Supports a wide range of chart types and customization options
  • Large community and extensive documentation

Cons of Bokeh

  • Steeper learning curve due to its extensive feature set
  • Heavier library with larger file sizes
  • May be overkill for simple charting needs

Code Comparison

Bokeh:

from bokeh.plotting import figure, show

p = figure(title="Simple Line Chart")
p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5])
show(p)

Lightweight-charts-python:

from lightweight_charts import Chart

chart = Chart()
line_series = chart.create_line_series()
line_series.set_data([
    {'time': '2019-04-11', 'value': 80.01},
    {'time': '2019-04-12', 'value': 96.63},
    {'time': '2019-04-13', 'value': 76.64}
])
chart.show()

Bokeh offers a more traditional Python-like syntax for creating charts, while Lightweight-charts-python uses a more object-oriented approach with specific methods for different chart elements. Bokeh's example shows a simple line chart with numeric x-axis, whereas Lightweight-charts-python demonstrates a time series chart with date-based x-axis.

1,358

A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews

Pros of hvplot

  • Broader ecosystem integration with HoloViews, Bokeh, and other PyViz tools
  • More diverse chart types and advanced customization options
  • Better support for large datasets and interactive exploration

Cons of hvplot

  • Steeper learning curve due to its extensive feature set
  • Heavier dependency footprint, which may impact project size and load times
  • Potentially slower rendering for simple charts compared to lightweight alternatives

Code Comparison

hvplot:

import hvplot.pandas
import pandas as pd

df = pd.read_csv('data.csv')
plot = df.hvplot.line(x='date', y='value', title='Time Series')

lightweight-charts-python:

from lightweight_charts import Chart

chart = Chart()
chart.line_series(data, 'date', 'value')
chart.show()

Summary

hvplot offers a more comprehensive charting solution with extensive customization and ecosystem integration, while lightweight-charts-python provides a simpler, more lightweight approach for basic charting needs. The choice between them depends on the specific requirements of your project, such as the complexity of visualizations needed and performance considerations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

lightweight-charts-python

PyPi Release Made with Python License Documentation

cover

lightweight-charts-python aims to provide a simple and pythonic way to access and implement TradingView's Lightweight Charts.

Installation

pip install lightweight-charts

Features

  1. Streamlined for live data, with methods for updating directly from tick data.
  2. Multi-pane charts using Subcharts.
  3. The Toolbox, allowing for trendlines, rectangles, rays and horizontal lines to be drawn directly onto charts.
  4. Events allowing for timeframe selectors (1min, 5min, 30min etc.), searching, hotkeys, and more.
  5. Tables for watchlists, order entry, and trade management.
  6. Direct integration of market data through Polygon.io's market data API.

Supports: Jupyter Notebooks, PyQt6, PyQt5, PySide6, wxPython, Streamlit, and asyncio.

PartTimeLarry: Interactive Brokers API and TradingView Charts in Python


1. Display data from a csv:

import pandas as pd
from lightweight_charts import Chart


if __name__ == '__main__':
    
    chart = Chart()
    
    # Columns: time | open | high | low | close | volume 
    df = pd.read_csv('ohlcv.csv')
    chart.set(df)
    
    chart.show(block=True)

setting_data image


2. Updating bars in real-time:

import pandas as pd
from time import sleep
from lightweight_charts import Chart

if __name__ == '__main__':

    chart = Chart()

    df1 = pd.read_csv('ohlcv.csv')
    df2 = pd.read_csv('next_ohlcv.csv')

    chart.set(df1)

    chart.show()

    last_close = df1.iloc[-1]['close']
    
    for i, series in df2.iterrows():
        chart.update(series)

        if series['close'] > 20 and last_close < 20:
            chart.marker(text='The price crossed $20!')
            
        last_close = series['close']
        sleep(0.1)

live data gif


3. Updating bars from tick data in real-time:

import pandas as pd
from time import sleep
from lightweight_charts import Chart


if __name__ == '__main__':
    
    df1 = pd.read_csv('ohlc.csv')
    
    # Columns: time | price 
    df2 = pd.read_csv('ticks.csv')
    
    chart = Chart()
    
    chart.set(df1)
    
    chart.show()
    
    for i, tick in df2.iterrows():
        chart.update_from_tick(tick)
            
        sleep(0.03)

tick data gif


4. Line Indicators:

import pandas as pd
from lightweight_charts import Chart


def calculate_sma(df, period: int = 50):
    return pd.DataFrame({
        'time': df['date'],
        f'SMA {period}': df['close'].rolling(window=period).mean()
    }).dropna()


if __name__ == '__main__':
    chart = Chart()
    chart.legend(visible=True)

    df = pd.read_csv('ohlcv.csv')
    chart.set(df)

    line = chart.create_line('SMA 50')
    sma_data = calculate_sma(df, period=50)
    line.set(sma_data)

    chart.show(block=True)

line indicators image


5. Styling:

import pandas as pd
from lightweight_charts import Chart


if __name__ == '__main__':
    
    chart = Chart()

    df = pd.read_csv('ohlcv.csv')

    chart.layout(background_color='#090008', text_color='#FFFFFF', font_size=16,
                 font_family='Helvetica')

    chart.candle_style(up_color='#00ff55', down_color='#ed4807',
                       border_up_color='#FFFFFF', border_down_color='#FFFFFF',
                       wick_up_color='#FFFFFF', wick_down_color='#FFFFFF')

    chart.volume_config(up_color='#00ff55', down_color='#ed4807')

    chart.watermark('1D', color='rgba(180, 180, 240, 0.7)')

    chart.crosshair(mode='normal', vert_color='#FFFFFF', vert_style='dotted',
                    horz_color='#FFFFFF', horz_style='dotted')

    chart.legend(visible=True, font_size=14)

    chart.set(df)

    chart.show(block=True)

styling image


6. Callbacks:

import pandas as pd
from lightweight_charts import Chart


def get_bar_data(symbol, timeframe):
    if symbol not in ('AAPL', 'GOOGL', 'TSLA'):
        print(f'No data for "{symbol}"')
        return pd.DataFrame()
    return pd.read_csv(f'bar_data/{symbol}_{timeframe}.csv')


def on_search(chart, searched_string):  # Called when the user searches.
    new_data = get_bar_data(searched_string, chart.topbar['timeframe'].value)
    if new_data.empty:
        return
    chart.topbar['symbol'].set(searched_string)
    chart.set(new_data)


def on_timeframe_selection(chart):  # Called when the user changes the timeframe.
    new_data = get_bar_data(chart.topbar['symbol'].value, chart.topbar['timeframe'].value)
    if new_data.empty:
        return
    chart.set(new_data, True)


def on_horizontal_line_move(chart, line):
    print(f'Horizontal line moved to: {line.price}')


if __name__ == '__main__':
    chart = Chart(toolbox=True)
    chart.legend(True)

    chart.events.search += on_search

    chart.topbar.textbox('symbol', 'TSLA')
    chart.topbar.switcher('timeframe', ('1min', '5min', '30min'), default='5min',
                          func=on_timeframe_selection)

    df = get_bar_data('TSLA', '5min')
    chart.set(df)

    chart.horizontal_line(200, func=on_horizontal_line_move)

    chart.show(block=True)

callbacks gif


Documentation

Inquiries: shaders_worker_0e@icloud.com


This package is an independent creation and has not been endorsed, sponsored, or approved by TradingView. The author of this package does not have any official relationship with TradingView, and the package does not represent the views or opinions of TradingView.