Rebuilds derived tables from the event-sourced ledger and bars, and returns the reconstructed state artifacts.
Details
This is the low-level reconstruction API. User-facing helpers such as
ledgr_results(bt, "equity") and as_tibble(bt, what = "equity") delegate
to the same ledger-derived state model without requiring users to manage a
raw DBI connection.
An availability-aware run is rebuilt on its session calendar up to its last fully valued pulse, valuing each holding at its last observed close, which is the current, stale or frozen mark the run used, so members may miss bars. A dense run needs a close for every instrument at every pulse.
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())
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
# Low-level reconstruction requires an explicit DBI connection.
con <- ledgr_db_init(bt$db_path)
state <- ledgr_state_reconstruct(bt$run_id, con)
state$positions
#> instrument_id qty
#> 1 AAA 1
DBI::dbDisconnect(con, shutdown = TRUE)
close(bt)