Skip to contents

Rebuilds derived tables from the event-sourced ledger and bars, and returns the reconstructed state artifacts.

Usage

ledgr_state_reconstruct(run_id, con)

Arguments

run_id

Run identifier.

con

A DBI connection to DuckDB.

Value

A list with positions, cash, pnl, and equity_curve.

Details

This is the low-level reconstruction API. User-facing helpers such as ledgr_compute_equity_curve() and as_tibble(bt, what = "equity") delegate to the same ledger-derived state model without requiring users to manage a raw DBI connection.

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 = "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)