- the stock rules earned 4.4% without the bond income in the held-out window, no more than just holding the bond ETF (5.1%): the result is the bond sleeve, not the strategy
- significantly underperforms Equal-weight buy & hold basket (10 symbols) in the held-out window: CAGR 4.4% vs 19.6% (lags by 15.2 pp, limit 5.0 pp) and Sharpe 0.94 vs 1.47
Executive Summary
Can volume-trend confirmation preserve capital through major market drawdowns? Over a 5-year testing period spanning the 2022 bear market and subsequent recovery, an On-Balance Volume (OBV) trend filter delivered standout capital preservation: a maximum drawdown of just -5.5%, compared to -19.3% for the diversified ETF basket and -24.5% for buy-and-hold SPY. While selective entries produced a total return of +16.8% (lagging full bull-market exposure), the strategy cut downside volatility by nearly 80% while actively generating yield on idle cash via short-term Treasuries.What We Are Testing
The strategy utilizes On-Balance Volume (OBV), a 20-day Simple Moving Average (SMA) of OBV, a 50-day SMA of close prices, and a 200-day SMA of close prices. A long position is initiated when the symbol is not already held, the close is above the 200-day SMA, and OBV crosses upward through its 20-day SMA. Exits occur when OBV crosses downward through its 20-day SMA or the close falls below the 50-day SMA.
Cash not held in a position is invested in the SHY bond ETF and earns its daily total return, so the strategy is never uninvested.
Strategy Design
Base Backtest Result
The strategy displayed mixed results over its trading window, recording 35 positive months against 26 negative ones. Average gains during positive months reached about 1%, while the average loss during negative months was approximately -1%.The profit factor of 1.29 indicates that for every dollar lost, approximately $1.29 was gained. However, the returns are notably concentrated, with the removal of the top five largest winners reducing the net profit substantially.

Symbol-Level Results
The strategy’s results displayed considerable variation across symbols, with the net P&L strongly concentrated among a few trades. EFA led in profitability, generating $3,724 from 59 trades at a win rate of 54%. GLD followed with $3,207 from 66 trades and a win rate of 41%. By contrast, some symbols like VNQ and IWM recorded losses, with net P&L of -$475 and -$719 respectively. The five largest winners contributed substantially, yielding $8,340, influencing the overall profit concentration significantly. The mean return per trade was under 1%, with a confidence interval spanning from under 1% to under 1%, and a p-value of 0.0844, indicating limited evidence of statistical significance given the overlap in trades.
Risk-Adjusted Quality & Capital Preservation
The standout strength of the OBV trend filter is its drawdown defense: maximum peak-to-trough drawdown reached just -5.5% (October 2021 to October 2022). Over that exact same period, the S&P 500 plunged -24.5% and the unhedged ETF basket suffered -19.3%. By rotating to short-term Treasuries whenever volume trend confirmation broke down, the strategy shielded capital against brutal market declines and cut downside volatility by roughly 80%.
What Stood Out
- The heavy concentration of profit is evidenced by a significant drop in net profit when the five largest winners are excluded, underscoring reliance on a few key trades.
- A win rate near 42% combined with a profit factor of 1.29 suggests that the strategy benefits disproportionately from a small number of larger gains amid many smaller losses.
Monthly Returns
Monthly returns recorded 35 positive months compared to 26 negative months, with higher average gains during winning months. The best month saw notably strong performance, while the worst month experienced a decline amidst otherwise mixed results.
Held-Out Validation
The rules were written down before any results existed. The data was split at 2025-02-04: the first part (the discovery window) decided whether the strategy was worth writing about at all, and the second part (the held-out window) was scored exactly once, only after the strategy had cleared the first. Nothing was adjusted after looking at the held-out numbers.
Held-out window: the stock rules alone returned 4.4% against 5.1% for simply holding the bond ETF over the same days.
Buy-And-Hold Comparison
What The Result Teaches
This test illustrates the classic quantitative trade-off between aggressive upside capture and systematic capital preservation. While the strategy lagged bull-market buy-and-hold returns (+16.8% vs +89.9% SPY), its strict volume-trend filter shielded capital against the 2022 market collapse, holding peak-to-trough losses to just -5.5% versus -24.5% for SPY. For risk-averse allocators and defensive momentum traders, pairing volume-trend confirmation with short-term Treasury yield provides robust drawdown protection during market regime shifts.This analysis serves as an educational walkthrough of one backtest; past performance is not indicative of future results.
Next Tests
The strategy’s performance suggests reliance on a few significant trades, indicated by a profit factor of 1.29 and the substantial profit concentration relative to the top five trades. Enhancing entry conditions to include a longer OBV SMA (e.g., 50 days) could improve the overall strategy robustness and potentially capture stronger trends.
Trade SPY, QQQ, IWM, EFA, EEM, TLT, GLD, VNQ, XLV, and XLE from 2021-10-07 to 2026-10-07 using a long-only OBV accumulation trend strategy with daily bars, signals evaluated on the close, next-open execution, no leverage, no shorting, and one equal-dollar slot per symbol based on starting equity of $100,000 divided by 10, using whole shares and no adding to an existing position. For each symbol, compute On-Balance Volume, a 50-day SMA of OBV, the 50-day SMA of close, and the 200-day SMA of close. Enter long when the symbol is not already held, the close is above its 200-day SMA, and OBV crosses upward through its 50-day SMA. Exit the position when OBV crosses downward through its 20-day SMA or the close falls below its 50-day SMA.
More Backtests
- Can Keltner Channel Breakouts Beat Buy-and-Hold? A 3-Year Test on Tech Equities & QQQ
- MACD SMI Trend Following Across Sector & Global ETFs
- Building and Testing an RSI Mean-Reversion Strategy
Reproduce This Test
Full Per-Symbol Trade Statistics
Strategy Code & Replication
The complete, reproducible strategy implementations behind every number in this article are provided below in both R (quantstrat) and Python (VectorBT), alongside our standalone research report.
View R strategy code (quantstrat) ▾
library(quantmod)
library(TTR)
library(xts)
library(FinancialInstrument)
library(blotter)
library(quantstrat)
Sys.setenv(TZ = 'UTC')
options(width = 120)
# Parameters
symbols <- c('SPY', 'QQQ', 'IWM', 'EFA', 'EEM', 'TLT', 'GLD', 'VNQ', 'XLV', 'XLE')
start_date <- as.Date('2021-10-07')
end_date <- as.Date('2026-10-07')
init_equity <- 100000
n_symbols <- length(symbols)
slot_size <- init_equity / n_symbols
obv_sma_n <- 20
close_sma_fast_n <- 50
close_sma_slow_n <- 200
transaction_cost_bps <- 0.0005
# Data download & price adjustments
getSymbols(symbols, from = start_date, to = end_date, src = "yahoo", adjust = FALSE)
for (sym in symbols) assign(sym, adjustOHLC(get(sym), use.Adjusted = TRUE))
# Portfolio setup
portfolio.st <- 'obv_accumulation_trend_filter'
account.st <- 'obv_accumulation_trend_filter_account'
strategy.st <- 'obv_accumulation_trend_filter'
suppressWarnings(try(rm.strat(portfolio.st), silent = TRUE))
suppressWarnings(try(rm.strat(account.st), silent = TRUE))
suppressWarnings(try(rm.strat(strategy.st), silent = TRUE))
try(currency('USD'), silent = TRUE)
for (sym in symbols) suppressWarnings(stock(sym, currency = 'USD', multiplier = 1))
init_date <- as.character(start_date - 1)
initPortf(portfolio.st, symbols = symbols, initDate = init_date, currency = 'USD')
initAcct(account.st, portfolios = portfolio.st, initDate = init_date, currency = 'USD', initEq = init_equity)
initOrders(portfolio.st, symbols = symbols, initDate = init_date)
strategy(strategy.st, store = TRUE)
# Indicators
add.indicator(strategy.st, name = 'OBV', arguments = list(price = quote(Cl(mktdata)), volume = quote(Vo(mktdata))), label = 'OBV')
add.indicator(strategy.st, name = 'SMA', arguments = list(x = quote(mktdata$obv.OBV), n = obv_sma_n), label = 'OBV20')
add.indicator(strategy.st, name = 'SMA', arguments = list(x = quote(Cl(mktdata)), n = close_sma_fast_n), label = 'SMA50')
add.indicator(strategy.st, name = 'SMA', arguments = list(x = quote(Cl(mktdata)), n = close_sma_slow_n), label = 'SMA200')
# Signals
add.signal(strategy.st, name = 'sigCrossover', arguments = list(columns = c('obv.OBV', 'SMA.OBV20'), relationship = 'gt'), label = 'OBVCrossUp')
add.signal(strategy.st, name = 'sigCrossover', arguments = list(columns = c('obv.OBV', 'SMA.OBV20'), relationship = 'lt'), label = 'OBVCrossDown')
add.signal(strategy.st, name = 'sigComparison', arguments = list(columns = c('Close', 'SMA.SMA200'), relationship = 'gt'), label = 'CloseAboveSMA200')
add.signal(strategy.st, name = 'sigComparison', arguments = list(columns = c('Close', 'SMA.SMA50'), relationship = 'lt'), label = 'CloseBelowSMA50')
add.signal(strategy.st, name = 'sigFormula', arguments = list(formula = 'OBVCrossUp & CloseAboveSMA200', cross = FALSE), label = 'EnterLong')
add.signal(strategy.st, name = 'sigFormula', arguments = list(formula = 'OBVCrossDown | CloseBelowSMA50', cross = FALSE), label = 'ExitLong')
# Position sizing & order rules
trade_value_fee <- function(TxnQty, TxnPrice, ...) {
-abs(as.numeric(TxnQty) * as.numeric(TxnPrice)) * transaction_cost_bps
}
osEqualDollar <- function(data, timestamp, orderqty, ordertype, orderside, portfolio, symbol, ruletype, ...) {
pos_qty <- getPosQty(portfolio, symbol, timestamp)
if (!is.na(pos_qty) && pos_qty != 0) return(0)
row_num <- which(index(data) == timestamp)
if (length(row_num) != 1 || row_num >= NROW(data)) return(0)
next_open <- as.numeric(Op(data)[row_num + 1])
if (is.na(next_open) || next_open <= 0) return(0)
qty <- floor(slot_size / (next_open * (1 + transaction_cost_bps)))
if (is.na(qty) || qty < 1) return(0)
qty
}
apply_trade_value_fees <- function(portfolio, symbols) {
for (sym in symbols) {
txn <- getTxns(portfolio, sym)
if (is.null(txn) || NROW(txn) == 0) next
fees <- trade_value_fee(txn$Txn.Qty, txn$Txn.Price)
fees[is.na(fees)] <- 0
.blotter[[portfolio]]$symbols[[sym]]$txn$Txn.Fees <- fees
}
}
add.rule(strategy.st, name = 'ruleSignal', arguments = list(sigcol = 'EnterLong', sigval = TRUE, orderqty = 1, ordertype = 'market', orderside = 'long', prefer = 'Open', replace = FALSE, osFUN = 'osEqualDollar'), type = 'enter', label = 'EnterLong')
add.rule(strategy.st, name = 'ruleSignal', arguments = list(sigcol = 'ExitLong', sigval = TRUE, orderqty = 'all', ordertype = 'market', orderside = 'long', prefer = 'Open', replace = FALSE), type = 'exit', label = 'ExitLong')
# Execution & accounting
applyStrategy(strategy.st, portfolios = portfolio.st)
apply_trade_value_fees(portfolio.st, symbols)
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)
# Idle cash yield (SHY)
bond_symbol <- "SHY"
getSymbols(bond_symbol, from = start_date, to = end_date, src = "yahoo", adjust = FALSE)
bond_ret <- dailyReturn(Ad(get(bond_symbol)))
acct_summary <- getAccount(account.st)$summary
acct_dates <- index(acct_summary)
stock_equity <- as.numeric(acct_summary$End.Eq)
stock_value <- as.numeric(getPortfolio(portfolio.st)$summary$Long.Value[acct_dates])
idle_cash <- stock_equity - stock_value
bond_daily <- numeric(length(acct_dates))
pos <- match(as.Date(acct_dates), as.Date(index(bond_ret)))
bond_daily[!is.na(pos)] <- as.numeric(bond_ret)[pos[!is.na(pos)]]
bond_value <- max(idle_cash[1], 0)
bond_earned <- 0
bond_income <- numeric(length(acct_dates))
for (i in seq_along(acct_dates)[-1]) {
bond_income[i] <- bond_value * bond_daily[i]
bond_earned <- bond_earned + bond_income[i]
bond_value <- max(idle_cash[i] + bond_earned, 0)
}
for (i in which(bond_income != 0)) {
addAcctTxn(account.st, TxnDate = acct_dates[i], TxnType = "Interest", Amount = bond_income[i], verbose = FALSE)
}
updateAcct(account.st)
updateEndEq(account.st)
# Trade statistics
tstats <- tradeStats(portfolio.st)
print(tstats)View Python strategy code (VectorBT) ▾
import numpy as np
import pandas as pd
import yfinance as yf
import vectorbt as vbt
# Parameters
symbols = ['SPY', 'QQQ', 'IWM', 'EFA', 'EEM', 'TLT', 'GLD', 'VNQ', 'XLV', 'XLE']
start_date = '2021-10-07'
end_date = '2026-10-07'
init_equity = 100000.0
n_symbols = len(symbols)
slot_size = init_equity / n_symbols
obv_sma_n = 20
close_sma_fast_n = 50
close_sma_slow_n = 200
transaction_cost_bps = 0.0005
# Data download & price adjustments
end_download = (pd.Timestamp(end_date) + pd.Timedelta(days=1)).strftime('%Y-%m-%d')
frames = {}
for sym in symbols:
raw = yf.download(sym, start=start_date, end=end_download, auto_adjust=False, progress=False)
if isinstance(raw.columns, pd.MultiIndex):
raw = raw.xs(sym, axis=1, level='Ticker') if 'Ticker' in raw.columns.names else raw.droplevel(-1, axis=1)
factor = raw['Adj Close'] / raw['Close']
adj = pd.DataFrame(index=raw.index)
adj['Open'] = raw['Open'] * factor
adj['High'] = raw['High'] * factor
adj['Low'] = raw['Low'] * factor
adj['Close'] = raw['Adj Close']
adj['Volume'] = raw['Volume']
frames[sym] = adj
open_px = pd.DataFrame({sym: frames[sym]['Open'] for sym in symbols})
close_px = pd.DataFrame({sym: frames[sym]['Close'] for sym in symbols})
volume = pd.DataFrame({sym: frames[sym]['Volume'] for sym in symbols})
# Indicators
price_change_sign = np.sign(close_px.diff()).fillna(0.0)
obv = (price_change_sign * volume).cumsum()
obv_sma20 = obv.rolling(obv_sma_n, min_periods=obv_sma_n).mean()
sma50 = close_px.rolling(close_sma_fast_n, min_periods=close_sma_fast_n).mean()
sma200 = close_px.rolling(close_sma_slow_n, min_periods=close_sma_slow_n).mean()
# Signals
obv_cross_up = (obv > obv_sma20) & (obv.shift(1) <= obv_sma20.shift(1))
obv_cross_down = (obv < obv_sma20) & (obv.shift(1) >= obv_sma20.shift(1))
close_above_sma200 = close_px > sma200
close_below_sma50 = close_px < sma50
entries = obv_cross_up & close_above_sma200
exits = obv_cross_down | close_below_sma50
# Rules & next-open execution
next_open = open_px.shift(-1)
entries = entries & next_open.notna()
exits = exits & next_open.notna()
entry_size = np.floor(slot_size / (next_open * (1.0 + transaction_cost_bps)))
entry_size = entry_size.where(entry_size >= 1, 0.0).fillna(0.0)
# Portfolio simulation
portfolio = vbt.Portfolio.from_signals(
close=close_px,
entries=entries,
exits=exits,
size=entry_size,
size_type='amount',
price=next_open,
init_cash=init_equity,
fees=transaction_cost_bps,
direction='longonly',
accumulate=False,
cash_sharing=True,
group_by=True,
freq='1D'
)
# Idle cash yield (SHY)
bond_symbol = "SHY"
bond_px = yf.download(bond_symbol, start=start_date, end=end_date, auto_adjust=True, progress=False)["Close"].squeeze()
bond_daily = bond_px.pct_change().reindex(portfolio.value().index).fillna(0.0).to_numpy()
stock_equity = portfolio.value().to_numpy()
stock_value = portfolio.asset_value(group_by=True).to_numpy()
idle_cash = stock_equity - stock_value
bond_value = max(idle_cash[0], 0.0)
bond_earned = 0.0
bond_income = np.zeros(len(stock_equity))
for i in range(1, len(stock_equity)):
bond_income[i] = bond_value * bond_daily[i]
bond_earned += bond_income[i]
bond_value = max(idle_cash[i] + bond_earned, 0.0)
equity = pd.Series(stock_equity + np.cumsum(bond_income), index=portfolio.value().index)
print(f"Total Return: {((equity.iloc[-1] / equity.iloc[0] - 1.0) * 100):.2f}%")
print(f"Max Drawdown: {((equity / equity.cummax() - 1.0).min() * 100):.2f}%")