OBV accumulation trend filter

R / quantstrat Research Notebook

Author

quantstr.at Research

Published

October 21, 2026

0.1 Overview

This notebook is a complete, executable replication of the strategy published at quantstr.at. Every number, table and chart below is produced by the R code in this document at render time; nothing is pasted in from the article. Re-running it (quarto render obv-accumulation-trend-diversified-etfs-20261014-R.qmd) reproduces every result from scratch against freshly downloaded market data.

The strategy, as specified:

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 20-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 20-day SMA. Exit the position when OBV crosses downward through its 20-day SMA or the close falls below its 50-day SMA.

1 Backtest

1.1 Environment

Load the backtesting packages and set a stable timezone.

suppressPackageStartupMessages({
  library(quantmod)
  library(TTR)
  library(xts)
  library(FinancialInstrument)
  library(blotter)
  library(quantstrat)
})
Sys.setenv(TZ = 'UTC')
options(width = 120)

1.2 Universe & Parameters

Strategy specification implemented here: OBV, 20-day SMA of OBV, 50-day SMA of close, 200-day SMA of close; enter on OBV upward cross with close above SMA200; exit on OBV downward cross or close below SMA50.

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

parameter_table <- data.frame(
  parameter = c('symbols', 'start_date', 'end_date', 'init_equity', 'n_symbols', 'slot_size', 'obv_sma_n', 'close_sma_fast_n', 'close_sma_slow_n', 'transaction_cost_bps'),
  value = c(paste(symbols, collapse = ', '), as.character(start_date), as.character(end_date), init_equity, n_symbols, slot_size, obv_sma_n, close_sma_fast_n, close_sma_slow_n, transaction_cost_bps)
)
print(parameter_table)

1.3 Data

Download unadjusted Yahoo data, convert every symbol to adjusted OHLC, and stop if a split-like daily return remains.

getSymbols(symbols, from = start_date, to = end_date, src = "yahoo", adjust = FALSE)
 [1] "SPY" "QQQ" "IWM" "EFA" "EEM" "TLT" "GLD" "VNQ" "XLV" "XLE"
for (sym in symbols) assign(sym, adjustOHLC(get(sym), use.Adjusted = TRUE))
for (sym in symbols) {
  worst <- max(abs(dailyReturn(Cl(get(sym)))), na.rm = TRUE)
  if (worst > 0.40) stop(sprintf("%s has a %.0f%% one-day move: likely an unadjusted split.", sym, worst * 100))
}

1.4 Portfolio Account & Strategy Setup

Create a long-only quantstrat portfolio, account, orders object, and strategy container.

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)

1.5 Indicators

Compute On-Balance Volume, the 20-day SMA of OBV, the 50-day SMA of close, and the 200-day SMA of close for each symbol.

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')

1.6 Signals

Build entry and exit signals from OBV/SMA crosses and close/SMA trend filters evaluated on the close.

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')

1.7 Rules

Enter with one whole-share equal-dollar slot at the next open, do not pyramid, and apply transaction costs as basis points of traded value before portfolio accounting.

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')

1.8 Run the Backtest

Apply the strategy, charge percentage transaction costs to every filled trade, then update portfolio, account, and ending equity.

applyStrategy(strategy.st, portfolios = portfolio.st)
apply_trade_value_fees(portfolio.st, symbols)
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)

1.9 Idle Cash in Bonds

Cash that is not held in a position is never left idle. It is treated as invested in a short-term Treasury bond ETF (bond_symbol) and earns that ETF’s daily total return (dividends included). The stock positions and their trades are unchanged; the bond income is credited to the account as interest, so every equity, return and drawdown figure below includes it. Idle cash on a day is the equity of the stock account minus the market value of the stock positions, plus the bond income already earned.

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))   # one value per account date; 0 on a date with no bond price
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)   # cash held in the bond ETF at the close of the previous day
bond_earned <- 0                      # bond income accumulated so far
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)
cat(sprintf("Idle cash earned $%s in %s over the window.\n", format(round(sum(bond_income)), big.mark = ","), bond_symbol))

1.10 Trade Statistics

tstats <- tradeStats(portfolio.st)
print(tstats)
                        Portfolio Symbol Num.Txns Num.Trades Net.Trading.PL Avg.Trade.PL Med.Trade.PL Largest.Winner
EEM obv_accumulation_trend_filter    EEM      121         60      1309.7691    20.187989   -17.256792       642.4118
EFA obv_accumulation_trend_filter    EFA      118         59      3723.5025    63.110212    24.364594       782.6155
GLD obv_accumulation_trend_filter    GLD      132         66      3207.0293    48.591352   -21.330231      1864.3193
IWM obv_accumulation_trend_filter    IWM      107         53      -826.1109   -13.566244   -28.114257       524.0348
QQQ obv_accumulation_trend_filter    QQQ      117         58      1939.9649    24.128417   -53.465413      1034.7159
SPY obv_accumulation_trend_filter    SPY      126         63      2087.7893    33.139513     8.310939       770.3247
TLT obv_accumulation_trend_filter    TLT       46         23      -867.9483   -37.736882   -39.000267       459.7532
VNQ obv_accumulation_trend_filter    VNQ      118         59      -475.2914    -8.055786   -32.133871       619.9413
XLE obv_accumulation_trend_filter    XLE      119         59      1990.1878    31.037081   -46.537727      1984.5871
XLV obv_accumulation_trend_filter    XLV      108         54      -997.2592   -18.467763   -29.224562       467.5112
    Largest.Loser Gross.Profits Gross.Losses Std.Dev.Trade.PL Std.Err.Trade.PL Percent.Positive Percent.Negative
EEM     -378.1601      5152.548    -3941.269         216.5031         27.95043         45.00000         55.00000
EFA     -390.6801      5977.617    -2254.114         217.3391         28.29514         54.23729         45.76271
GLD     -389.6002      7394.238    -4187.209         357.9605         44.06190         40.90909         59.09091
IWM     -471.3854      3083.314    -3802.325         183.1164         25.15297         35.84906         64.15094
QQQ     -262.0020      5972.709    -4573.261         262.2887         34.44019         43.10345         56.89655
SPY     -285.7364      4766.694    -2678.905         182.9686         23.05188         53.96825         46.03175
TLT     -327.6402      1113.364    -1981.312         171.9023         35.84411         30.43478         69.56522
VNQ     -292.9874      2995.671    -3470.962         160.4844         20.89329         35.59322         64.40678
XLE     -598.1200      8116.067    -6284.879         440.9274         57.40386         38.98305         61.01695
XLV     -276.1835      1860.563    -2857.822         124.3921         16.92762         33.33333         66.66667
    Profit.Factor Avg.Win.Trade Med.Win.Trade Avg.Losing.Trade Med.Losing.Trade Avg.Daily.PL Med.Daily.PL
EEM     1.3073323      190.8351      94.03809       -119.43240       -116.75454    20.187989   -17.256792
EFA     2.6518694      186.8005      83.49892        -83.48572        -60.41914    63.110212    24.364594
GLD     1.7659110      273.8607      90.74966       -107.36433        -88.55997    48.591352   -21.330231
IWM     0.8109023      162.2797     139.77904       -111.83309        -70.40613   -13.566244   -28.114257
QQQ     1.3060067      238.9084     138.54858       -138.58366       -153.23949    24.128417   -53.465413
SPY     1.7793443      140.1969      50.30256        -92.37603        -82.37664    33.139513     8.310939
TLT     0.5619326      159.0520     112.40097       -123.83200       -110.34499   -37.736882   -39.000267
VNQ     0.8630664      142.6510      85.67286        -91.34112        -81.82672    -8.055786   -32.133871
XLE     1.2913640      352.8725     153.77967       -174.57997       -117.13573    31.037081   -46.537727
XLV     0.6510422      103.3646      53.95524        -79.38394        -63.94797   -18.467763   -29.224562
    Std.Dev.Daily.PL Std.Err.Daily.PL Ann.Sharpe Max.Drawdown Profit.To.Max.Draw Avg.WinLoss.Ratio Med.WinLoss.Ratio
EEM         216.5031         27.95043   1.480230   -1189.4012          1.1012004          1.597851         0.8054341
EFA         217.3391         28.29514   4.609588    -603.4829          6.1700218          2.237515         1.3819946
GLD         357.9605         44.06190   2.154885   -1835.5998          1.7471288          2.550760         1.0247256
IWM         183.1164         25.15297  -1.176069   -1632.3408         -0.5060897          1.451088         1.9853248
QQQ         262.2887         34.44019   1.460325   -1843.7748          1.0521702          1.723929         0.9041310
SPY         182.9686         23.05188   2.875211   -1132.4250          1.8436447          1.517676         0.6106411
TLT         171.9023         35.84411  -3.484854   -1035.3125         -0.8383443          1.284417         1.0186323
VNQ         160.4844         20.89329  -0.796848   -2401.7826         -0.1978911          1.561739         1.0470035
XLE         440.9274         57.40386   1.117414   -3341.2950          0.5956337          2.021265         1.3128332
XLV         124.3921         16.92762  -2.356795   -1224.1976         -0.8146227          1.302084         0.8437366
    Max.Equity Min.Equity End.Equity
EEM  2017.0789  -970.2150  1309.7691
EFA  4066.2484  -356.3121  3723.5025
GLD  4352.5894  -878.8507  3207.0293
IWM   113.1105 -1519.2303  -826.1109
QQQ  3243.2230  -405.4693  1939.9649
SPY  2850.9444  -310.0711  2087.7893
TLT     0.0000 -1035.3125  -867.9483
VNQ  1468.6756  -933.1071  -475.2914
XLE  2553.1986  -788.0964  1990.1878
XLV   226.9384  -997.2592  -997.2592

2 Benchmarks & Risk

This section continues in the same R session, reusing the portfolio, account and price data built above.

2.1 Headline Performance

library(PerformanceAnalytics)
strategy_eq <- getAccount(account.st)$summary$End.Eq
final_eq <- as.numeric(last(strategy_eq))
total_ret_pct <- (final_eq / init_equity - 1) * 100
strategy_ret <- dailyReturn(strategy_eq)
ann_ret_pct <- as.numeric(Return.annualized(strategy_ret)) * 100
sharpe <- as.numeric(SharpeRatio.annualized(strategy_ret, Rf = 0))
maxdd_pct <- as.numeric(maxDrawdown(strategy_ret)) * 100
tstats_kpi <- tradeStats(portfolio.st)
n_trades <- sum(tstats_kpi$Num.Trades)
n_winners <- sum(round(tstats_kpi$Percent.Positive / 100 * tstats_kpi$Num.Trades))
win_rate <- n_winners / n_trades * 100
profit_factor <- sum(tstats_kpi$Gross.Profits) / abs(sum(tstats_kpi$Gross.Losses))
kpi_df <- data.frame(
  Metric = c("Final Equity", "Total Return", "Annualized Return", "Annualized Sharpe",
             "Max Drawdown", "Closed Trades", "Win Rate", "Profit Factor"),
  Value = c(sprintf("$%s", format(round(final_eq), big.mark = ",", scientific = FALSE)),
            sprintf("%.2f%%", total_ret_pct), sprintf("%.2f%%", ann_ret_pct), sprintf("%.2f", sharpe),
            sprintf("%.2f%%", maxdd_pct), sprintf("%d", n_trades), sprintf("%.1f%%", win_rate),
            sprintf("%.2f", profit_factor)))
gt::gt(kpi_df) |>
  gt::tab_header(title = "Headline Results", subtitle = sprintf("%s to %s", start_date, end_date)) |>
  gt::cols_align(align = "right", columns = "Value")
Headline Results
2021-10-07 to 2026-10-07
Metric Value
Final Equity $116,847
Total Return 16.85%
Annualized Return 3.18%
Annualized Sharpe 0.77
Max Drawdown 5.46%
Closed Trades 554
Win Rate 42.1%
Profit Factor 1.29

2.2 Strategy vs. Benchmarks

The strategy against two passive benchmarks over the same window: SPY buy-and-hold and an equal-weight buy-and-hold basket of the traded symbols.

spy <- getSymbols("SPY", from = start_date, to = end_date, auto.assign = FALSE, src = "yahoo", adjust = FALSE)
spy <- adjustOHLC(spy, use.Adjusted = TRUE)
spy_eq <- init_equity * Cl(spy) / as.numeric(Cl(spy)[1])
basket_eq <- Reduce(`+`, lapply(symbols, function(s) {
  px <- Cl(get(s)); (init_equity / length(symbols)) * px / as.numeric(px[1])
}))
comparison <- merge(strategy_eq, spy_eq, basket_eq, join = "inner")
colnames(comparison) <- c("Strategy", "SPY", "Equal-weight basket")
plot(as.zoo(comparison), plot.type = "single", col = c("#00E08F", "#8B5CF6", "#2563EB"),
     lwd = 2, xlab = "", ylab = "Equity ($)", main = "Strategy vs. Benchmark Equity Curves")
legend("topleft", legend = colnames(comparison), col = c("#00E08F", "#8B5CF6", "#2563EB"), lwd = 2, bty = "n")

bench_final <- as.numeric(last(comparison))
gt::gt(data.frame(Series = colnames(comparison),
                  `Final Equity` = sprintf("$%s", format(round(bench_final), big.mark = ",")),
                  `Total Return` = sprintf("%.2f%%", (bench_final / init_equity - 1) * 100), check.names = FALSE))
Series Final Equity Total Return
Strategy $116,847 16.85%
SPY $189,892 89.89%
Equal-weight basket $166,953 66.95%

2.3 Drawdown

dd <- Drawdowns(strategy_ret) * 100
plot(as.zoo(dd), col = "#FF4D6A", lwd = 1.5, xlab = "", ylab = "Drawdown (%)", main = "Strategy Drawdown")
abline(h = 0, lty = 2, col = "gray60")

2.4 Portfolio Exposure Over Time

Mark-to-market share of equity held in positions, from blotter’s own position values.

pos_value <- Reduce(`+`, lapply(symbols, function(s) getPortfolio(portfolio.st)$symbols[[s]]$posPL.USD$Pos.Value))
exposure_pct <- 100 * merge(pos_value, strategy_eq, join = "inner")[, 1] / merge(pos_value, strategy_eq, join = "inner")[, 2]
plot(as.zoo(exposure_pct), col = "#2563EB", lwd = 1.5, xlab = "", ylab = "% of Equity Invested", main = "Portfolio Exposure Over Time")

2.5 Rolling 3-Month Sharpe

roll <- rollapply(strategy_ret, width = 63, FUN = function(r) mean(r) / sd(r) * sqrt(252), align = "right", fill = NA)
plot(as.zoo(roll), col = "#8B5CF6", lwd = 1.5, xlab = "", ylab = "Annualized Sharpe", main = "Rolling 3-Month Sharpe")
abline(h = 0, lty = 2, col = "gray60")