pythoncandlestick-chart

Python: Add vwap to candlestick chart


I have tried to figure this out but unable to come up with an idea. I'm plotting OHlC candlestick using plotly. I also have vwap calculated on the same csv. How do I plot the vwap on the same graph as the candlestick chart like

as shown here

Is there any resources, I can check?


Solution

  • To calculate the average price of the trading volume load, I used the following page as a reference. The mpf library can be found here and the instructions for adding plots can be found here.

    import pandas as pd
    import numpy as np
    import yfinance as yf
    import mplfinance as mpf
    
    df = yf.download("AAPL", start="2021-01-01", end="2021-07-01")
    
    v = df['Volume'].values
    tp = (df['Low'] + df['Close'] + df['High']).div(3).values
    df = df.assign(vwap=(tp * v).cumsum() / v.cumsum())
    
    adp = mpf.make_addplot(df['vwap'], type='line')
    mpf.plot(df, figratio=(8,4), type='candle', addplot=adp, volume=True, style='yahoo')
    

    enter image description here

    plotly

    import pandas as pd
    import numpy as np
    import yfinance as yf
    import plotly.graph_objects as go
    
    df = yf.download("AAPL", start="2021-01-01", end="2021-07-01")
    
    v = df['Volume'].values
    tp = (df['Low'] + df['Close'] + df['High']).div(3).values
    df = df.assign(vwap=(tp * v).cumsum() / v.cumsum())
    
    
    fig = go.Figure(data=[go.Candlestick(x=df.index,
                    open=df['Open'],
                    high=df['High'],
                    low=df['Low'],
                    close=df['Close'],name='AAPL')])
    
    fig.add_trace(go.Scatter(
        x=df.index,
        y=df['vwap'],
        mode='lines',
        name='vwap', 
        line=dict(color='royalblue',width=2)
    ))
    
    fig.update_layout(
        height=600
    )
    fig.show()
    

    enter image description here