louisnw01 / lightweight-charts-python Goto Github PK
View Code? Open in Web Editor NEWPython framework for TradingView's Lightweight Charts JavaScript library.
License: MIT License
Python framework for TradingView's Lightweight Charts JavaScript library.
License: MIT License
Hi,
i suggest to add an argument to the show()
function which will display the chart window maximized.
chart2 = chart.create_subchart(position='bottom', width=0.9, height=0.3, sync=True)
subchart is always on the right of main chart
Is it possible to add legends for lines? Would be nice to see both the main charts values and the lines values in the legend at the same time.
Hi,
great work on the package. But how do i add technical indicators on a separate pane.
I am experiencing an issue where the chart is not displaying after running the code. I have followed the necessary steps and reviewed the documentation, but I'm unable to resolve the problem.
Code Snippet:
import pandas as pd
from lightweight_charts import Chart
import yfinance as yf
data = yf.download("AWL.NS", period= "50d" , interval= "15m")
data["time"] = data.index
data = data.reset_index(drop = True)
data.rename(columns={'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume' : 'volume'}, inplace=True)
if __name__ == '__main__':
chart = Chart()
# Columns: | time | open | high | low | close | volume (if volume is enabled) |
df = data
chart.set(df)
chart.show(block=True)
Hi,
i just noticed that the enhancement for the set method were not done for the update method. I think it should work the same way.
when using set, the column names can now be capitalised, and the date column can be the index.
BR
As the title suggests, I want to be able to render minute-level data and display changes in StreamlitChart.
Hi,
for charts we can use the set() method with an empty dataframe to clear the data. I think the same should work with lines:
def set(self, data: pd.DataFrame, name=''):
"""
Sets the line data.\n
:param data: If the name parameter is not used, the columns should be named: date/time, value.
:param name: The column of the DataFrame to use as the line value. When used, the Line will be named after this column.
"""
if data.empty or data is None:
self.run_script(f'{self.id}.series.setData([]); {self.id}.name = "{name}"')
return
...
Hi!
Is it possible to get a sma indicator while also updating the bars (the sma updates as new bars appear)?
`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]
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)`
OS: Ubuntu 22.04
Python version: 3.10
Error:
Traceback (most recent call last):
File "/home/hamza/.local/lib/python3.10/site-packages/webview/platforms/gtk.py", line 494, in _callback
value = webview.run_javascript_finish(task)
gi.repository.GLib.GError: WebKitJavascriptError: about:blank:3:31: TypeError: JSON.stringify cannot serialize cyclic structures. (699)
Example code:
chart = Chart(debug=True)
chart.legend(visible=True)
df = pd.read_csv('ohlcv.csv')
chart.set(df)
line = chart.create_line()
sma_data = calculate_sma(df, period=50)
line.set(sma_data, name='SMA 50')
After this error, realtime plotting has stopped.
Although, I tried on Ubuntu 20.04 and windows 10 it works perfectly.
Hi,
when setting new data to the chart the markers from before will still be in the array of markers and shown at the first data point.
I suggest to add the function remove_marker_all()
to clear the array of markers:
def remove_marker_all(self):
"""
Clears the array of markers.\n
"""
self.run_script(f'''
{self.id}.markers = []
{self.id}.series.setMarkers({self.id}.markers)''')
BR
Hi there!
Thanks for putting this package together!
I've been experimenting with this package all day, and I think I've come to realize that because I run my application in Docker, I'm in for a hard time. Even the most basic example doesn't run; it requires the container image to have all sorts of GTK/QT system and python dependencies installed, as well as xhost and probably other magic on my Docker host to make this all work. I've been at it all day and have nothing to show for it so I think I need to approach this differently.
I was thinking of building a Streamlit app and using the Streamlit hooks you've included in the package, but as I was reading through the docs, I came across this snippet:
This object only supports the displaying of static data, and should not be used with the update_from_tick or update methods. Every call to the chart object must occur before calling load.
Does that mean I can't use this with callbacks/realtime data? If not, then I'll need to look at another approach.
Thanks for your time!
Hello sir thank you for this. I am trying to get tick chart working. Here is my setup.
Here is what i am trying to do.
Get live current data from selenium.
save tick data in CSV. (trying to avoid this)
tick_now - holds 5 seconds interval tick data with tick time.
is it possible to pass tick_now as a tick source for tick chart along with historical csv?
I am finding hard to understand how tick plot works, it is possible to plot using historical data and supplying live tick data from above selenium without saving tick data to CSV and loading data from CSV.
My goal is to plot intraday ( 1 min candle), in this case do my historical ohlc data has to be 1 min ohlc as well?
What is the exact time format required for tick data? - 2023-05-04 15:15:17.630544+00:00
do datetime.now() work?
Sorry for dumb question. Thank you for this awesome project.
Hello,
i'm trying to implement show_async to have a more flexible chart. I am using the Callbacks example.
I'm wondering about two things.
1.) Accessing subcharts
When using the Callbacks example I want to create a chart including subcharts. I am struggling to access the subcharts (including their lines) after creating them in the main function. What is the best way to access them?
2.) Setting the switcher widget current option programmatically
In the example the topbar text is set
self.chart.topbar['symbol'].set(searched_string)
I am wondering if I can do the same for a switcher widget? I couldn't find any similiar way to change the current option programmatically
BR
OS: 22.04
Python version: 3.10
Code:
import pandas as pd
from time import sleep
from lightweight_charts import Chart
import sqlite3
def calculate_sma(data: pd.DataFrame, period: int = 50):
def avg(d: pd.DataFrame):
return d['close'].mean()
result = []
for i in range(period - 1, len(data)):
val = avg(data.iloc[i - period + 1:i])
result.append({'time': data.iloc[i]['time'], f'SMA {period}': val})
return pd.DataFrame(result)
if __name__ == '__main__':
chart = Chart()
symbol = "LINAUSDT"
timeframe = "5m"
conn_ohlc = sqlite3.connect(f'data/{symbol}_{timeframe}_ohlc.db')
df_ohlc = pd.read_sql_query('SELECT * FROM ohlc_data', conn_ohlc)
df1 = df_ohlc[:30]
df2 = df_ohlc[30:]
chart.set(df1)
line = chart.create_line()
sma_data = calculate_sma(df1, period=10)
line.set(sma_data, name='SMA 10')
chart.show()
last_close = df1.iloc[-1]
for i, series in df2.iterrows():
chart.update(series)
line.update(series)
last_close = series['close']
sleep(0.1)
Problem: Candlestick and line disappears after updating line, although when i fetch live data it does'nt make problem as such.
Thanks in advance
Note: I have used updated version of this lightweight_charts
library
Hi,
I was wondering how I can create a subchart within a subchart. If we take both of your examples, I would want to create a 4x4 layout, so 4 charts and all of them should have a 0.2 height subchart for RSI. Is this possible as of now or how could I do this? I was thinking maybe 4x8 chart, but this didn't work.
On a note, is there a way to change the color of lines?
Thanks!
I get an issue after update to use subchart feature, my version is py 3.9.13
from lightweight_charts import Chart
File "C:\Users\VLus\anaconda3\lib\site-packages\lightweight_charts_init.py", line 1, in
from .chart import Chart
File "C:\Users\VLus\anaconda3\lib\site-packages\lightweight_charts\chart.py", line 8, in
from lightweight_charts.pywebview import loop
File "C:\Users\VLus\anaconda3\lib\site-packages\lightweight_charts\pywebview.py", line 6, in
from lightweight_charts.js import LWC
File "C:\Users\VLus\anaconda3\lib\site-packages\lightweight_charts\js.py", line 47, in
class LWC:
File "C:\Users\VLus\anaconda3\lib\site-packages\lightweight_charts\js.py", line 528, in LWC
width: float = 0.5, height: float = 0.5, sync: bool | UUID = False):
TypeError: unsupported operand type(s) for |: 'type' and 'type'
Hello,
I'm writing to request support for Python 3.8 in your Lightweight Charts Python project.
I have been using your project and find it very useful. However, I would like to use it along with QuantConnect, which currently only supports Python 3.8.
I have done some preliminary testing on my local environment, and it seems that the library functions well with Python 3.8. This preliminary testing was not exhaustive though, so it would be great if you could confirm this compatibility.
I believe Python 3.8 support would make your project even more helpful to a broader audience, and I am eager to hear your thoughts on this.
Thank you for your consideration and for all your work on this project.
Best regards
@louisnw01 This is a wonderful package and I applaud your work! Would you be interested in building a more expansive version that adds broker trading (via Alpaca)? I'm wanting something for my personal trading and can provide some financial support.
Hey all, I've stumbled across lightweight_charts and looking to use in a project but have been unsuccessful in even getting to import the package.
Following the sample code,
import pandas as pd
from lightweight_charts import Chart
if __name__ == '__main__':
chart = Chart()
# Columns: | time | open | high | low | close | volume (if volume is enabled) |
# df = pd.read_csv('ohlcv.csv') ### df saved and formatted from yfinance data.
chart.set(df)
chart.show(block=True)
I'm getting this error -
ImportError: cannot import name 'Unpack' from 'typing_extensions' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/typing_extensions.py)
I've tried re-installing and updating all packages for pandas, lightweight-charts, typing_extensions, and python. Versions are below
lightweight-charts == 1.0.13.1
pandas == 2.0.3
typing_extensions == 4.7.0
python == 3.10.0
It didn't look like this error had come up in closed issues, unsure what I may be doing wrong but any help would be greatly appreciated.
Hey. There is a little problem when using .set() and intraday candles. First .set() will modify dataset itself making it unusable later on.
My workaround was using .copy() when executing _df_datetime_format() method.
Example:
chart = Chart()
#ohlc with time format ("%Y-%m-%d %H:%M%S)
chart.set(candles)
line = chart.create_line()
#not going to work since time column was modified to timestamps on previous .set()
line.set(calculate_sma(candles))
Getting proper python implementation for these charts is a blessing. Thank you.
Hi there,
I have a question regarding the horizontal price line that gets automatically created when creating a line (e.g. for an indicator).
Is it possible to remove or disable this feature? I looked through the documentation and also in the js.py file but can't figure out how to do this.
Also how do I scale the y-axis so that it shows the lowest candle in the viewport at the bottom and the highest at the top and ignores all indicators? Is this somehow possible? Currently I have to manually adjust the y-axis to achieve this.
Thanks!
Hi,
found some weird display bug. When I use two types of markers they sometimes disappear when I zoom in. See code below.:
import pandas as pd
import numpy as np
from lightweight_charts import Chart
def calculate_sma(data: pd.DataFrame, period: int = 50):
def avg(d: pd.DataFrame):
return d['close'].mean()
result = []
for i in range(period - 1, len(data)):
val = avg(data.iloc[i - period + 1:i])
result.append({'time': data.iloc[i]['date'], 'value': val})
return pd.DataFrame(result)
if __name__ == '__main__':
chart = Chart(maximize=True)
df = pd.read_csv('ohlcv.csv')
chart.set(df)
line = chart.create_line()
sma_data = calculate_sma(df)
line.set(sma_data)
df['Gain'] = df['close'] - df['open']
longs = df.query('Gain < -20')
shorts = df.query('Gain > 20')
for index, row in longs.iterrows():
chart.marker(row['date'], 'below', 'arrow_up', 'green', 'L')
for index, row in shorts.iterrows():
chart.marker(row['date'], 'above', 'arrow_down', 'red', 'S')
chart.show(block=True)
Somehow if I only use the "longs" markers, they will not disappear when zooming in.
Video of the bug:
https://github.com/louisnw01/lightweight-charts-python/assets/104310309/4b7ef48a-002e-41d0-a62b-4f06da46b579
Regarding the live_data feature:
`
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]
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)
`
Is it possibe to loop the drawing after the chart has updated all series in df2? So the df2 bars get cleared and the program starts drawing all the df2 bars again. And it does this over and over again.
PS. Without closing the application.
Hey. Some suggestions after playing with the library for a bit.
self.run_script(f'{self._parent.id}.chart.removeSeries({self.id}.series)')
. And then keeping track of lines I've added.Thank you.
Is there any way to save the charts as a image file with for eg png format ?
# Yahoo data to show
import yfinance as yf
from lightweight_charts import Chart,JupyterChart
ticker = 'AAPL'
start = '2022-01-01'
end = '2023-01-01'
df = yf.download(ticker, start=start, end=end)
df.rename(columns = {
'Open':'open',
'High':'high',
'Low':'low',
'Close':'close',
'Volume':'volume'}, inplace = True)
df['time']=df.index
chart = Chart()
# Columns: | time | open | high | low | close | volume (if volume is enabled) |
chart.set(df)
chart.show()
Hi,
I tried creating an intraday chart from a JSON file, but the chart is almost blank with only the grid, the price axis and the last price (like the screenshot). I attached the script and the sample data, could you please check it out?
I guess there's something wrong with the time series, which is updated every few seconds, but I don't know how to make it work with your library.
Anyway, I really like you work. It looks really promising, and I love TradingView.
Best regards,
I want to use it similar to tradingview Indicators. So If I can able to hide and un-hide indicators that would be great.
Can you please add an enhancement to save the chart as html with all displayed values.
Thanks
Hi, I am trying to draw region around horizontal line is it possible to add that functionality to the horizontal line function
thanks
Hi there! Thank you for the library. Really enjoying the simplicity and elegance of it! However, after the latest upgrade, I tried to launch a chart and got a black screen with only the toolbox
on the left.
OS: Ubuntu 22.04 LTS
Python version: 3.11.4
Here's the code that I've tried to launch for testing purposes and it worked fine with the last update lightweight-charts==1.0.13.4
:
if __name__ == '__main__':
chart = PolygonChart(timeframe_options=('1min', '5min', '15min', '1H', '4H', 'D', 'W'), api_key='MY_API_KEY', live=True)
chart.polygon.log(info=True)
chart.show(block=True)
Traceback from the console:
Traceback (most recent call last):
File "/home/econlq/VSCode/realtime_chart_TWS/.venv/lib/python3.11/site-packages/webview/platforms/gtk.py", line 494, in _callback
value = webview.run_javascript_finish(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
gi.repository.GLib.GError: WebKitJavascriptError: about:blank:3:31: TypeError: JSON.stringify cannot serialize cyclic structures. (699)
There may be an issue with webview
component on my machine (Ubuntu 22.04 LTS). I haven't programmed in Python for a while, and apologize for bothering if the mistake is too obvious.
Thank you for your time!
hi,
chart.marker not set marker with format ("%Y-%m-%d %H:%M%S) - on axis data/time , just works with "1d" interval or ("%Y-%m-%d)
Need grid lines visibility in chart option set to true or false and option to plot line charts required please
HoloViz Panel is powerful data exploration & web app framework for Python. I'm a user and contributor. I work in energy trading and would like to be able to use the TradingView charts in my teams data apps.
Panel has a different architecture than Streamlit that makes it support streaming, async and bidirectional communication very well. It works both for exploration in notebooks and on web servers too.
Would you be interested in adding support for Panel? I would be willing to contribute. I already have a proof of concept, so I know it will work. I will primarily need your review and guidance. I would need to refactor the existing code a little bit.
Hi, first of all, great job on this awesome solution which is a great tool for all of us traders!
I would like to know if it is possible for us to be able to personalize our chart with the applyOptions option.
For instance, I need to change the precision on the price because at this moment it is showing only two decimal digits.
For instance, EURUSD or other currencies, we need to see at least 6 digits.
Thanks for all the great work!
Hey, first of all drawings feature is insane. Thank you!
Some minor suggestions:
"cmd-Z will delete the last drawing."
. Don't think event.metaKey
is detected correctly (as win key) while doing that on windows. Maybe replace it with Ctrl+Z
in windows case?I have been trying to save the chart image instead of showing it in a new window. Any ideas?
Thanks for the latest update. I'm currently checking newest additions.
Some things:
1)
There is a bug in new clear_markers() function:
code now:
self.run_script(f'''{self.id}.markers = []; {self.id}.series.setMarkers([]])''')
fixed code:
self.run_script(f'''{self.id}.markers = []; {self.id}.series.setMarkers([])''')
Negative values are displayed incorrectly since last update
I can't get a legend to show in a subchart. I think this did not work in previous version too?
while giving input to dataframe open, high , low , close , and volume are always needed to be small case can you add support to Title case and camel case
Can we please have full trade entry exit symbology, like Long, Short, Stop Loss and Profit Target, with Labels.
That way one can place trades directly from Python onto a TradingView chart, which would be mind-boggling.
import pandas as pd
from lightweight_charts import Chart
if __name__ == '__main__':
chart = Chart()
# Columns: | time | open | high | low | close | volume (if volume is enabled) |
df = pd.read_csv('ohlcv.csv', index_col=0).iloc[:100]
print(df)
chart.set(df)
chart.show(block=True)
python version 3.9.13
after running the chart is completely blank, here's an image for reference:
# Yahoo data to show
import yfinance as yf
from lightweight_charts import Chart,JupyterChart
ticker = 'AAPL'
start = '2022-01-01'
end = '2023-01-01'
df = yf.download(ticker, start=start, end=end)
df.rename(columns = {
'Open':'open',
'High':'high',
'Low':'low',
'Close':'close',
'Volume':'volume'}, inplace = True)
df['time']=df.index
chart = Chart()
# Columns: | time | open | high | low | close | volume (if volume is enabled) |
chart.set(df)
chart.show()
Hi, I just installed the package and ran this, which gave an error.
import yfinance as yf
df = yf.Ticker("aapl").history(start="2020-06-02", end="2020-06-07", interval="1d")
df = df.reset_index().rename(columns = {"Date": "time", "Open": "open", "High": "high", "Low": "low", "Close": "close", "Volume": "volume"})
import pandas as pd
from lightweight_charts import Chart
chart = Chart()
chart.set(df)
chart.show(block=True)
Process Process-1:
Traceback (most recent call last):
File "/home/adrian/miniconda3/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
self.run()
File "/home/adrian/miniconda3/lib/python3.10/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/home/adrian/miniconda3/lib/python3.10/site-packages/lightweight_charts/chart.py", line 17, in init
self.loop()
File "/home/adrian/miniconda3/lib/python3.10/site-packages/lightweight_charts/chart.py", line 23, in loop
webview.start(debug=self.debug) if arg == 'start' else getattr(self.webview, arg)()
File "/home/adrian/miniconda3/lib/python3.10/site-packages/webview/init.py", line 132, in start
guilib = initialize(gui)
File "/home/adrian/miniconda3/lib/python3.10/site-packages/webview/guilib.py", line 92, in initialize
if not try_import(guis):
File "/home/adrian/miniconda3/lib/python3.10/site-packages/webview/guilib.py", line 62, in try_import
if import_func():
File "/home/adrian/miniconda3/lib/python3.10/site-packages/webview/guilib.py", line 16, in import_gtk
import webview.platforms.gtk as guilib
File "/home/adrian/miniconda3/lib/python3.10/site-packages/webview/platforms/gtk.py", line 41, in
webkit_ver = webkit.get_major_version(), webkit.get_minor_version(), webkit.get_micro_version()
gi.repository.GLib.GError: g-invoke-error-quark: Could not locate webkit_get_major_version: 'webkit_get_major_version': /lib/x86_64-linux-gnu/libjavascriptcoregtk-4.0.so.18: undefined symbol: webkit_get_major_version (1)
** (ipykernel_launcher.py:81049): WARNING **: 00:18:13.758: Failed to load shared library 'libwebkit2gtk-4.0.so.37' referenced by the typelib: /lib/x86_64-linux-gnu/libwebkit2gtk-4.0.so.37: undefined symbol: gst_codec_utils_caps_get_mime_codec
Hi,
I noticed that in a chart with a synced subchart both charts can have different width if for ex. the chart has values from 1000-2000 and the subchart 1,000,000 - 2,000,000.
This code does show the problem:
import pandas as pd
from lightweight_charts import Chart
if __name__ == '__main__':
chart = Chart(inner_width=1, inner_height=0.8)
chart2 = chart.create_subchart(sync=True, position='bottom', width=1, height=0.2)
line1 = chart2.create_line()
chart.watermark('1')
chart2.watermark('2')
df = pd.read_csv('ohlcv.csv')
df2 = df[['date']]
df2['value'] = df['volume']
pd.DataFrame()
chart.set(df)
line1.set(df2)
chart.show(block=True)
or in this picture:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.