DEV Community

ayushman4you-ctrl
ayushman4you-ctrl

Posted on

How to Calculate Vectorized Supertrend & Intraday VWAP in Python (Plus 125+ Free Quant Scripts)

When backtesting algorithmic trading strategies or building financial models in Python, the biggest bottleneck is almost always slow, iterative for loops over Pandas DataFrames.

Whether you are running an intraday strategy on index options or scanning hundreds of equities, vectorizing your technical indicators using pandas and numpy can speed up execution by 50x to 100x.

To save developers and quants from rewriting boilerplate code, I built PyQuant Library — a free, open-access collection of 125+ production-ready, vectorized Python scripts with an embedded browser sandbox.

Here is a quick look at how we handle two classic institutional indicators—Intraday VWAP (with daily session resets) and Supertrend—using clean, vectorized Python.


1. Intraday VWAP with Automatic Daily Session Reset

Standard cumulative VWAP calculations break on multi-day intraday data (like 5-minute candles) unless you group by the trading session date. Here is the clean vectorized way to do it:


python
import pandas as pd
import numpy as np

def calculate_intraday_vwap(df: pd.DataFrame) -> pd.DataFrame:
    """
    Expects a DataFrame with DatetimeIndex and 'High', 'Low', 'Close', 'Volume' columns.
    Resets calculation automatically at the start of each new trading day.
    """
    df = df.copy()

    # Calculate Typical Price
    df['Typical_Price'] = (df['High'] + df['Low'] + df['Close']) / 3
    df['TP_Volume'] = df['Typical_Price'] * df['Volume']

    # Group by trading date for session reset
    session_date = df.index.date
    df['Cum_TP_Vol'] = df.groupby(session_date)['TP_Volume'].cumsum()
    df['Cum_Vol'] = df.groupby(session_date)['Volume'].cumsum()

    df['VWAP'] = df['Cum_TP_Vol'] / np.where(df['Cum_Vol'] == 0, np.nan, df['Cum_Vol'])

    return df.drop(columns=['Typical_Price', 'TP_Volume', 'Cum_TP_Vol', 'Cum_Vol'])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)