I'm really strugling to find a solution here. If you look at the last line of code, you will understand that I want to BUY at next open and SELL 5 days later (x = 5).
The thing is that the xts
index is counting weekends. So for example you'd get index = 1 on friday july 12th... But on monday july 15th, the index = 4. I want it to be equal to 2 which is +1 trading day.
Can I modify the index OR use another method than Cl(SPY)[index(SPY) + x]
in order to get x + 5 trading days ?
Thanks in advance for any hints on this
# Variable d'optimisation
x <- 5
library(quantmod)
# Get data from Yahoo, then adjust
getSymbols("SPY", from = "1990-01-01")
# add RSI3 column
SPY$RSI3 <- RSI(Cl(SPY), n = 3)
# Add buy sig
SPY$buySig <- ifelse(SPY$RSI3 > 90, 1, 0)
# If signal, buy tomorrow at open, sell at close x days later
# PnL Calculation here :
PnL <- ifelse(lag(SPY$buySig) == 1, Cl(SPY)[index(SPY) + x] - Op(SPY), NA)
Use lag
to calculate the Close at +x
days. You may need to change the value of k
to -(x+1)
depending on your actual desired logic (sell 5 days after the signal or 5 days after the position was opened).
SPY$Lag.Cl <- lag(Cl(SPY),-x)
PnL <- lag(SPY$buySig) * (SPY$Lag.Cl - Op(SPY))