- GuruFinance Insights
- Posts
- I Tested This Strategy on the 100 Largest US Companies - Here Are the Results
I Tested This Strategy on the 100 Largest US Companies - Here Are the Results
Dive into the World of Value Investing with Wharton Online
The Applied Value Investing Certificate program provides a comprehensive 8-week online experience for those looking to implement the same value investing strategies and approaches used by the world’s top investors.
Beyond mastering technical skills from top Wall Street instructors, you'll gain insights from industry leaders like Jeff Gramm, author of The Education of Value Investor, and Howard Marks, Co-Founder of Oaktree Capital.
Plus, enjoy exclusive networking opportunities, LinkedIn groups, and targeted recruitment events with leading firms.
Exciting News: Paid Subscriptions Have Launched! 🚀
On September 1, we officially rolled out our new paid subscription plans at GuruFinance Insights, offering you the chance to take your investing journey to the next level! Whether you're just starting or are a seasoned trader, these plans are packed with exclusive trading strategies, in-depth research paper analysis, ad-free content, monthly AMAsessions, coding tutorials for automating trading strategies, and much more.
Our three tailored plans—Starter Investor, Pro Trader, and Elite Investor—provide a range of valuable tools and personalized support to suit different needs and goals. Don’t miss this opportunity to get real-time trade alerts, access to masterclasses, one-on-one strategy consultations, and be part of our private community group. Click here to explore the plans and see how becoming a premium member can elevate your investment strategy!
Check Out Latest Premium Articles
Imagine a scenario where you have a strategy at your disposal that enables you to pinpoint crucial price levels where major institutional investors might be executing their trades. Such a strategy could significantly enhance your trading approach by providing insights into the movements of the market's most influential players. One tool that stands out in this regard is the Volume Weighted Average Price (VWAP) indicator. This powerful indicator is extensively utilized by traders across the globe to ascertain the average price at which a security has been traded over the course of a trading day. What makes VWAP particularly valuable is its consideration of both the volume and the price of trades, offering a more comprehensive view of market activity.
By integrating the VWAP indicator into your trading strategy, you open up the possibility of aligning your trades with those of the so-called “smart money”.
You missed Amazon. You don't have to again.
Amazon, once a small online bookstore, grew into a global behemoth, transforming industries along the way. Now, imagine yourself at the forefront of the next revolution: AI. In The Motley Fool's latest report, uncover the parallels between Amazon's early trajectory and the current AI revolution. Experts predict one of these AI companies could surpass Amazon's success with market caps nine times larger. Yep, you read that right. Don't let history repeat itself without you. Sign up for Motley Fool Stock Advisor to access the exclusive report.
What is VWAP?
The Volume Weighted Average Price (VWAP) is a sophisticated trading indicator that provides a more nuanced view of a security's average price by incorporating the volume of trades executed at each price level. This makes VWAP distinct from simple moving averages, which only consider price data without accounting for the volume of trades. By integrating both price and volume, VWAP offers a more comprehensive measure of market sentiment and activity.
VWAP is particularly valuable in the realm of intraday trading, where traders seek to make informed decisions based on short-term market movements. It serves as a benchmark that traders use to compare the current price of a security against its average price throughout the trading day. When the current price is above the VWAP, it suggests a bullish sentiment, indicating that the market may be trending upwards. Conversely, if the price is below the VWAP, it indicates a bearish sentiment, suggesting a potential downward trend.
However, the utility of VWAP extends beyond merely identifying market trends. It is also employed to pinpoint potential support and resistance levels within the market.
VWAP Trading Strategy
The strategy that revolves around the Volume Weighted Average Price (VWAP) involves utilizing this particular indicator as a dynamic level of support and resistance within the market. The underlying concept is straightforward yet effective: when the market price of an asset is trading below the VWAP, it is often interpreted as a potential buying opportunity, suggesting that the asset may be undervalued at that moment. Conversely, when the price is trading above the VWAP, it might indicate that the asset is overvalued, presenting a good opportunity to sell or initiate a short position.
To elaborate further, here’s a basic strategy that you can implement using the VWAP as a guiding tool:
Buy Signal: When the price of the asset crosses above the VWAP after having been below it for a period of time, this movement is indicative of a potential upward reversal in the market trend. Such a scenario could present an opportune moment to enter a long position, as it suggests that the buying momentum is gaining strength and the price may continue to rise.
Sell Signal: When the price of a security crosses below the Volume Weighted Average Price (VWAP) after having been above it for a period of time, this movement suggests a potential downward reversal in the market trend. Such a crossover can be interpreted as a bearish signal, indicating that the asset may be losing its upward momentum and could be poised.
The calculus is based on:
Implementing the Strategy on S&P 500 Companies
To thoroughly evaluate the effectiveness of this strategy, I decided to implement it on the 50 largest companies within the S&P 500 index. This selection was made to ensure a diverse representation of industries and market capitalizations, providing a robust testing ground for the strategy. The core of this strategy involves utilizing historical intraday trading.
import yfinance as yf
import pandas as pd
from backtesting import Backtest, Strategy
import openpyxl
# List of top 50 S&P 500 companies by market cap
top_50_sp500 = [
'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'BRK-B', 'TSLA', 'NVDA', 'JPM', 'JNJ',
'V', 'UNH', 'HD', 'PG', 'DIS', 'MA', 'PYPL', 'VZ', 'ADBE', 'NFLX',
'INTC', 'CMCSA', 'KO', 'PFE', 'PEP', 'T', 'XOM', 'CSCO', 'ABT', 'MRK',
'NKE', 'ABBV', 'CRM', 'AVGO', 'MCD', 'QCOM', 'TXN', 'ACN', 'MDT', 'COST',
'NEE', 'DHR', 'WMT', 'AMGN', 'HON', 'IBM', 'GE', 'LOW', 'CAT', 'BA'
]
# Parameters
start_date = '2020-01-01'
end_date = '2023-01-01'
cash = 10000
commission = 0.002
# Function to calculate VWAP
def calculate_vwap(data):
cum_volume = data['Volume'].cumsum()
cum_vwap = (data['Close'] * data['Volume']).cumsum() / cum_volume
return cum_vwap
# Define the VWAP Strategy
class VWAPStrategy(Strategy):
def init(self):
self.vwap = self.I(calculate_vwap, self.data.df)
def next(self):
if self.data.Close[-1] > self.vwap[-1] and self.data.Close[-2] <= self.vwap[-2]:
self.buy()
elif self.data.Close[-1] < self.vwap[-1] and self.data.Close[-2] >= self.vwap[-2]:
self.sell()
# Function to run the backtest for a list of tickers
def run_backtests(tickers, start_date, end_date, cash, commission):
all_metrics = []
for ticker in tickers:
try:
# Fetch historical intraday data
data = yf.download(ticker, start=start_date, end=end_date, interval="1d")
if data.empty:
print(f"No data for {ticker}. Skipping...")
continue
# Ensure there's enough data for the calculation
if len(data) < 2:
print(f"Not enough data for {ticker}. Skipping...")
continue
# Run the backtest
bt = Backtest(data, VWAPStrategy, cash=cash, commission=commission)
stats = bt.run()
# Collect metrics
metrics = {
"Stock": ticker,
"Start": stats['Start'],
"End": stats['End'],
"Duration": stats['Duration'],
"Equity Final [$]": stats['Equity Final [$]'],
"Equity Peak [$]": stats['Equity Peak [$]'],
"Return [%]": stats['Return [%]'],
"Buy & Hold Return [%]": stats['Buy & Hold Return [%]'],
"Max. Drawdown [%]": stats['Max. Drawdown [%]'],
"Avg. Drawdown [%]": stats['Avg. Drawdown [%]'],
"Max. Drawdown Duration": stats['Max. Drawdown Duration'],
"Trades": stats['# Trades'],
"Win Rate [%]": stats['Win Rate [%]'],
"Best Trade [%]": stats['Best Trade [%]'],
"Worst Trade [%]": stats['Worst Trade [%]'],
"Avg. Trade [%]": stats['Avg. Trade [%]'],
"Max. Trade Duration": stats['Max. Trade Duration'],
"Avg. Trade Duration": stats['Avg. Trade Duration'],
"Profit Factor": stats['Profit Factor'],
"Expectancy [%]": stats['Expectancy [%]'],
"Sharpe Ratio": stats['Sharpe Ratio'],
"Sortino Ratio": stats['Sortino Ratio'],
}
all_metrics.append(metrics)
except Exception as e:
print(f"Error processing {ticker}: {e}")
continue
# Convert to DataFrame
metrics_df = pd.DataFrame(all_metrics)
# Save to Excel
metrics_df.to_excel("top_50_sp500_vwap_metrics.xlsx", index=False)
return metrics_df
# Run the backtests
metrics_df = run_backtests(top_50_sp500, start_date, end_date, cash, commission)
# Print the results
print(metrics_df)
Brief Explanation of the Code
The provided code implements a comprehensive trading strategy that leverages the Volume Weighted Average Price (VWAP) indicator to make informed trading decisions. This strategy is designed to analyze and execute trades based on the VWAP, which is a popular technical analysis tool used by traders to assess the average price a security has traded at throughout the day, weighted by volume. Below is an expanded breakdown of the key components of this code:
1. Data Download: The code utilizes the yfinance
library to efficiently download historical intraday trading data for the top 50 companies listed in the S&P 500 index. The data spans a period from January 1, 2020, to January 1, 2023. This extensive dataset provides a robust foundation for analyzing market trends and testing the trading strategy over a significant timeframe.
2. VWAP Calculation: The calculate_vwap
function is a crucial part of the strategy, as it computes the VWAP by taking the cumulative sum of the product of the closing prices and the trading volume, and then dividing it by the cumulative sum of the volume. This calculation results in a price that is weighted by the volume, offering a more accurate reflection of where the majority of trading activity has occurred. The VWAP serves as a benchmark for evaluating the current price levels.
3. VWAP Strategy Implementation: The VWAPStrategy
class encapsulates the core trading logic. Within the __init__
method, the VWAP is calculated for the entire dataset, setting the stage for the strategy's execution. The `next` method is where the strategy actively monitors the market for potential trading signals. It does so by checking for crossovers between the current market price and the VWAP. Specifically, if the current price crosses above the VWAP, the strategy interprets this as a bullish signal and generates a buy order. Conversely, if the price crosses below the VWAP,
Results and Observations
As you can see, there are a few stocks such as Intel Corporation (INTC), Boeing (BA), The Walt Disney Company (DIS), Meta Platforms (META), Salesforce (CRM), and Medtronic (MDT), where the strategy demonstrates significant power and achieves commendable results. The Volume Weighted Average Price (VWAP)-based strategy provided intriguing insights, although the results were not overwhelmingly positive during the initial backtests. The strategy occasionally faced challenges in highly volatile markets or during extended periods of low trading volume, which can distort the VWAP calculation and affect its accuracy. Despite these challenges, the VWAP indicator remains a robust tool for identifying key intraday price levels, offering traders valuable information about the average price at which a stock has traded throughout the day.
This strategy can serve as a foundational baseline for further refinement and testing. By combining it with other technical indicators or specific conditions, traders can filter out false signals and enhance the strategy's effectiveness. The potential for improvement is significant, and with careful adjustments, the strategy can be tailored to better suit various market environments.
In conclusion, while the initial results of the VWAP strategy were mixed, this approach offers a solid foundation for future research and refinement. VWAP is a widely respected indicator, particularly among institutional traders, due to its ability to provide a more comprehensive view of a stock's price action. Aligning your trading strategy with VWAP can help you make more informed and strategic trading decisions. As with any trading strategy, continuous testing and adjustments are essential to adapt to different market conditions and improve overall performance. By remaining flexible and open to modifications, traders can enhance the strategy's robustness and increase their chances of success in the ever-evolving financial markets.