Optimization and Walk-Forward with
PortfolioTesteR
knitr::opts_chunk$set(collapse=TRUE, comment="#>", fig.width=7, fig.height=5, dpi=96, cache=FALSE, message=FALSE, warning=FALSE)
set.seed(1)
heavy <- identical(Sys.getenv("NOT_CRAN"), "true")
library(PortfolioTesteR)
data(sample_prices_weekly)
# ---- Grid optimization ----
builder_opt <- function(prices, params, ...) {
sel <- filter_top_n(calc_momentum(prices, params$lookback), params$n_top)
weight_equally(sel)
}
grid_opt <- if (heavy) {
list(lookback = seq(6, 26, by = 2), n_top = c(5, 10, 15))
} else {
list(lookback = c(8, 12, 26), n_top = c(5, 10))
}
opt <- run_param_grid(
prices = sample_prices_weekly,
grid = grid_opt,
builder = builder_opt,
metric = NULL, # defaults to metric_sharpe()
name_prefix = "MOM",
verbose = FALSE,
light_mode = TRUE,
precompute_returns = TRUE
)
plot(opt, type = "line", params = "lookback")

# ---- Walk-forward ----
builder_wf <- function(prices, params, ...) {
weight_equally(filter_top_n(calc_momentum(prices, params$lookback), params$n_top))
}
grid_wf <- if (heavy) {
list(lookback = c(8, 12, 26, 40), n_top = c(5, 10, 15))
} else {
list(lookback = c(8, 12), n_top = c(5, 10))
}
wf <- run_walk_forward(
prices = sample_prices_weekly,
grid = grid_wf,
builder = builder_wf,
metric = NULL, # defaults to metric_sharpe()
is_periods = 52,
oos_periods = 26,
step = 26,
verbose = FALSE,
light_mode = TRUE,
precompute_all = TRUE,
builder_args = list()
)
plot(wf, type = "parameters")

plot(wf, type = "is_oos", metric = "OOS_Score")

plot(wf, type = "equity")

## R version 4.2.1 (2022-06-23 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 26100)
##
## Matrix products: default
##
## locale:
## [1] LC_COLLATE=C
## [2] LC_CTYPE=English_United Kingdom.utf8
## [3] LC_MONETARY=English_United Kingdom.utf8
## [4] LC_NUMERIC=C
## [5] LC_TIME=English_United Kingdom.utf8
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] PortfolioTesteR_0.1.2
##
## loaded via a namespace (and not attached):
## [1] lattice_0.20-45 zoo_1.8-12 digest_0.6.37 grid_4.2.1
## [5] R6_2.6.1 lifecycle_1.0.4 jsonlite_2.0.0 evaluate_1.0.5
## [9] cachem_1.1.0 rlang_1.1.4 cli_3.6.1 curl_7.0.0
## [13] data.table_1.16.0 rstudioapi_0.17.1 TTR_0.24.4 jquerylib_0.1.4
## [17] bslib_0.9.0 xts_0.14.1 rmarkdown_2.29 tools_4.2.1
## [21] xfun_0.53 yaml_2.3.10 fastmap_1.2.0 compiler_4.2.1
## [25] htmltools_0.5.8.1 knitr_1.50 sass_0.4.10