Question

I've got a data series which is of the form date. open high low and close (prices). I want to create local maxima and minima for the close column of the data. I further want to buy after 2 days of local minima @ close and sell after two days of local maxima @ close. I further want to calculate the profit and loss for the same. the code for the same is as under.

require(quantmod)
tckr1<-"^NSEI" 
start<-Sys.Date()-200
end<- format(Sys.Date(),"%Y-%m-%d") # yyyy-mm-dd 
getSymbols(tckr1, from=start, to=end) 
data<- NSEI$NSEI.Close
data$n <- 1:nrow(data)
data$z <- ZigZag(data$NSEI.Close , change = 2 , percent = T)
data$level<- data[c(findPeaks(data$z) , findValleys(data$z)) - 1 , ]
data$NSEI.Close.1<- NULL
data$n.1<- NULL
data$trade<- lag(data$level,2)

Now i need the data column to tell me when to buy and sell by +1 and -1 and also to calculate the profit and loss for the same. In this above mentioned data i will buy when n= 29 @ 5719.70 and when n=36 @ 5851.20 etc.

regards Ashish

Was it helpful?

Solution

require(quantmod)
tckr1<-"^NSEI" 
start<-Sys.Date()-200
end<- format(Sys.Date(),"%Y-%m-%d") # yyyy-mm-dd 
getSymbols(tckr1, from=start, to=end) 
data<- NSEI$NSEI.Close
data$n <- 1:nrow(data)
data$z <- ZigZag(data$NSEI.Close , change = 2 , percent = T)
data$level<- data[c(findPeaks(data$z) , findValleys(data$z)) - 1 , ]
ex <- data[c(findPeaks(data$z) , findValleys(data$z)) - 1 , ]
data$trade<- data$level
data$trade[is.na(data$level)]<- 0
data$trade[data$trade!=0,]<- c(1,-1)

This way you can get your trade column +/- 1.

OTHER TIPS

Just to provide an answer to the final "P/L" curve part of the question, the below code will generate an equity curve based upon ANUP's code,

require(PerformanceAnalytics)
ex <- data[c(findPeaks(data$z) , findValleys(data$z)) - 1 , ]
returns <- ROC(ex$NSEI.Close)*(Lag(ex$trade))
equity <- exp(cumsum(na.trim(returns)))
charts.PerformanceSummary(equity)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top