Code
suppressPackageStartupMessages({
library(quantmod)
library(TTR)
library(xts)
library(FinancialInstrument)
library(blotter)
library(quantstrat)
})
Sys.setenv(TZ = 'UTC')
options(width = 120)R / quantstrat Research Notebook
Get the code: Download Strategy Code (.R) | Download Analysis Code (.R)
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 adx-trend-emergence-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, XLK, XLF, and XLE from 2021-10-07 to 2026-10-07 using a long-only ADX trend-emergence 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 ADX(14), SMA(50), and SMA(200). Enter long when the symbol is not already held, ADX(14) crosses above 20 from at or below 20, the close is above the SMA(50), and the SMA(50) is above the SMA(200). Exit when the symbol is held and either the close falls below the SMA(50) or ADX(14) crosses below 20 from at or above 20.
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)Strategy specification implemented here: ADX(14), SMA(50), and SMA(200); enter long when not held, ADX crosses above 20, close > SMA50, and SMA50 > SMA200; exit when held and close < SMA50 or ADX crosses below 20.
symbols <- c('SPY', 'QQQ', 'IWM', 'EFA', 'EEM', 'TLT', 'GLD', 'XLK', 'XLF', '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
adx_n <- 14
sma_fast_n <- 50
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', 'adx_n', 'sma_fast_n', '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, adx_n, sma_fast_n, sma_slow_n, transaction_cost_bps)
)
print(parameter_table)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" "XLK" "XLF" "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))
}Create a long-only quantstrat portfolio, account, orders object, and strategy container.
portfolio.st <- 'adx_trend_emergence'
account.st <- 'adx_trend_emergence_account'
strategy.st <- 'adx_trend_emergence'
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)Compute ADX(14), SMA(50), and SMA(200) for each symbol.
add.indicator(strategy.st, name = 'ADX', arguments = list(HLC = quote(HLC(mktdata)), n = adx_n), label = 'ADX')
add.indicator(strategy.st, name = 'SMA', arguments = list(x = quote(Cl(mktdata)), n = sma_fast_n), label = 'SMA50')
add.indicator(strategy.st, name = 'SMA', arguments = list(x = quote(Cl(mktdata)), n = sma_slow_n), label = 'SMA200')Build entry and exit signals from ADX crosses and moving average trend conditions.
add.signal(strategy.st, name = 'sigThreshold', arguments = list(column = 'ADX.ADX', threshold = 20, relationship = 'gt', cross = TRUE), label = 'ADXCrossUp')
add.signal(strategy.st, name = 'sigThreshold', arguments = list(column = 'ADX.ADX', threshold = 20, relationship = 'lt', cross = TRUE), label = 'ADXCrossDown')
add.signal(strategy.st, name = 'sigComparison', arguments = list(columns = c('Close', 'SMA.SMA50'), relationship = 'gt'), label = 'CloseAboveSMA50')
add.signal(strategy.st, name = 'sigComparison', arguments = list(columns = c('SMA.SMA50', 'SMA.SMA200'), relationship = 'gt'), label = 'SMA50AboveSMA200')
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 = 'ADXCrossUp & CloseAboveSMA50 & SMA50AboveSMA200', cross = FALSE), label = 'EnterLong')
add.signal(strategy.st, name = 'sigFormula', arguments = list(formula = 'ADXCrossDown | CloseBelowSMA50', cross = FALSE), label = 'ExitLong')Enter with one whole-share equal-dollar slot at the next open, do not pyramid, and apply transaction costs.
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')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)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))The complete tradeStats table, every column, for every symbol.
tstats <- tradeStats(portfolio.st)
print(tstats) Portfolio Symbol Num.Txns Num.Trades Net.Trading.PL Avg.Trade.PL Med.Trade.PL Largest.Winner
EEM adx_trend_emergence EEM 26 13 -466.05240 -35.85018 -125.79911 530.94595
EFA adx_trend_emergence EFA 26 13 217.82044 16.75542 7.35382 330.68732
GLD adx_trend_emergence GLD 18 9 4948.62878 549.84764 178.20030 1758.49991
IWM adx_trend_emergence IWM 14 7 -1982.75677 -283.25097 -329.04838 404.97512
QQQ adx_trend_emergence QQQ 22 11 1368.04640 124.36785 -15.45769 1380.48855
SPY adx_trend_emergence SPY 14 7 1209.25062 172.75009 34.08317 1082.18950
TLT adx_trend_emergence TLT 6 3 78.46441 26.15480 11.75728 215.23116
XLE adx_trend_emergence XLE 22 11 1101.83197 100.16654 -242.57792 1969.46121
XLF adx_trend_emergence XLF 20 10 -1964.51887 -196.45189 -248.57603 13.11969
XLK adx_trend_emergence XLK 12 6 3625.80542 604.30090 361.35709 2008.19527
Largest.Loser Gross.Profits Gross.Losses Std.Dev.Trade.PL Std.Err.Trade.PL Percent.Positive Percent.Negative
EEM -436.30689 1344.38129 -1810.43368 294.3710 81.64383 38.46154 61.53846
EFA -251.14341 1020.00407 -802.18362 179.9203 49.90092 53.84615 46.15385
GLD 0.00000 4948.62878 0.00000 617.7539 205.91797 100.00000 0.00000
IWM -868.71716 408.75002 -2391.50680 407.0549 153.85230 28.57143 71.42857
QQQ -281.76785 2138.21058 -770.16418 452.2603 136.36160 45.45455 54.54545
SPY -385.57767 1886.75936 -677.50874 492.3603 186.09470 57.14286 42.85714
TLT -148.52402 226.98844 -148.52402 182.3045 105.25354 66.66667 33.33333
XLE -986.51521 3640.24982 -2538.41785 804.5215 242.57237 36.36364 63.63636
XLF -330.27388 13.11969 -1977.63856 123.9261 39.18888 10.00000 90.00000
XLK -63.58479 3689.39020 -63.58479 778.2350 317.71310 83.33333 16.66667
Profit.Factor Avg.Win.Trade Med.Win.Trade Avg.Losing.Trade Med.Losing.Trade Avg.Daily.PL Med.Daily.PL
EEM 0.742574168 268.87626 266.13686 -226.30421 -218.65599 -35.85018 -125.79911
EFA 1.271534393 145.71487 87.73349 -133.69727 -122.03208 16.75542 7.35382
GLD NA 549.84764 178.20030 NaN NA 549.84764 178.20030
IWM 0.170917357 204.37501 204.37501 -478.30136 -419.76796 -283.25097 -329.04838
QQQ 2.776304882 427.64212 225.84541 -128.36070 -122.16673 124.36785 -15.45769
SPY 2.784848731 471.68984 385.24334 -225.83625 -181.57116 172.75009 34.08317
TLT 1.528294411 113.49422 113.49422 -148.52402 -148.52402 26.15480 11.75728
XLE 1.434062490 910.06245 810.52350 -362.63112 -269.07761 100.16654 -242.57792
XLF 0.006634017 13.11969 13.11969 -219.73762 -277.10763 -196.45189 -248.57603
XLK 58.023159999 737.87804 544.97200 -63.58479 -63.58479 604.30090 361.35709
Std.Dev.Daily.PL Std.Err.Daily.PL Ann.Sharpe Max.Drawdown Profit.To.Max.Draw Avg.WinLoss.Ratio Med.WinLoss.Ratio
EEM 294.3710 81.64383 -1.933288 -1972.2409 -0.2363060 1.18811867 1.2171487
EFA 179.9203 49.90092 1.478343 -783.4151 0.2780396 1.08988662 0.7189379
GLD 617.7539 205.91797 14.129511 -1719.2497 2.8783653 NA NA
IWM 407.0549 153.85230 -11.046346 -2572.5244 -0.7707436 0.42729339 0.4868762
QQQ 452.2603 136.36160 4.365359 -1530.3067 0.8939688 3.33156586 1.8486654
SPY 492.3603 186.09470 5.569748 -497.7366 2.4294990 2.08863655 2.1217210
TLT 182.3045 105.25354 2.277479 -480.7110 0.1632258 0.76414721 0.7641472
XLE 804.5215 242.57237 1.976448 -2819.8740 0.3907380 2.50960936 3.0122295
XLF 123.9261 39.18888 -25.164808 -2168.0075 -0.9061403 0.05970616 0.0473451
XLK 778.2350 317.71310 12.326585 -1172.5993 3.0921096 11.60463200 8.5707924
Max.Equity Min.Equity End.Equity
EEM 314.79910 -1972.24093 -466.05240
EFA 777.38138 -221.06625 217.82044
GLD 5643.87872 -35.74966 4948.62878
IWM 44.61342 -2527.91095 -1982.75677
QQQ 2189.60740 -33.97391 1368.04640
SPY 1264.49548 -388.33520 1209.25062
TLT 393.86210 -107.95956 78.46441
XLE 3033.94566 -520.67414 1101.83197
XLF 172.58720 -1995.42027 -1964.51887
XLK 4102.62247 -76.47089 3625.80542
This section continues in the same R session, reusing the portfolio, account and price data built above.
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 | $115,365 |
| Total Return | 15.36% |
| Annualized Return | 2.91% |
| Annualized Sharpe | 0.80 |
| Max Drawdown | 5.49% |
| Closed Trades | 90 |
| Win Rate | 48.9% |
| Profit Factor | 1.73 |
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 | $115,365 | 15.36% |
| SPY | $189,892 | 89.89% |
| Equal-weight basket | $184,861 | 84.86% |
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")
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")
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")