louisnw01 / lightweight-charts-python

Python framework for TradingView's Lightweight Charts JavaScript library.
MIT License
1.11k stars 205 forks source link

[BUG] Toolbox drawings are not loaded from drawings.json #208

Closed xylophoneengine closed 10 months ago

xylophoneengine commented 10 months ago

Expected Behavior

Persisted drawings are rendered

Current Behaviour

Drawings are not rendered

Reproducible Example

import pandas as pd
import yfinance as yf
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()
    fin_data: yf.Ticker = yf.Ticker("^SPX")
    fin_hist: pd.DataFrame = fin_data.history(
        period="max",  # 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
        interval="1d",  # 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
        start="1983-01-01",
    )
    return fin_hist

def on_search(chart, searched_string):
    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)

    # Load the drawings saved under the symbol.
    chart.toolbox.load_drawings(searched_string)

def on_timeframe_selection(chart):
    new_data = get_bar_data(
        chart.topbar["symbol"].value, chart.topbar["timeframe"].value
    )
    if new_data.empty:
        return
    # The symbol has not changed, so we want to re-render the drawings.
    chart.set(new_data, render_drawings=True)

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)

    # Imports the drawings saved in the JSON file.
    chart.toolbox.import_drawings("drawings.json")

    # Loads the drawings under the default symbol.
    chart.toolbox.load_drawings(chart.topbar["symbol"].value)

    # Saves drawings based on the symbol.
    chart.toolbox.save_drawings_under(chart.topbar["symbol"])

    chart.show(block=True)

    # Exports the drawings to the JSON file upon close.
    chart.toolbox.export_drawings("drawings.json")

Environment

- OS: Windows 10
- Library:
pandas==2.1.2
lightweight-charts==1.0.18.6
yfinance==0.2.31
louisnw01 commented 10 months ago

Hey @xylophoneengine,

Thanks for pointing this out, appeared to be a rounding error. Fixed in the latest version.

Louis