This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.

Optimising the rsims package for Fast Backtesting in R – Part I

Robot Wealth

Robot Wealth
Visit: Robot Wealth

rsims is a new package for fast, quasi event-driven backtesting in R. You can find the source on GitHub, docs here, and an introductory blog post here.

Our use case for rsims was accurate but fast simulation of trading strategies. I’ve had a few questions about how I made the backtester as fast as it is – after all, it uses a giant for loop, and R is notoriously slow for such operations – so here’s a post about how I optimised rsims for speed.


I firstly wrote the backtester with a focus on ease of understanding. I wanted something that worked as expected, and that I could think about without too much effort. At this stage, I wasn’t thinking much about speed or efficiency.

Once I had that working, I focused on finding bottlenecks with profvis. It’s a good idea to resist the urge to optimise before you know where you’ll get the most bang for your buck (speaking from experience here).

Then I simply tackled those bottlenecks one at a time until I reached a point of diminishing returns (which is a little subjective and dependent on one’s use case).

There’s one thing I’d do differently if I were starting over: write the tests first, rather than after the fact. In hindsight, this would have saved a ton of time. To be honest, it’s something that I say after every little development effort, but this time I’ve really learned my lesson.

Profiling with profvis

The original code looked a lot different from the current version. It had lots of data frames and dplyr pipelines for operating on data:

positions_from_no_trade_buffer <- function(current_positions, current_prices, current_theo_weights, cap_equity, num_assets, trade_buffer) {
  current_weights <- current_positions*current_prices/cap_equity
  target_positions <- current_positions
  for(j in 1:num_assets) {
    if([j]) || current_theo_weights[j] == 0) {
      target_positions[j] <- 0
    # note: we haven't truncated to nearest whole coin, as coins are divisible (unlike shares)
    if(current_weights[j] < current_theo_weights[j] - trade_buffer) {
      target_positions[j] <- (current_theo_weights[j] - trade_buffer)*cap_equity/current_prices[j]
    } else if(current_weights[j] > current_theo_weights[j] + trade_buffer) {
      target_positions[j] <- (current_theo_weights[j] + trade_buffer)*cap_equity/current_prices[j]
cash_backtest_original <- function(backtest_df_long, trade_buffer = 0., initial_cash = 10000, commission_pct = 0, capitalise_profits = FALSE) {
  # Create wide data frames 
  wide_prices <- backtest_df_long %>%
    pivot_wider(date, names_from = 'ticker', values_from = 'price')
  wide_theo_weights <- backtest_df_long %>%
    pivot_wider(date, names_from = 'ticker', values_from = 'theo_weight')
  # get tickers for later
  tickers <- colnames(wide_prices)[-1]
  # initial state
  num_assets <- ncol(wide_prices) - 1  # -1 for date column
  current_positions <- rep(0, num_assets)
  previous_theo_weights <- rep(0, num_assets)
  row_list <- list() 
  cash <- initial_cash
  # backtest loop
  for(i in 1:nrow(wide_prices)) {
    current_date <- wide_prices[i, 1] %>% pull() %>% as.Date()
    current_prices <- wide_prices[i, -1] %>% as.numeric()
    current_theo_weights <- wide_theo_weights[i, -1] %>% as.numeric()
    # update equity
    equity <- sum(current_positions * current_prices, na.rm = TRUE) + cash
    cap_equity <- ifelse(capitalise_profits, equity, min(initial_cash, equity))  # min reflects assumption that we don't top up strategy equity if in drawdown
    # update positions based on no-trade buffer
    target_positions <- positions_from_no_trade_buffer(current_positions, current_prices, current_theo_weights, cap_equity, num_assets, trade_buffer)
    # calculate position deltas, trade values and commissions
    trades <- target_positions - current_positions
    trade_value <- trades * current_prices
    commissions <- abs(trade_value) * commission_pct
    # adjust cash by value of trades
    cash <- cash - sum(trade_value, na.rm = TRUE) - sum(commissions, na.rm = TRUE)
    current_positions <- target_positions
    position_value <- current_positions * current_prices
    equity <- sum(position_value, na.rm = TRUE) + cash
    # Create data frame and add to list
    row_df <- data.frame(
       Ticker = c('Cash', tickers),
       Date = rep(current_date, num_assets + 1),
       Close = c(0, current_prices),
       Position = c(0, current_positions),
       Value = c(cash, position_value),
       Trades = c(-sum(trade_value), trades),
       TradeValue = c(-sum(trade_value), trade_value),
       Commission = c(0, commissions)
    row_list[[i]] <- row_df
    previous_theo_weights <- current_theo_weights
  # Combine list into dataframe

Stay tuned for the next part in which Kris will demonstrate how to make a data frame of randomly generated prices and weights.

Visit Robot Wealth to download the complete R script:

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from Robot Wealth and is being posted with permission from Robot Wealth. The views expressed in this material are solely those of the author and/or Robot Wealth and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.

trading top