To add another possibility: Here is how such a model could be run in the PMwR
package (which I maintain). It seems that sig
holds the desired position. Suppose we have a time series of prices P
.
sig <- c("b", "b", "s", "s", "b", "b", "b", "s",
"s", "b", "s", "b", "s", "s", "b", "s",
"b", "s", "s", "s", "s", "b", "b", "s",
"s", "b", "b", "b", "b", "b", "b", "s",
"b", "b", "b", "b", "b", "b", "b")
P <- cumsum(sample(c(1, -1), replace = TRUE, size = length(sig))) + 100
Then with PMwR::btest
, the backtest could be run as follows:
library("PMwR")
signal <- function(sig)
switch(sig[Time()], "b" = 1, "s" = 0, NULL)
bt <- btest(P, signal, sig = sig)
## initial wealth 0 => final wealth 10
The signal
function maps sig
at every point in time to a position of either 1 or 0. The result, stored in bt
, is a list that stores the details of the backtest.
journal(bt)
## instrument timestamp amount price
## 1 asset 1 2 1 100
## 2 asset 1 4 -1 100
## 3 asset 1 6 1 98
## 4 asset 1 9 -1 101
## 5 asset 1 11 1 101
## [....]
plot(NAVseries(bt))
## etc.
b
ands
signals into1
for long,-1
for short, and0
for do nothing... and then multiplying them by the returns $\endgroup$ – Rime Oct 7 '15 at 18:31