How can i use trading view lightweight chart library with stream-lit for plotting stock data

import pandas as pd
from lightweight_charts import Chart
import yfinance as yf
import streamlit as st

def main():
    # Define the ticker symbol
    tickerSymbol = 'AAPL'

    # Set the start and end dates for the data
    startDate = '2023-01-01'
    endDate = '2024-01-01'

    # Get the historical data for the ticker within the specified date range and at a daily interval
    data = yf.download(tickerSymbol, start=startDate, end=endDate)

    # Create a new Streamlit chart object
    st.write("Candlestick Chart:")
    chart = Chart()
    chart.add_ohlc(data)
    st.write(chart)

if __name__ == '__main__':
    main()

this is what i coded

Hi @knox

Youโ€™ll need to use StreamlitChart() method to render the charts, the following code snippet was taken from lightweight_chartsโ€™ Documentation:

import pandas as pd
from lightweight_charts.widgets import StreamlitChart

chart = StreamlitChart(width=900, height=600)

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

chart.load()

Reference:

thanks bro it really helped me
i found another solution. but there was problem in that also. i was not able change height and width of chart . your solution is very perfect

my code solution was as follows

ticker_symbol = 'AAPL'

# Download the stock data
stock_data = yf.download(ticker_symbol, start='2023-01-01', end='2024-01-01')

# Reset the index to make the date a column
stock_data.reset_index(inplace=True)
stock_data['Date'] = pd.to_datetime(stock_data['Date'])

# Convert datetime objects to Unix timestamps
stock_data['Time'] = stock_data['Date'].apply(lambda x: int(x.timestamp()))

# Calculate SMA with a window of 20 days
stock_data['SMA'] = stock_data['Close'].rolling(window=20).mean()

# Calculate EMA with a span of 20 days
stock_data['EMA'] = stock_data['Close'].ewm(span=20, adjust=False).mean()

chartOptions = {
    "layout": {
        "textColor": 'black',
        "background": {
            "type": 'solid',
            "color": 'white'
        }
    }
}

seriesCandlestickChart = [{
    "type": 'Candlestick',
    "data": [
        {"open": row['Open'], "high": row['High'], "low": row['Low'], "close": row['Close'], "time": row['Time']}
        for index, row in stock_data.iterrows()
    ],
    "options": {
        "upColor": '#26a69a',
        "downColor": '#ef5350',
        "borderVisible": False,
        "wickUpColor": '#26a69a',
        "wickDownColor": '#ef5350'
    }
}]

seriesSMA = [{
    "type": 'Line',
    "data": [
        {"value": row['SMA'], "time": row['Time']} for index, row in stock_data.iterrows() if not pd.isnull(row['SMA'])
    ],
    "options": {
        "color": 'blue',
        "lineStyle": 0,
        "lineWidth": 1,
    }
}]

seriesEMA = [{
    "type": 'Line',
    "data": [
        {"value": row['EMA'], "time": row['Time']} for index, row in stock_data.iterrows() if not pd.isnull(row['EMA'])
    ],
    "options": {
        "color": 'red',
        "lineStyle": 0,
        "lineWidth": 1,
    }
}]

st.subheader("Candlestick Chart with SMA and EMA")

renderLightweightCharts([
    {
        "chart": chartOptions,
        "series": seriesCandlestickChart + seriesSMA + seriesEMA
    }
], 'candlestick')

hi @dataprofessor
is there any library that can plot more interactive charts than this
and also have indicators and toolkit for drawing trendline and stuff

1 Like

@knox If the answer of dataprofessor solved your issue, select it as an answer.

If you have other questions, it is better that you create another thread/topic.

Let us try to solve issues one at a time.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.