Lesson Overview

Welcome to our final lesson in this course, Explorer! In this lesson, we will delve into the concept and calculation of Volume Weighted Average Price (VWAP) specifically for Tesla ($TSLA) stock data using Pandas. VWAP is a crucial indicator in trading that helps by providing the average price a security has traded at during the day, weighted by volume. By the end of this lesson, you'll be able to calculate VWAP and visualize it alongside the closing prices of Tesla stock data.

Introduction to VWAP
Loading and Preprocessing Tesla Stock Data

Let's start by importing the necessary libraries and loading the Tesla ($TSLA) stock data. We'll use the load_dataset function from the datasets library.

import pandas as pd
import numpy as np
from datasets import load_dataset

# Load Tesla dataset
dataset = load_dataset('codesignal/tsla-historic-prices')
tesla_df = pd.DataFrame(dataset['train'])

Next, we'll preprocess the data by converting the 'Date' column to datetime format and setting it as the index.

# Convert Date column to datetime format and set as index
tesla_df['Date'] = pd.to_datetime(tesla_df['Date'])
tesla_df.set_index('Date', inplace=True)

For better visualization, we'll filter the data to focus on the year 2018.

# Filter data for the year 2018
tesla_df_small = tesla_df.loc['2018'].copy()
Calculating the VWAP

Now that we have our data preprocessed, we can calculate the VWAP. We'll use the cumulative sum (the running total, where each value is added to the sum of previous values) of the product of volume and close price and then divide it by the cumulative sum of the volume.

# Calculate VWAP
tesla_df_small['VWAP'] = (np.cumsum(tesla_df_small['Volume'] * tesla_df_small['Close']) / 
                          np.cumsum(tesla_df_small['Volume']))
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal