How to send mplfinance candle stick chart to frontend using flask?

Viewed 388

I'm working on the flask project where I use the mplfinance library to create candlestick charts and I need to pass this chart to the frontend.

@app.route('/chartdata', methods =['POST'])
def chart_data():
    if request.method == 'POST':
        
        body = request.json
        df = pd.read_csv('test_data.csv',index_col=0,parse_dates=True)
        df.index.name = 'Date'
        mplfinance.plot(df, type = 'candle',style ='yahoo',savefig ="sample.png")
        
        return "image to transferred" 

I tried this approach of saving the image and passing it to the front but here I can't avoid chart plot opening, Does anyone knows a better way to transfer these charts to the frontend Html page in this flask project

1 Answers

You can save your figure to a io.BytesIO object and send it to the frontend, like here https://mellowd.dev/python/using-io-bytesio/

mplfinance.plot(...) has a savefig parameter for that, see https://github.com/matplotlib/mplfinance/blob/master/src/mplfinance/plotting.py#L171

Something like below, needs to be tested, as mplfinance.plot() does not have a keyword for image format.

import io

@app.route('/chartdata', methods =['POST'])
def chart_data():
    if request.method == 'POST':
        
        body = request.json
        df = pd.read_csv('test_data.csv',index_col=0,parse_dates=True)
        df.index.name = 'Date'
        b = io.BytesIO()
        mplfinance.plot(df, type = 'candle',style ='yahoo', savefig=b)
        return b 
Related