Backtests

Can OBV Accumulation Signals Improve Trend Entries on Diversified ETFs?

October 17, 2026
Share: Post Share Reddit
Post-Mortem — this strategy failed our held-out test. We publish these on purpose: most trading ideas do not work, and showing why is as useful as showing the ones that do.
  • 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
ResultsHeld-Out TestBreakdownRiskMonthly ReturnsReproduce

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.
Strategy
+16.8% (CAGR: +3.2%)
Worst decline: -5.5% | Risk-adjusted: 0.77 Sharpe
Equal-weight buy & hold basket (10 symbols)
+67.0% (CAGR: +10.8%)
Worst decline: -19.3% | Risk-adjusted: 0.81 Sharpe
Buy & hold SPY
+89.9% (CAGR: +13.7%)
Worst decline: -24.5% | Risk-adjusted: 0.80 Sharpe

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.

Component Description
Indicator OBV, 20-day SMA of OBV, 50-day SMA of close, 200-day SMA of close
Signal Close is above 200-day SMA and OBV crosses upward through its 20-day SMA
Rule Enter long at next open when signals are true; exit at next open when OBV crosses downward through its 20-day SMA or close falls below its 50-day SMA

Strategy Design

Backtest Setup
Read from this run’s saved configuration
Parameter Setting / Value
Asset universe 10 symbols (SPY, QQQ, IWM, EFA, EEM, TLT, GLD, VNQ, XLV, XLE)
Time window 2021-10-07 to 2026-10-07 (5.0 years)
Starting equity $100,000
Benchmarks Equal-weight buy & hold basket (10 symbols) (+67.0%); Buy & hold SPY (+89.9%)
Position size (as executed) 12 to 309 units per trade
Idle cash Held in SHY (daily total return credited)
Execution model Orders fill at the next bar’s open after the signal bar
Transaction cost 5 bps of traded value on every fill (entry and exit)
Commission None modelled beyond the 5 bps cost
Position sizing One equal dollar slot per symbol (starting equity divided by the number of symbols), whole shares, long-only, no leverage and no adding to open positions
Idle cash Cash not held in a position is invested in a short-term Treasury bond ETF and earns its daily total return

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.

Backtest Summary
Every figure computed from this run’s saved results
Metric Value
Starting capital $100,000
Ending capital $116,847
Total return +16.85%
Annualized return (CAGR) +3.16%
Closed trades 554 (+3 still open at the end)
Win rate (closed trades) 41.9%
Profit factor (closed trades) 1.29
Sharpe ratio (annualized) 0.77
Calmar ratio 0.58
Max drawdown -5.46%
Bond income on idle cash (SHY) $5,756
Total return without bond income +11.09%
Equal-weight buy & hold basket (10 symbols) +66.95%
Strategy vs. Equal-weight buy & hold basket (10 symbols) -50.11 pp
Buy & hold SPY +89.89%
Strategy vs. Buy & hold SPY -73.05 pp
Risk-Adjusted Return Metrics
Metric Value
Annualized Return (CAGR) 3.16%
Annualized Volatility 4.13%
Sharpe Ratio 0.77
Sortino Ratio 1.12
Calmar Ratio 0.58

Risk-Adjusted Returns

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.
Distribution Across Symbols
How the result is spread across the universe
Statistic Value
Symbols with closed trades 10
Symbols profitable 6 (60.0%)
Median net P&L per symbol +$1,305
Mean net P&L per symbol +$1,040
10th / 90th percentile net P&L – 881/+881 / +3,259
25th / 75th percentile net P&L – 658/+658 / +2,024
Performance by Symbol
10 symbols, closed trades only
Symbol Trades Net P&L Win rate Profit factor
EFA 59 +$3,724 54.2% 2.65
GLD 66 +$3,207 40.9% 1.77
SPY 63 +$2,088 54.0% 1.78
XLE 59 +$1,831 39.0% 1.29
QQQ 58 +$1,399 43.1% 1.31
EEM 60 +$1,211 45.0% 1.31
VNQ 59 -$475 35.6% 0.86
IWM 53 -$719 35.8% 0.81
TLT 23 -$868 30.4% 0.56
XLV 54 -$997 31.5% 0.65
Profit Concentration
How much of the result depends on the largest winning trades (closed trades only)
Scenario Net profit Total return Profit removed
Headline result +$16,847 +16.8% –
Excluding the single largest winner +$14,863 +14.9% $1,985
Excluding the 5 largest winners +$8,507 +8.5% $8,340

Is the Average Trade Different From Zero?
One-sample t-test on per-trade returns; overlapping trades are not independent, so treat the p-value as indicative
Statistic Value
Closed trades tested 554
Mean return per trade +0.19%
Standard error 0.11 pp
95% confidence interval for the mean -0.03% to +0.41%
t-statistic (H0: mean = 0) 1.73
p-value (two-sided) 0.0844

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 Matrix (%)
Month202120222023202420252026
Jan–-0.69%1.96%-0.78%0.05%2.87%
Feb–-0.43%-2.02%0.18%0.02%2.84%
Mar–-1.40%2.17%1.06%0.45%-2.11%
Apr–-0.50%0.53%-2.08%-0.36%1.37%
May–0.60%-0.38%1.39%0.68%0.28%
Jun–-0.59%0.24%0.13%0.90%-1.13%
Jul–0.75%1.99%1.88%0.00%-0.03%
Aug–-1.12%-0.87%1.58%0.21%0.29%
Sep–-1.31%-0.41%1.17%1.77%-0.88%
Oct-0.28%1.13%0.40%-0.48%0.20%0.48%
Nov-0.06%1.22%1.13%0.71%-0.10%–
Dec-0.21%-0.34%2.68%-0.45%-0.33%–
YTD-0.55%-2.70%7.57%4.32%3.53%3.93%

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.

Discovery window
2021-10-06 to 2025-02-04
Held-out window
2025-02-04 to 2026-10-06
CAGRSharpeMax drawdownCAGRSharpeMax drawdown
Strategy (with bond income on idle cash)2.5%0.675.5%4.4%0.943.1%
Equal-weight buy & hold basket (10 symbols)6.6%0.5019.3%19.6%1.4713.0%
Buy & hold SPY11.5%0.6824.5%18.1%1.0618.8%

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

Side-by-Side Comparison
Benchmark CAGR, drawdown and Sharpe are computed from daily closes over the same window, with the same method as the strategy’s daily equity (zero risk-free rate)
Metric Strategy Equal-weight buy & hold basket (10 symbols) Buy & hold SPY
Total return +16.8% +67.0% +89.9%
Annualized return (CAGR) +3.2% +10.8% +13.7%
Max drawdown -5.5% -19.3% -24.5%
Sharpe ratio (annualized) 0.77 0.81 0.80
Ending equity $116,847 $166,953 $189,892

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

Reproduce This Test

Full Per-Symbol Trade Statistics

Trade Statistics by Symbol
Detailed performance and risk metrics breakdown per traded asset
Symbol Trades Realised Net P&L Win Rate Loss Rate Max Equity Min Equity Gross Profits Gross Losses Max Drawdown Transactions Avg Trade P&L Ending Equity (incl. open) Largest Winner Largest Loser Profit Factor Avg Winning Trade Avg Losing Trade Median Trade P&L Trade P&L Std Dev Avg Win/Loss Ratio Median Losing Trade Median Winning Trade Median Win/Loss Ratio Profit / Max Drawdown
SPY 63 $2,088 54.0% 46.0% $2,851 -$310 $4,767 -$2,679 -$1,132 126 $33 $2,088 $770 -$286 1.78 $140 -$92 $8 $183 1.52 -$82 $50 0.61 1.84
QQQ 58 $1,399 43.1% 56.9% $3,243 -$405 $5,973 -$4,573 -$1,844 117 $24 $1,940 $1,035 -$262 1.31 $239 -$139 -$53 $262 1.72 -$153 $139 0.90 1.05
IWM 53 -$719 35.8% 64.2% $113 -$1,519 $3,083 -$3,802 -$1,632 107 -$14 -$826 $524 -$471 0.81 $162 -$112 -$28 $183 1.45 -$70 $140 1.99 -0.51
EFA 59 $3,724 54.2% 45.8% $4,066 -$356 $5,978 -$2,254 -$603 118 $63 $3,724 $783 -$391 2.65 $187 -$83 $24 $217 2.24 -$60 $83 1.38 6.17
EEM 60 $1,211 45.0% 55.0% $2,017 -$970 $5,153 -$3,941 -$1,189 121 $20 $1,310 $642 -$378 1.31 $191 -$119 -$17 $217 1.60 -$117 $94 0.81 1.10
TLT 23 -$868 30.4% 69.6% $0 -$1,035 $1,113 -$1,981 -$1,035 46 -$38 -$868 $460 -$328 0.56 $159 -$124 -$39 $172 1.28 -$110 $112 1.02 -0.84
GLD 66 $3,207 40.9% 59.1% $4,353 -$879 $7,394 -$4,187 -$1,836 132 $49 $3,207 $1,864 -$390 1.77 $274 -$107 -$21 $358 2.55 -$89 $91 1.02 1.75
VNQ 59 -$475 35.6% 64.4% $1,469 -$933 $2,996 -$3,471 -$2,402 118 -$8 -$475 $620 -$293 0.86 $143 -$91 -$32 $160 1.56 -$82 $86 1.05 -0.20
XLV 54 -$997 31.5% 68.5% $227 -$997 $1,861 -$2,858 -$1,224 108 -$18 -$997 $468 -$276 0.65 $109 -$77 -$29 $124 1.42 -$63 $54 0.85 -0.81
XLE 59 $1,831 39.0% 61.0% $2,553 -$788 $8,116 -$6,285 -$3,341 119 $31 $1,990 $1,985 -$598 1.29 $353 -$175 -$47 $441 2.02 -$117 $154 1.31 0.60

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}%")
R · quantstrat
View the Full R Research Report →
Interactive standalone research report with complete backtest, benchmark plots, and risk metrics.
Interactive Web Backtester

Clone and test this strategy in the web app

Launch the audited recipe in our web backtester. Tweak indicators, adjust thresholds, and test alternative parameters with 1 click.

Clone & Test Strategy →
← Back to all backtests