Package-prefixed convenience wrapper around tibble::as_tibble() for
backtest result tables.
Usage
ledgr_results(bt, what = c("equity", "returns", "fills", "trades", "ledger"))Details
The returned object is tibble-compatible. Its print method may compact
all-midnight UTC timestamps for EOD output according to
options(ledgr.print_ts_utc), but programmatic access keeps ts_utc as
POSIXct UTC.
what = "fills" returns execution fill rows, including opening and closing
actions. Fill rows include execution side, absolute qty, price, fee,
derived action, and realized_pnl. Opening fills have action = "OPEN"
and do not count as closed trades.
what = "trades" returns closed trade rows only. This table has the same
zero-row schema as fills, but only rows with action = "CLOSE" are present.
It is the source for n_trades, win_rate, and avg_trade.
what = "equity" returns the public equity curve used for return,
drawdown, volatility, and exposure metrics. Open positions can affect equity
through positions_value even when there are zero closed trade rows. The
final equity used by prints and comparisons is the last row of this table.
what = "returns" returns the public equity curve as return evidence with
columns ts_utc, equity, and period_return. The first period return is
NA_real_; later rows use the same adjacent-equity return formula as
ledgr-owned metrics and retained sweep returns.
ledgr_results() does not support what = "metrics". Metrics are derived
from the public result tables; use summary(bt) for printed interpretation
or ledgr_compute_metrics(bt) for a named list.
ledgr_results() also does not support what = "features"; inspect feature
values at pulse time with ledgr_pulse_snapshot() and
ledgr_pulse_features() or ledgr_pulse_wide().
Articles
Metrics and accounting:
vignette("metrics-and-accounting", package = "ledgr")
system.file("doc", "metrics-and-accounting.html", package = "ledgr")
Examples
bars <- data.frame(
ts_utc = as.POSIXct("2020-01-01", tz = "UTC") + 86400 * 0:3,
instrument_id = "AAA",
open = c(100, 101, 102, 103),
high = c(101, 102, 103, 104),
low = c(99, 100, 101, 102),
close = c(100, 101, 102, 103),
volume = 1000
)
strategy <- function(ctx, params) {
targets <- ctx$flat()
targets["AAA"] <- 1
targets
}
bt <- ledgr_backtest(data = bars, strategy = strategy, initial_cash = 1000, cost_model = ledgr_cost_zero())
ledgr_results(bt, what = "trades")
#> # A tibble: 0 × 9
#> # ℹ 9 variables: event_seq <int>, ts_utc <date>, instrument_id <chr>,
#> # side <chr>, qty <dbl>, price <dbl>, fee <dbl>, realized_pnl <dbl>,
#> # action <chr>
ledgr_results(bt, what = "returns")
#> # A tibble: 4 × 3
#> ts_utc equity period_return
#> <date> <dbl> <dbl>
#> 1 2020-01-01 1000 NA
#> 2 2020-01-02 1000 0
#> 3 2020-01-03 1001 0.001000
#> 4 2020-01-04 1002 0.000999
close(bt)