1

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

Ashish Jalan
  • 181
  • 8
  • This question doesn't appear to be reproducible. (See [this post](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example).) What libraries are you using? Also please show us the code you have written to create the columns you mention. It doesn't matter if the code doesn't work, but it helps to see what you have done. – SlowLearner Aug 10 '13 at 12:16
  • i've done the required changes. I'm unable to replace numbers from data$trade by +1 and -1. – Ashish Jalan Aug 10 '13 at 19:22
  • 1
    also tried data$trade<- data[c(replace(data$trade, findPeaks(data$trade),1),replace(data$trade, (data$trade)!=0),0), replace(data$trade, findValleys(data$trade),1),0)-1,] getting some errors. – Ashish Jalan Aug 10 '13 at 20:58

2 Answers2

1
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.

Ashish Jalan
  • 181
  • 8
ANUP
  • 98
  • 1
  • 8
1

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)
Hao
  • 59
  • 6