pythonpython-3.xalgorithmtradingtradingview-api

Most efficient way to calculate VWAP(VOLUME WEIGHTED AVERAGE PRICE) for trading algorithm


I am looking for an efficient VWAP algorithm for a dataframe that contains 5 minute candles data for a stock for an year.

My code:

def calculate_vwap(data):
    data['VWAP'] = data.groupby('date').apply(lambda x: ((x['high'] + x['low'] + x['close']) / 3 * x['volume']).cumsum() / x['volume'].cumsum()).reset_index(level=0, drop=True)
    return data['VWAP']

The output of my code does not match tradingview VWAP values. Link to the sample data - https://drive.google.com/file/d/12oDiWe9HWQDZEvGmQAqcznklT8NBObGQ/view?usp=sharing Sample:

stock dataframe


Solution

  • After doing some research I found out that some trading platforms use this average price - (high+low+close)/3 and some use (high+low)/2 for arriving at VWAP values.

    And also for the VWAP calculation the cumulataive volume and cumulative (priceXvolume) is calculated from first candle of the day. This lead me to modify my codes like this and it worked now -

    for ticker in Angel_Hist_Data5Min:
    
    Angel_Hist_Data5Min[ticker]["AvgP"] = ((Angel_Hist_Data5Min[ticker]["high"]+Angel_Hist_Data5Min[ticker]["low"]+Angel_Hist_Data5Min[ticker]["close"])/3)
    Angel_Hist_Data5Min[ticker]["PV"] = Angel_Hist_Data5Min[ticker]["AvgP"]*Angel_Hist_Data5Min[ticker]["volume"]
    Angel_Hist_Data5Min[ticker]['CumPV'] = Angel_Hist_Data5Min[ticker].groupby(Angel_Hist_Data5Min[ticker]['date'].dt.date)['PV'].cumsum()
    Angel_Hist_Data5Min[ticker]["VWAP_hlc"] = Angel_Hist_Data5Min[ticker]["CumPV"]/Angel_Hist_Data5Min[ticker]["CumVolume"] 
    
    Angel_Hist_Data5Min[ticker]["AvgP_hl"] = ((Angel_Hist_Data5Min[ticker]["high"]+Angel_Hist_Data5Min[ticker]["low"])/2)
    Angel_Hist_Data5Min[ticker]["PV_hl"] = Angel_Hist_Data5Min[ticker]["AvgP_hl"]*Angel_Hist_Data5Min[ticker]["volume"]  
    Angel_Hist_Data5Min[ticker]['CumPV_hl'] = Angel_Hist_Data5Min[ticker].groupby(Angel_Hist_Data5Min[ticker]['date'].dt.date)['PV_hl'].cumsum()
    Angel_Hist_Data5Min[ticker]["VWAP_hl"] = Angel_Hist_Data5Min[ticker]["CumPV_hl"]/Angel_Hist_Data5Min[ticker]["CumVolume"]
    

    I am calculating two VWAPs now and this helps to match with all the trading platforms data.