lokheart
lokheart

Reputation: 24675

Generate signal for stock price reaching record high

I have created a dummy stock price xts object as below:

temp <- data.frame(date=as.Date("2010-01-01")+(0:99))
set.seed(1)
temp[,"price"] <- sample(1:100,nrow(temp),replace=TRUE)
# temp <- as.xts(temp[,"price"],order.by=temp[,"date"])

temp[,"record_hi"] <- FALSE

for (loop in (2:nrow(temp))) {
  if (all(temp[loop,"price"]>=temp[1:loop,"price"])) {
    temp[loop,"record_hi"] <- TRUE
  }
}

I want to create a signal so that once the price has reached record high, I did similar things before using for-loop and just realized that I am so dumb for not aware xts gives the same output much faster.

How can I create such signal using xts?

Upvotes: 2

Views: 81

Answers (1)

Roland
Roland

Reputation: 132706

This only differs in the first line:

temp$record_hi2 <- temp$price == cummax(temp$price)

#           date price record_hi record_hi2
# 1   2010-01-01    27     FALSE       TRUE
# 2   2010-01-02    38      TRUE       TRUE
# 3   2010-01-03    58      TRUE       TRUE
# 4   2010-01-04    91      TRUE       TRUE
# 5   2010-01-05    21     FALSE      FALSE
# 6   2010-01-06    90     FALSE      FALSE
# 7   2010-01-07    95      TRUE       TRUE
# 8   2010-01-08    67     FALSE      FALSE
# 9   2010-01-09    63     FALSE      FALSE
# 10  2010-01-10     7     FALSE      FALSE
# 11  2010-01-11    21     FALSE      FALSE
# 12  2010-01-12    18     FALSE      FALSE
# 13  2010-01-13    69     FALSE      FALSE
# 14  2010-01-14    39     FALSE      FALSE
# 15  2010-01-15    77     FALSE      FALSE
# 16  2010-01-16    50     FALSE      FALSE
# 17  2010-01-17    72     FALSE      FALSE
# 18  2010-01-18   100      TRUE       TRUE
# 19  2010-01-19    39     FALSE      FALSE
# <snip>

Upvotes: 5

Related Questions