# How To Make VWAP With Python

In this article, we will build a profitable trading strategy in Python. We will implement the strategy in different market scenarios to draw insight: **How to build a profitable VWAP trading strategy with Python.**

**Related reading:**

**Looking for a good, robust, and profitable trading strategy? (Hundreds in that link)**- ….
**and a few trading strategies for sale** **Many more examples of profitable and robust Python trading strategies**

## Trading and Hypothesis Testing

Scientific knowledge advances upon the idea of hypothesis testing, and we aim to do the same in trading.

It is necessary to test your experiment to know how effective the strategy is. When the Coronavirus came about, there was a race in the pharmaceutical companies to find the vaccine. The success rate was the primary criterion to approve or not the vaccines.

Quantitative trading follows the same principle. Backtesting a trading strategy to know its effectiveness is necessary because its results are unknown beforehand.

The criterion to know if a trading strategy is profitable or not is the total return (but also the risk, ie. volatility). The goal in trading is to find a profitable strategy and know in which market scenario it works and why.

## Volume Weighted Average Price (VWAP)

The Volume Weighted Average Price is a technical indicator to identify the trend, it uses the stock price and the volume for its calculation.

This indicator can be used to estimate long-term trends or short-term trends.

The first step is to calculate ** the Typical Price**:

The second step is to multiply Typical Price by Volume:

Finally, we implement a rolling division between the sum from the last Typical Price Volume k-values and the last Volume k-values:

The term k is a window length, in this example, k=3, but it can be any other value.

Let’s calculate the ** VWAP** from the previous table. The

**for day 1 is (30+28+28.7)/3=28.83, while the**

*Typical Price***is 28.83*100; for the second day, the**

*Typical Price Volume***is (32+32+31.7)=31.57, while the**

*Typical Price***is 31.57*70, etc. To estimate the**

*Typical Price Volume***, we set k = 3 days; therefore, we start from the third row, sum the last three**

*VWAP***values, and divide it by the last three**

*Typical Price Volume***values,**

*Volume***VWAP**=(2883.33+2209.67+2368.00)/(100+70+80)=29.84; for the fourth row, the

**VWAP**is (2209.67+2368.00+2340.00)/(70+80+90), etc.

## Python Example

We need to make a function:

A function is a portion of code that makes a task. It is useful to not repeat over and over the same procedure. The Python function “** sum_2**” takes parameters (a, b, and c), performs operations (d = a + b + c + d) in its body, and returns the desired output.

When we see the value from our previous function, we get 9.

## Python Function to Download Data

This article borrows part of its contents from other articles we have written. In case you have not seen them, please check these articles:

- How I Made a Weighted Moving Average Trading Strategy Using Python
- How To Download Data For Your Trading Strategy From Yahoo!Finance With Python

Let’s first import the libraries:

Now, we will implement the following function:

In the previous image, we create a function ** download_data** with three parameters, the first is the security name

**, the second is the start date**

*stock_name***, and the third is the end date**

*start***. Inside, we have the body that groups all the instructions to get our data**

*end***and**

*stock***. Finally, we have the return component (**

*data***that will give us the data. Then we apply the function**

*return data)***to get our data frame.**

*download_data(“DHR”, ‘2022-01-01’, “2023-06-30”)*## Calculate VWAP Indicator

In this case, we will use the Python library ** ta** that implements multiple technical indicators. To calculate our indicator, we use

**, which has five parameters:**

*ta.volume.VolumeWeightedAveragePrice**high*,

*low*,

*close*,

*volume*, and

*window*; the

*“window*” parameter indicates the number of periods to estimate our VWAP. We need to apply

**to get a pandas series.**

*vwap.volume_weighted_average_price()*When we implement the ** vwap_indicator(result, 30)**, we get a VWAP with a 30-day rolling window to estimate our result. In the last column of the previous image, you can observe a new column VWAP containing values from our indicator.

## Calculate SMA and Plot the Price and our Indicators

The following image shows how to compute a 5-day SMA using the Python packages ** ta**. We create a function to return the values from this indicator:

In the data frame ** result**, a new column SMA reflects this indicator’s value.

## Plotting VWAP, SMA, and the Closing Price

The following chart displays the price alongside our two indicators. The implementation of a 15-day VWAP aims to capture a long-term trend, while the 5-day SMA focuses on a short-term trend.

When we look at the evolution of our previous chart, it becomes evident that the data fluctuates horizontally; with a slight downtrend in the last two months. Furthermore, it tends to reverse direction whenever the closing price significantly deviates from the 15-day VWAP.

It looks like we can implement a strategy that profits from retracement in the stock price.

## Calculate the Buy and Sell Entries (Signals)

In this section, we will introduce our trading strategy based on the following rules:

**Buy:**

- When the Closing Price is lower than both the 15-day VWAP and the 5-day SMA, and the Closing Price is lower than the Closing Price from the last two days.
- Closing Price < 15-day VWAP
- Closing Price < 5-day SMA
- Closing Price < Closing Price from the last two days

**Sell:**

- When the Closing Price is greater than both the 15 days VWAP and the 5 days SMA, and the Closing Price is greater than the Closing Price from the last two days.
- Closing Price > 15-day VWAP
- Closing Price > 5-day SMA
- Closing Price > Closing Price from the last two days

The chart below provides an example of the previous rules.

The subsequent code implements a function, ** calculate_signals**, incorporating the previous buy and sell criteria:

## Profit and Loss Equity Curve

We implement the following code:

We get the following chart:

We can see that while the benchmark (DHR) has a negative total profit and loss, our strategy achieves more than 80% accumulated profit and loss.

**NVDA Analysis**

When we implement the same trading strategy to NVDA, we get the following equity curve:

We see that the stock goes down from around $250 to $120, which is approximately a 50% decline. Later, the stock goes up from around $120 to $430.

When we see the Equity Curve from NVDA, the strategy does not perform well.

The aim of the article is to explain to you how it can be done using Python. To make a profitable and tradable trading strategy you need to backtest a lot more. We leave that to you!