Extract tidy backtest tables
Usage
# S3 method for class 'ledgr_backtest'
as_tibble(x, what = "equity", ..., type = NULL)Details
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.
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.
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)
tibble::as_tibble(bt, what = "trades")
#> # A tibble: 0 × 9
#> # ℹ 9 variables: event_seq <int>, ts_utc <dttm>, instrument_id <chr>,
#> # side <chr>, qty <dbl>, price <dbl>, fee <dbl>, realized_pnl <dbl>,
#> # action <chr>
tibble::as_tibble(bt, what = "equity")
#> # A tibble: 4 × 6
#> ts_utc equity cash positions_value running_max drawdown
#> <dttm> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2020-01-01 00:00:00 1000 1000 0 1000 0
#> 2 2020-01-02 00:00:00 1000 899 101 1000 0
#> 3 2020-01-03 00:00:00 1001 899 102 1001 0
#> 4 2020-01-04 00:00:00 1002 899 103 1002 0
close(bt)