freyastreamlit / streamlit-lightweight-charts

Streamlit wrapper for lightweight-charts
MIT License
146 stars 31 forks source link

overlay and subplot do not plot Chart empty #27

Closed ajayX1 closed 1 year ago

ajayX1 commented 1 year ago

I am not a coder so please. I am trying to learn and make a analysis chart myself. I have prepared below code to plot candles with overlay ema20 and volume and macd as sub plot. candles plot but volume and MACD chart is blank. Ema also not plot. can you please suggest me the reason and solution:

selected_stock-5minute-candle.csv datetime,open,high,low,close 0,2023-05-02 09:00:00,1022.2,1022.2,1022.2,1022.2 1,2023-05-02 09:05:00,1022.2,1022.2,1020.4,1020.4 2,2023-05-02 09:15:00,1022.05,1032.15,1021.6,1031.35

selected_stock-5minute-ema.csv datetime,ema20 2023-05-02 09:00:00, 2023-05-02 09:05:00, 2023-05-02 09:15:00,

selected_stock-5minute-macd.csv datetime,macd_fast,macd_slow,macd_hist 2023-05-02 09:00:00,,, 2023-05-02 09:05:00,,, 2023-05-02 09:15:00,,, 2023-05-02 09:20:00,,, 2023-05-02 09:25:00,,, 2023-05-02 11:45:00,,, . . . 2023-05-02 11:50:00,5.165247857378063,8.073360673526318,-2.9081128161482557 2023-05-02 11:55:00,4.751474533183455,7.4089834454577455,-2.6575089122742908 2023-05-02 12:00:00,4.309327632083068,6.78905228278281,-2.479724650699742 2023-05-02 12:05:00,3.981613363333963,6.227564498893041,-2.2459511355590775

selected_stock-5minute-volume.csv datetime,volume 0,2023-05-02 09:00:00,4937 1,2023-05-02 09:05:00,2212 2,2023-05-02 09:15:00,210658

def plot_candlestick_chart(selected_stock-5minute-volume, selected_stock-5minute-candle, selected_stock-5minute-ema, selected_stock-5minute-macd, selected_stock, interval):

Read data from CSV file

dfCandle = pd.read_csv(filename1, skiprows=0, parse_dates=['datetime'], skip_blank_lines=True)
dfCandle.columns = ['datetime', 'open', 'high', 'low', 'close']
dfVolume = pd.read_csv(filename2, skiprows=0, parse_dates=['datetime'], skip_blank_lines=True)
st.write(dfVolume)
dfVolume.columns = ['datetime', 'volume']
dfema20 = pd.read_csv(filename_ema, skiprows=0, parse_dates=['datetime'], skip_blank_lines=True)
dfema20.columns = ['datetime', 'ema20']
dfMACD = pd.read_csv(filename_macd  , skiprows=0, parse_dates=['datetime'], skip_blank_lines=True)
dfMACD.columns = ['datetime', 'macd_fast', 'macd_slow', 'macd_hist']
dfCandle['time'] = dfCandle['datetime'].apply(lambda x: int(x.timestamp()))
dfVolume['time'] = dfVolume['datetime'].apply(lambda x: int(x.timestamp()))
dfema20['time'] = dfema20['datetime'].apply(lambda x: int(x.timestamp()))
dfMACD['time'] = dfMACD['datetime'].apply(lambda x: int(x.timestamp()))
# Prepare the data for the candlestick chart
candles = dfCandle[['time', 'open', 'high', 'low', 'close']].to_dict(orient='records')
# Prepare the data for the volume chart
volume = dfVolume[['time', 'volume']].to_dict(orient='records')
st.write(volume)
ema20 = dfema20[['time', 'ema20']].dropna().to_dict(orient='records')
st.write(ema20)
macd_fast = dfMACD[['time', 'macd_fast']].dropna().to_dict(orient='records')
macd_slow = dfMACD[['time', 'macd_slow']].dropna().to_dict(orient='records')
macd_hist = dfMACD[['time', 'macd_hist']].dropna().to_dict(orient='records')
st.write(macd_fast)

# Define the series for the candlestick and volume charts
series_candlestick_chart = [
    {
        "type": "Candlestick",
        "data": candles,
        "options": {
            "upColor": COLOR_BULL,
            "downColor": COLOR_BEAR,
            "borderVisible": False,
            "wickUpColor": COLOR_BULL,
            "wickDownColor": COLOR_BEAR
        }
    }
]

series_ema20_line = [
    {
        "type": "Line",
        "data": ema20,
        "options": {
            "color": 'green',
            "lineWidth": 2,
        }
    }
]

series_volume_chart = [
    {
        "type": "Bar",
        "data": volume,
        "options": {
            "color": volume_colors,
            "priceFormat": {
                "type": "volume"
            },
            "priceScaleId": ""
        },
        "priceScale": {
            "scaleMargins": {
                "top": 0,
                "bottom": 0
            },
            "alignLabels": False
        }
    }
]
seriesMACDchart = [
    {
        "type": 'Line',
        "data": macd_fast,
        "options": {
            "color": 'blue',
            "lineWidth": 2
        }
    },
    {
        "type": 'Line',
        "data": macd_slow,
        "options": {
            "color": 'green',
            "lineWidth": 2
        }
    },
    {
        "type": 'Histogram',
        "data": macd_hist,
        "options": {
            "color": 'red',
            "lineWidth": 1
        }
    }
]

# Define the chart options
chart_multipane_options = [
                                    # Candles -1     chart_multipane_options
    {                               
        "width": 1100,
        "height": 600,
        "layout": {
            "background": {
                "type": "solid",
                "color": "white"
            },
            "textColor": "black"
        },
        "grid": {
            "vertLines": {
                "color": "rgba(197, 203, 206, 0.5)"
            },
            "horzLines": {
                "color": "rgba(197, 203, 206, 0.5)"
            }
        },
        "crosshair": {
            "mode": 0
        },
        "priceScale": {
            "borderColor": "rgba(197, 203, 206, 0.8)"
        },
        "timeScale": {
            "timeVisible": True,
            "timeFormat": "%h:%m:%s",
            "timezone": "Asia/Kolkata",
            "borderColor": "rgba(197, 203, 206, 0.8)",
            "barSpacing": 15
        },
        "watermark": {
            "visible": True,
            "fontSize": 24,
            "horzAlign": "center",
            "vertAlign": "center",
            "color": "rgba(171, 71, 188, 0.3)",
            "text": f"{selected_stock} - {interval}",
        }
    },
    # Add the options for the EMA20 line pane      #  Ema -2            chart_multipane_options
    {                              
        "color": '#FFA500',
        "lineWidth": 2,
    },
    # Volume                    # volume -3 
    {
        "width": 1100,
        "height": 100,
        "layout": {
            "background": {
                "type": "solid",
                "color": "transparent"
            },
            "textColor": "black"
        },

        "timeScale": {
            "visible": False
        },
        "watermark": {
            "visible": True,
            "fontSize": 14,
            "horzAlign": "left",
            "vertAlign": "top",
            "color": "rgba(171, 71, 188, 0.7)",
            "text": "Volume"

        }
    },
    # MACD              # MACD 4       chart_multipane_options
    {     
        "width": 1100   ,
        "height": 200,
        "layout": {
            "background": {
                "type": "solid",
                "color": 'white'
            },
            "textColor": "black"
        },
        "timeScale": {
            "visible": False,
        },
        "watermark": {
            "visible": True,
            "fontSize": 14,
            "horzAlign": 'left',
            "vertAlign": 'top',
            "color": 'rgba(171, 71, 188, 0.7)',
            "text": 'MACD',
        }
    }
]

st.subheader("Multipane Chart with overlays")
# Render the candlestick and volume charts
renderLightweightCharts([
    {
        "chart": chart_multipane_options[0],
        "series": series_candlestick_chart + series_ema20_line
    },

    {
        "chart": chart_multipane_options[2],
        "series": series_volume_chart
    },

     {
    "chart": chart_multipane_options[3],
    "series": seriesMACDchart        # MACD three lines overlay on each other
    },        

], "multipane")
freyastreamlit commented 1 year ago

Hi @ajayX1 - could you please attach the CSV files (candle, ema, macd and volume) and I will add an example...

ajayX1 commented 1 year ago

Here is the sample file. I have added more columns than earlier. datetime,open,high,low,close,volume,rvgi1,rvgi2,StochRSI1,StochRSI2,rsi1,rsi2,rsi_ema200,ema20,ema50,ema200,macd_fast,macd_slow,macd_hist datetime,open,high,low,close pane 0, volume mane 0 rvgi1,rvgi2 pane 1 StochRSI1,StochRSI2 pane 2 rsi1,rsi2,rsi_ema200 pane 3 ,macd_fast,macd_slow,macd_hist pane 4 ema20,ema50,ema200 pane0 sample.csv

freyastreamlit commented 1 year ago

Done - have a look on example 'Multipane Chart (intraday) from CSV' MultiPaneChartsFromCSV.py Let me know...

freyastreamlit commented 1 year ago

And BTW, have a look on dataSamples.py so you have a reference how the JSON fields are required

(that is what the .to_)son on pandas df does - I rename the fields accordingly to the requirements)

ajayX1 commented 1 year ago

Very Nice Thanks a lot. By now I was managing by executing a react App to plot chart using native lightweightchart.js That needed two webpage to open. Now I can plot chart on same page.

ajayX1 commented 1 year ago

Is it possible to show chart size 1100. If I make chart wider the price scale hide behind some thing. price scale with "₹" and tags. Histogram is also only green. Below is code how I add "₹" in my reactjs lightweight chart:

const MainChartSeries = chart.addCandlestickSeries({ //--------------------Main Chart upColor: '#26A69A', downColor: '#EF5350', borderVisible: false, // title: 'CandleStick OHLC', data: props.candlestickData, priceFormat: { type: "custom", formatter: (price) => "₹" + Number(price).toFixed(2), }, pane: 0 });

Below how I added color Red and Green in my reactjs chart in volume histogram: ` //----------------- Volume Histogram {{{FOR NOW NOT PLOTTING}}} const volumeSeries = chart.addHistogramSeries({ //--------------------Volume Chart color: ({ up, down }) => up === undefined || up ? 'rgba(0, 150, 136, 0.5)' : 'rgba(255, 82, 82, 0.5)', priceFormat: { type: 'volume', }, priceScaleId: '', scaleMargins: { top: 0.6, bottom: 0.1, }, pane: 1,

});

volumeSeries.setData(props.histogramData.map((v, index) => {                 //--------------------Volume Chart Data  
  const candle = props.candlestickData[index];
  const color = candle && candle.close > candle.open ? 'rgba(0, 150, 136, 0.5)' : 'rgba(255, 82, 82, 0.5)';
  return {
    ...v,
    color,
  };
}));` 
freyastreamlit commented 1 year ago

Hi @ajayX1 - great that you can sod what you want Chart size I guess you can set upCSS on the iframe/div container, and for color - I guess you could disable the:

(or any other related)

Closing this ticket, as this is now out-of-scope for this plugin - all the best

Joe Rosa