Building a VWAP Indicator in Python

The Volume Weighted Average Price (VWAP) is a popular trading indicator used by traders and investors to assess the average price of a security based on both its price and trading volume. In this article, we’ll walk through how to code a VWAP indicator in Python using AAPL stock data with a 15-minute timeframe. We’ll also implement a check to alert us when the stock price crosses above or below the VWAP.
Step 1: Fetching Stock Data from yfinance
We’ll use yfinance to fetch AAPL stock data with a 15-minute timeframe. Import the required libraries and fetch the data:
import yfinance as yf
# Fetch AAPL stock data with a 15-minute timeframe
aapl = yf.Ticker("AAPL")
data = aapl.history(period="60d", interval="15m")Step 2: Calculating VWAP
To calculate the VWAP, we’ll use the following formula:
VWAP = Σ(Pi * Vi) / ΣViWhere:
Piis the average price at each data point.Viis the corresponding trading volume at each data point.
Let’s implement this calculation:
# Calculate VWAP
data['VWAP'] = (((data['High'] + data['Low'] + data['Close']) / 3) * data['Volume']).cumsum() / data['Volume'].cumsum()In the above code, we use the cumsum() method to perform cumulative summation on the data. Let’s break down how this calculation works:
cumsum()stands for "cumulative sum." It's a pandas DataFrame method that calculates the cumulative sum of values along a specified axis, typically used along columns (axis 0) or rows (axis 1).((data['High'] + data['Low'] + data['Close']) / 3) * data['Volume']calculates the cumulative sum of the product of the average price (calculated as the average of high, low, and close prices) and trading volumes. This represents the cumulative sum of the total traded value, a crucial component in VWAP calculation.data['Volume']calculates the cumulative sum of trading volumes. This cumulative sum of trading volumes serves as the denominator in the VWAP formula.- To obtain the VWAP at each data point, we divide the cumulative sum of the total traded value by the cumulative sum of trading volumes. This calculation results in the VWAP values stored in the ‘VWAP’ column of the DataFrame.
The cumsum() method is a powerful tool for performing cumulative operations on data, making it particularly useful for financial and time-series data analysis. Read more about it here: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html
Step 3: Detecting Crossings and Printing Alerts
We want to check if the stock price crosses above or below the VWAP in the last two rows of the data. We’ll implement this logic:
# Check for crossovers in the last two rows
last_row = data.iloc[-1]
second_last_row = data.iloc[-2]
if second_last_row['Close'] > second_last_row['VWAP'] and last_row['Close'] < last_row['VWAP']:
print('Price Cross Below VWAP')
elif second_last_row['Close'] < second_last_row['VWAP'] and last_row['Close'] > last_row['VWAP']:
print('Price Cross Above VWAP')
else:
print('No Crossover')Here we are just printing whether or not a cross over happened, but there are many things we can do with this. We can send an email or a text message to alert ourselves if this happened, or we can implement this logic as part of a trading bot. Those are just two suggestions, but you get the idea.
Conclusion
In this article, we’ve coded a VWAP indicator in Python using AAPL stock data with a 15-minute timeframe. We’ve also implemented a check to alert us when the stock price crosses above or below the VWAP. This combination of technical analysis and automation can be a powerful tool for traders and investors.
Feel free to adapt this code for other stocks, timeframes, or additional trading strategies.
Hope you learned something





