Home    /    Blogs    /    Indicator Coding
How to calculate vwap with Python - A step by step complete guide

The Volume-Weighted Average Price (VWAP) is a very famous and actually very useful indicator for intraday traders. Which tells you the price of a particular security, weighted by volume. Most of the intraday traders use VWAP for trade direction confirmation in their trading system.

If you want to calculate with Python code, then below is the required code.

 

1. Setting Up your working Environment

Install the required libraries:

pip install pandas yfinance

In our code we required a pandas dataframe to process the data with column names Open, High, Low, Close, and Volume.

 

2. Code for VWAP

def calculate_vwap(df, time_column='time'):
    """
    Calculate VWAP based on daily sessions
    
    Parameters:
    df: pandas DataFrame with OHLCV data
    time_column: str, name of the time/datetime column (default: 'time')
    
    Returns:
    pandas DataFrame with VWAP column calculated per day
    """
    try:
        df_copy = df.copy()
        
        # Ensure time column is datetime
        if not pd.api.types.is_datetime64_any_dtype(df_copy[time_column]):
            df_copy[time_column] = pd.to_datetime(df_copy[time_column])
        
        # Extract date for grouping (removes time component)
        df_copy['date'] = df_copy[time_column].dt.date
        
        # Function to calculate VWAP for each group (day)
        def calc_daily_vwap(group):
            # Calculate typical price
            group['typical_price'] = (group['High'] + group['Low'] + group['Close']) / 3
            
            # Calculate price * volume
            group['price_volume'] = group['typical_price'] * group['Volume']
            
            # Calculate cumulative values within the day
            group['cum_price_volume'] = group['price_volume'].cumsum()
            group['cum_volume'] = group['Volume'].cumsum()
            
            # Calculate VWAP
            group['VWAP'] = group['cum_price_volume'] / group['cum_volume']
            
            return group
        
        # Apply VWAP calculation to each day
        df_copy = df_copy.groupby('date', group_keys=False).apply(calc_daily_vwap)
        
        # Drop intermediate calculation columns
        drop_columns = ["typical_price", "price_volume", "cum_price_volume", "cum_volume", "date"]
        data = df_copy.drop(columns=drop_columns)
        
        # Reset index to ensure clean DataFrame
        data = data.reset_index(drop=True)
        return data
        
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        print("Error is " + str(e) + " at " + str(exc_tb.tb_lineno))
        return None

 

NOTE: You guys have to pass a pandas dataframe as the df input parameter.

Subscribe to our email list here to get the latest updates first in your inbox.