# %% 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)

# %% Universe & Parameters
#' 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)

# %% 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)
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))
}

# %% Portfolio Account & Strategy Setup
#' 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)

# %% Indicators
#' 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')

# %% Signals
#' 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')

# %% Rules
#' 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')

# %% 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)

# %% 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))


# %% Trade Statistics
#' The complete tradeStats table, every column, for every symbol.
tstats <- tradeStats(portfolio.st)
print(tstats)
