r - 按时间段查找 quantmod 中的第二高值



我试图在 6 个月的间隔内找到最大值和第二大最大值。我正在使用runMax来查找第一个值,但我不知道如何为第二个值做。这是我到目前为止的代码:

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

我想添加另一列具有第二大值的列,如下所示:

日期 开盘 高 低 收盘 成交量 最大6个月 2nd最大6m0 2016年10月 802.55 839.00 796.23 809.90 35391730 839.00 819.06 2016年11月 810.87 816.04 743.59 775.88 48353316 839.00 819.06 12月 2016 778.55 824.30 753.36 792.45 34356689 839.00 824.00 2017年1月 800.62 867.00 796.89 820.19 36840255 867.00 839.00 2017年2月 824.00 853.79 812.05 844.93 26492197 867.00 853.79 2017年3月 851.38 874.42 824.30 847.80 34553208 874.42 867.00 2017年4月 848.75 935.90 834.60 924.52 28721553 935.90 874.42 五月 2017 924.15 965.90 920.80 942.17 21302485 965.90 935.90

知道吗?

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)

这里有一种方法可以做到这一点:

df <- read.table(header=T, text="
Open      High     Low        Close     Volume   Max6mo  2ndMax6m0
Aug2016    786.67    813.88   785.04     789.85    28857075 813.88  803.94
Sep2016    791.98    819.06   783.50     804.06    31574466 819.06  813.88
Oct2016    802.55    839.00   796.23     809.90    35391730 839.00  819.06
Nov2016    810.87    816.04   743.59     775.88    48353316 839.00  819.06
Dec2016    778.55    824.30   753.36     792.45    34356689 839.00  824.00
Jan2017    800.62    867.00   796.89     820.19    36840255 867.00  839.00
Feb2017    824.00    853.79   812.05     844.93    26492197 867.00  853.79
Mar2017    851.38    874.42   824.30     847.80    34553208 874.42  867.00
Apr2017    848.75    935.90   834.60     924.52    28721553 935.90  874.42
May2017    924.15    965.90   920.80     942.17    21302485 965.90  935.90")
cbind(
df, 
rollapplyr(df$High, 6, function(x) 
setNames(sort(x, decreasing = T)[1:2], c("a","b")), fill = NA)
)
#           Open   High    Low  Close   Volume Max6mo X2ndMax6m0      a      b
# Aug2016 786.67 813.88 785.04 789.85 28857075 813.88     803.94     NA     NA
# Sep2016 791.98 819.06 783.50 804.06 31574466 819.06     813.88     NA     NA
# Oct2016 802.55 839.00 796.23 809.90 35391730 839.00     819.06     NA     NA
# Nov2016 810.87 816.04 743.59 775.88 48353316 839.00     819.06     NA     NA
# Dec2016 778.55 824.30 753.36 792.45 34356689 839.00     824.00     NA     NA
# Jan2017 800.62 867.00 796.89 820.19 36840255 867.00     839.00 867.00 839.00
# Feb2017 824.00 853.79 812.05 844.93 26492197 867.00     853.79 867.00 853.79
# Mar2017 851.38 874.42 824.30 847.80 34553208 874.42     867.00 874.42 867.00
# Apr2017 848.75 935.90 834.60 924.52 28721553 935.90     874.42 935.90 874.42

最新更新