# VWAP Calculation in Python with GroupBy and Apply Functions

In the world of financial markets, the Volume-Weighted Average Price (VWAP) holds significant importance for traders and investors. If you’re eager to explore what is VWAP and how to calculate VWAP using the power of `groupby` and `apply` functions, you’ve come to the right place. In this article, we will dive into the method of calculating VWAP, using the group by and apply techniques in Python and implement a few examples after which you will have a better understanding of its working.

## Understanding the Concept of VWAP

The Volume Weighted Average Price (VWAP) is a crucial trading indicator in financial markets, providing the average price at which a commodity has been traded over a specific time period. It’s calculated using the formula VWAP = (Cumulative Price * Volume) / Cumulative Volume. In Python, we can calculate VWAP using the groupby and apply functions. The groupby function groups data according to a specified column (like date), and the apply function applies a custom formula (like VWAP) to the grouped data. This method allows for the calculation of VWAP for single or multiplegroups, providing a comprehensive understanding of this important financial indicator.

VWAP is an acronym for Volume Weighted Average Price. It is a trading indicator that determines, taking into consideration the volume of trading at each price level, the average price at which level the average price at which a specific item(such as a stock, commodity, or cryptocurrency) has been traded over a specified time period. So, if the VWAP of a commodity rises, it signals traders to either buy or hold the commodity. Conversely, if the VWAP decreases, it’s a cue to sell the commodity or hold it until the VWAP ascends again.

The VWAP formula is: VWAP = (Cumulative Price * Volume) / Cumulative Volume

Let’s understand how to use VWAP with a simple example. Suppose you have the following price and volume data for stock A:

• Step 1: Calculate the cumulative volume and the product of price multiplied by volume for each data point and for your understanding write it down in a new column.
• Step 2: Use the cumulative sum of the product of price multiplied by volume and the cumulative sum of the volume and apply the VWAP formula to calculate the VWAP.
• Here, VWAP = (Cumulative Price * Volume) / Cumulative Volume
• VWAP = (\$1,000 + \$1,800 + \$3,000) / 450
• VWAP = \$5,800 / 450 ≈ \$12.89

This was a simple pen and paper example of how to calculate VWAP, Now let’s introduce Python and Pandas library to calculate VWAP for the given data.

## Computation of VWAP for a Single Group

Let’s get started by importing the `pandas` library and defining a dictionary called data which contains the price and volume data. The Price key maps to a list of price values [10.5, 11.2, 10.8, 11.5], and the Volume key maps to a list of corresponding volume values [100, 150, 200, 120]

```import pandas as pd

# Create a DataFrame with price and volume data
data = {'Price': [10.5, 11.2, 10.8, 11.5],
'Volume': [100, 150, 200, 120]}
df = pd.DataFrame(data)

df['Cumulative_Price_Volume'] = (df['Price'] * df['Volume']).cumsum()
df['Cumulative_Volume'] = df['Volume'].cumsum()
df['VWAP'] = df['Cumulative_Price_Volume'] / df['Cumulative_Volume']
print(df)
```

Here, a new column named ‘VWAP’ is added to our DataFrame `df`. The calculation `df['Price'] * df['Volume'] / df['Volume'].sum()` is performed, where each price is multiplied by its corresponding volume, and the resulting values are divided by the sum of all volumes. The result is assigned to the ‘VWAP’ column.

Output:

The output contains the VWAP of the individual rows of the data frame. The final VWAP value taken for the given stock data will be (using only 3 significant digits): `1.84+2.94+3.78+2.42 = 10.98`

Now let’s take more realistic data and introduce `groupby` and `apply`.

## Computation of VWAP for Multiple Groups Using GroupBy

The data for which VWAP is calculated is generally not as simple as we took in the last example. Generally, data includes the time/date when the volume of the stock had a given price. Let’s say you are given a large dataset and you need to calculate VWAP according to the date, this means the cumulative volume will be taken for only a particular date.

We can use `groupby()` function to group the data according to the column provided as the parameter and `apply()` function will help us apply our custom formula (here VWAP) to the grouped data. Let’s understand by an example:

```import pandas as pd

def calculate_vwap(group):
print(group)
vwap = (group['Price'] * group['Volume']).cumsum() / group['Volume'].cumsum()
group['VWAP'] = vwap
return group

```

Let’s start with importing the` pandas` module and defining our function `calculate_vwap(group)` which calculates the VWAP of the grouped data frame created by the `groupby()` function.

```data = {'Price': [10.5, 11.2, 10.8, 11.5, 12.2, 12.8],
'Volume': [100, 150, 200, 120, 180, 220],
'Group': ['A', 'A', 'B', 'B', 'A', 'B']}
df = pd.DataFrame(data)
```

After that let’s initialize our data. Our data contains 2 groups A and B, These groups can be anything like dates, group names, etc. We will then convert the dictionary to a pandas data frame to calculate VWAP.

```df = df.groupby('Group').apply(calculate_vwap)

print(df)
```

Finally, we will pass our column name ‘Group’ to the function `groupby()` and after that, we pass our custom function calculate_vwap to apply() which will pass the grouped data frame to our function to calculate Groupwise VWAP.

Output:

You can see how `groupby()` sent rows grouped by the ‘Group’ column, the output contains cumulative VWAP of the group elements, which means the VWAP of the last element sums up the VWAP of the entire group. So for our example VWAP of group A ≈ 11.455 and the VWAP of group B ≈ 11.770

## Summary

VWAP is a powerful tool that helps traders assess the average price for executing large orders without causing market disruption. It’s a vital indicator in the financial world, providing insights into market trends and trading opportunities.

VWAP is given by VWAP = (Cumulative Price * Volume) / Cumulative Volume

In this article, we explored how to calculate VWAP (Volume Weighted Average Price) using `groupby()` and `apply()` in Python using a simple and a relatively more practical example, providing a good understanding of this important financial indicator. How do you plan to apply VWAP in your trading strategies?