Search code examples
rdata-extractionback-testing

backtest package R extracting returns from object


I would like to extract the returns from the backtest package which are according the to the manual stored within a 5 dimensional array called 'results')

This is the backtest package:

https://cran.r-project.org/web/packages/backtest/backtest.pdf

A simple example looks like this:

library(backtest)
data(starmine)
bt <- backtest(starmine, in.var = c("smi"),
           ret.var = "ret.0.1.m", date.var = "date",
           id.var = "id", buckets = 10,
           natural = TRUE, by.period = TRUE)
summary(bt)

When you run the summary command, it will print out the return series for each decile. I would like to extract those into a dataframe that I can use for further analysis.

Does someone know, how I can access the return series or extract it?


Solution

  • The bt object is an object with class backtest (which we see from class(bt)). The summary() function has a method defined for backtest objects which only prints the information to the screen. If you try to assign the information via stuff <- summary(bt), the stuff object will be NULL. To access the data that summary(bt) prints to the screen, you should use the accessor functions created for that object ( they are described in ?'backtest-class'). These functions include:

    • means()
    • counts()
    • summary()
    • marginals()
    • summaryStats()
    • turnover()

    In order to access the data frame of summary statistics by month printed as the side effect of summary(bt), you can run summaryStats(bt). Please see pages 5-8 of the backtest help files for more information.