If you are backtesting 5-minute intraday candles across 5 years of historical market data, a single naive iterrows() loop in Pandas can turn a 50-millisecond matrix operation into a 2-minute bottleneck. Worse, subtle logical bugs—like forgetting to reset cumulative VWAP at the start of each trading session or using simple rolling averages instead of Wilder’s smoothing—can completely distort your live trading signals. While building PyQuant Library (an open directory of 126+ production-ready Python scripts for quants, traders, and financial engineers), I standardized the core building blocks of algorithmic trading so they run purely on vectorized pandas, numpy, and scipy without heavy C-compiler wrapper libraries breaking across Python updates. Here are 5 institutional-grade, copy-paste Python scripts you can drop straight into your backtesting or live execution engine today. 1. Wilder’s RMA Supertrend Indicator (Vectorized)Standard libraries like TA-Lib don't include Supertrend out-of-the-box, and naive loops slow down intraday backtesting. Using Wilder's smoothing (ewm(alpha=1/period)) matches exact Supertrend values on TradingView and broker terminals while generating single-candle trend-flip signals. Core Formula:$\text{Basic Upper Band} = \frac{\text{High} + \text{Low}}{2} + (\text{Multiplier} \times \text{ATR})$ $\text{Basic Lower Band} = \frac{\text{High} + \text{Low}}{2} - (\text{Multiplier} \times \text{ATR})$ Pythonimport pandas as pd
import numpy as np
def calculate_supertrend(df, period=10, multiplier=3.0):
df = df.copy()
tr1 = df['High'] - df['Low']
tr2 = (df['High'] - df['Close'].shift(1)).abs()
tr3 = (df['Low'] - df['Close'].shift(1)).abs()
df['TR'] = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
df['ATR'] = df['TR'].ewm(alpha=1/period, adjust=False).mean()
hl2 = (df['High'] + df['Low']) / 2 df['Upper'] = hl2 + (multiplier * df['ATR']) df['Lower'] = hl2 - (multiplier * df['ATR']) df['Trend'] = np.where( df['Close'] > df['Upper'].shift(1), 1, np.where(df['Close'] < df['Lower'].shift(1), -1, np.nan) ) df['Trend'] = df['Trend'].ffill().fillna(1) df['Signal'] = np.where( (df['Trend'] == 1) & (df['Trend'].shift(1) == -1), 1, np.where((df['Trend'] == -1) & (df['Trend'].shift(1) == 1), -1, 0) ) return df - Intraday VWAP with Automatic Daily Session ResetCalculating cumulative Volume Weighted Average Price (VWAP) across multiple days of 1-minute or 5-minute intraday data without resetting at market open distorts the entire curve. This script groups by the session date to reset cumulative volume and typical price automatically at 9:15 AM daily. Core Formula:$\text{Typical Price (TP)} = \frac{\text{High} + \text{Low} + \text{Close}}{3}$ $\text{VWAP} = \frac{\sum (\text{TP} \times \text{Volume})}{\sum \text{Volume}}$ grouped by trading day. Pythonimport pandas as pd import numpy as np
def intraday_vwap(df):
df = df.copy()
df['TP'] = (df['High'] + df['Low'] + df['Close']) / 3.0
df['TPV'] = df['TP'] * df['Volume']
dates = df.index.date
df['VWAP'] = df.groupby(dates)['TPV'].cumsum() / df.groupby(dates)['Volume'].cumsum() df['Above_VWAP'] = np.where(df['Close'] > df['VWAP'], 1, -1) return df.drop(['TP', 'TPV'], axis=1) - European Option Greeks (Delta, Gamma, Theta, Vega) via Black-ScholesThird-party option pricing packages often break on newer Python versions or run slowly on full option chains. This pure NumPy and SciPy implementation computes Call/Put prices and all Option Greeks instantaneously. Pass time to expiry T in annualized years (for example, 7 days to expiry is T = 7 / 365.0). Core Formula:$d_1 = \frac{\ln(S/K) + (r + 0.5\sigma^2)T}{\sigma\sqrt{T}}$ $d_2 = d_1 - \sigma\sqrt{T}$ Pythonimport numpy as np from scipy.stats import norm
def black_scholes_greeks(S, K, T, r, sigma, option_type='call'):
d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
d2 = d1 - sigma * np.sqrt(T)
if option_type == 'call': price = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2) delta = norm.cdf(d1) theta = (- (S * norm.pdf(d1) * sigma) / (2 * np.sqrt(T)) - r * K * np.exp(-r * T) * norm.cdf(d2)) / 365.0 else: price = K * np.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1) delta = norm.cdf(d1) - 1 theta = (- (S * norm.pdf(d1) * sigma) / (2 * np.sqrt(T)) + r * K * np.exp(-r * T) * norm.cdf(-d2)) / 365.0 gamma = norm.pdf(d1) / (S * sigma * np.sqrt(T)) vega = (S * norm.pdf(d1) * np.sqrt(T)) / 100.0 return { 'Price': round(price, 2), 'Delta': round(delta, 4), 'Gamma': round(gamma, 6), 'Theta_Daily': round(theta, 4), 'Vega': round(vega, 4) } ⚡ Test It Live in Your Browser: You don't even need to open an IDE to test Black-Scholes Greeks or ATR Position Sizing. Try our live Interactive Quant Terminal directly on PyQuant Library. 4. Hurst Exponent Market Regime Filter (Mean-Reversion vs. Trend)Applying trend-following indicators to a mean-reverting stock guarantees whipsaw losses. The Hurst Exponent ($H$) mathematically measures the long-term memory of a time series so you can deploy the right strategy per ticker: $H < 0.45$: Mean-Reverting (Use RSI / Bollinger reversals) $0.45 \le H \le 0.55$: Geometric Random Walk $H > 0.55$: Persistent Trend (Use Supertrend / Donchian breakouts) Pythonimport numpy as np
def calculate_hurst_exponent(price_series, max_lag=20):
lags = range(2, max_lag)
tau = [np.sqrt(np.std(np.subtract(price_series[lag:], price_series[:-lag]))) for lag in lags]
poly = np.polyfit(np.log(lags), np.log(tau), 1)
hurst = poly[0] * 2.0
regime = 'MEAN_REVERTING' if hurst < 0.45 else ('TRENDING' if hurst > 0.55 else 'RANDOM_WALK') return {'Hurst_Exponent': round(hurst, 4), 'Market_Regime': regime} - Multi-Asset Portfolio Optimization via Sharpe Ratio MaximizationEqual-weight portfolios ignore asset correlations and covariance risk. This script uses SciPy’s Sequential Least Squares Programming (SLSQP) optimizer to compute the exact portfolio weights that maximize the annualized Sharpe Ratio subject to long-only constraints ($\sum w_i = 1, 0 \le w_i \le 1$). Pythonimport numpy as np import pandas as pd import scipy.optimize as sco import yfinance as yf
def optimize_portfolio(tickers: list, start_date: str, end_date: str, risk_free_rate: float = 0.05):
data = yf.download(tickers, start=start_date, end=end_date, progress=False)['Close']
returns = data.pct_change().dropna()
mean_returns = returns.mean() * 252
cov_matrix = returns.cov() * 252
num_assets = len(tickers) def neg_sharpe_ratio(weights):
p_ret = np.sum(mean_returns * weights)
p_vol = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
sharpe = (p_ret - risk_free_rate) / p_vol
return -sharpe
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
bounds = tuple((0, 1) for _ in range(num_assets))
init_guess = num_assets * [1.0 / num_assets]
opt_results = sco.minimize(
neg_sharpe_ratio, init_guess, method='SLSQP', bounds=bounds, constraints=constraints
)
return {
'optimal_weights': dict(zip(tickers, np.round(opt_results.x, 4))),
'max_sharpe_ratio': round(-opt_results.fun, 4)
}
Example Usage:
print(optimize_portfolio(['RELIANCE.NS', 'TCS.NS', 'HDFCBANK.NS'], '2023-01-01', '2026-01-01'))
Explore All 126+ Quant & Financial Automation ScriptsWhether you are building Nifty/BankNifty Option Chain Max Pain scrapers, 1D Kalman Filters, GARCH(1,1) Volatility models, Commercial Credit Appraisal (DSCR, MPBF, Altman Z-Score), or Zero-Disk Bank Statement Sanitizers, you don't need to write them from scratch. 🌐 Browse the Free Directory & Live Calculators: https://pyquant-library.netlify.app 📦 Download the Complete 125+ Script Engineer ZIP Bundle ($19): Grab the Full Codebase on Gumroad