Pergunta

After studying the vectorization methods used in the two links below, I've attempted to create a simple trading strategy template (code shown below) that can be vectorized in R for better speed vs a loop-based structure. I'm having difficulty vectorizing because variable state must be maintained and built upon such as:

1) The signals I'm using are not mutually exclusive for long and short (as in a simplistic MA crossover system).

2) Once triggered, the signal can wander until it gets an opposing indication (such as an RSI go short above 80, go long below 20 type system).

3) Positions are held for multiple periods so it isn't a case of enter on every signal or exit after a signal is false (I wish to be able to only enter once as in a Stop and Reverse or SAR system).

I consider this to be a simple example system but it is a bit more complex than the examples listed here:

http://blog.fosstrading.com/2011/03/how-to-backtest-strategy-in-r.html

Cumulative Return in Trading Strategy Test

System logic summary: The system starts flat then goes long (short) at the ask (bid) price when zscore is below (above) -2 (2). The system keeps track of performance statistics such as 'trades', 'wins', closed P&L (others omitted for simplicity). The system also keeps a running 'equity' for plotting after a system run.

# assume vectors bid, ask, and zscore containing those price series respectively
# pos = current position where 1 == long, -1 == short, 0 == flat
# entryP = entry price, pnl = open pnl, cpnl = closed pnl
pos = 0; entryP = 0.0; pnl = 0; cpnl = 0; trades = 0; wins = 0
ub = length(bid)
equity = rep(0, ub)
for (i in 10000:ub) {
pnl = 0
if (pos > 0) pnl = bid[i] - entryP
if (pos < 0) pnl = entryP - ask[i]
if (zscore[i] > 2.0 && pos != -1) { # go short
    if (pos > 0) { # exit long and record pnl
        cpnl = cpnl + pnl
        if (pnl > 0) wins = wins + 1
        trades = trades + 1
        pnl = 0
    }
    pos = -1
    entryP = bid[i]
} else if (zscore[i] < -2.0 && pos != 1) { # go long
    if (pos < 0) { # exit short and record pnl
        cpnl = cpnl + pnl
        if (pnl > 0) wins = wins + 1
        trades = trades + 1
        pnl = 0
    }
    pos = 1
        entryP = ask[i]
    }

    equity[i] = cpnl + pnl
}
# assume close-out of final position
cpnl = cpnl + pnl
if (pnl > 0) wins = wins + 1
if (pos != 0) trades = trades + 1
# plot equity chart and report performance stats
plot(equity, t='l', lwd=3)
cpnl;trades; cpnl / trades; wins/trades

Is it possible to vectorize this simple loop-based mean reversion trading system in R?

Foi útil?

Solução

" I'm having difficulty vectorizing because variable state must be maintained "

That sums it all. You can't avoid loops if your result in any iteration depends on previous iterations.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top