I am trying to find the maximal and the second largest value during a 6 months interval. I am using runMax to find the first value but I can't figure out how to do for the second one. Here's my code so far:
library(quantmod)
library(TTR)
getSymbols("GOOGL")
GOOGL_mo<-to.monthly(GOOGL)#to get monthly data
GOOGL_mo$Max_6mo<-runMax(GOOGL.High, 6)#add a column with the max value during a 6 months period
I would like to add another column with the second largest value to have something like this:
Date Open High Low Close Volume Max6mo 2ndMax6m0 Oct 2016 802.55 839.00 796.23 809.90 35391730 839.00 819.06 Nov 2016 810.87 816.04 743.59 775.88 48353316 839.00 819.06 Dec 2016 778.55 824.30 753.36 792.45 34356689 839.00 824.00 Jan 2017 800.62 867.00 796.89 820.19 36840255 867.00 839.00 Feb 2017 824.00 853.79 812.05 844.93 26492197 867.00 853.79 Mar 2017 851.38 874.42 824.30 847.80 34553208 874.42 867.00 Apr 2017 848.75 935.90 834.60 924.52 28721553 935.90 874.42 May 2017 924.15 965.90 920.80 942.17 21302485 965.90 935.90
Any idea?
library(quantmod)
library(TTR)
getSymbols("GOOG",src="google")
GOOG <- to.monthly(GOOG)
thing <- data.frame(max1 = rep(NA, 5), max2 = rep(NA, 5))
for (x in 1:(nrow(GOOG)-5)) {
max1 <- max(GOOG[x:(x+5), "GOOG.High"])
max2 <- max(GOOG$GOOG.High[x:(x+5)][GOOG$GOOG.High[x:(x+5)] != max1])
thing <- rbind(thing, data.frame(max1, max2))
}
GOOG <- cbind(data.frame(GOOG), thing)