Find running minimum and Max in R

假装没事ソ 提交于 2021-02-04 08:28:04

问题


I have a vector of stock prices throughout the day:

> head(bidStock)
         [,1]
[1,] 1179.754
[2,] 1178.000
[3,] 1178.438
[4,] 1178.367
[5,] 1178.830
[6,] 1178.830

I want to find two things. As I the algorithm goes through the day. I want it to find how far the current point is from the historical minimum and maxim throughout the day.

There is a function called 'mdd' in the 'stocks' package which finds the maximum draw down throughout the day (i.e. the lowest value which corresponds to a point being the farthest from the historical maximum of the day). However, I don't want just the lowest value, I want a vector. I have come up with the code below to do that. However, I need a way to do with how far a point is from the running historical minimum as well.

    mddVec<-rep(NA,1)
   for (i in 1: length(bidStock)){
     mddVec[i]<-mdd(bidStock[1:i])
     }

Finally, typical price is calculated by (max(day) + min(day) + closing price)/3. Is there a way to make that work like a running average using running historical min and max throughout the day.

Thanks for your help in advance


回答1:


You just need cummmin and cummax for cumulative minima and maxima, from which you can calculate how far off-minimum and maximum you are, and whatever permutations you like:

# in base R, as data.frame
df <- data.frame(price = bidStock, 
                 min = cummin(bidStock), 
                 max = cummax(bidStock))
df$off_min <- df$price - df$min
df$off_max <- df$price - df$max
df$typical_price <- (df$price + df$min + df$max) / 3    # using price for closing price

df
##      price      min      max off_min off_max typical_price
## 1 1179.754 1179.754 1179.754   0.000   0.000      1179.754
## 2 1178.000 1178.000 1179.754   0.000  -1.754      1178.585
## 3 1178.438 1178.000 1179.754   0.438  -1.316      1178.731
## 4 1178.367 1178.000 1179.754   0.367  -1.387      1178.707
## 5 1178.830 1178.000 1179.754   0.830  -0.924      1178.861
## 6 1178.830 1178.000 1179.754   0.830  -0.924      1178.861

# or in dplyr
library(dplyr)

data.frame(price = bidStock) %>% 
    mutate(min = cummin(bidStock), 
           max = cummax(bidStock), 
           off_min = price - min, 
           off_max = price - max,
           typical_price = (price + min + max) / 3)
##      price      min      max off_min off_max typical_price
## 1 1179.754 1179.754 1179.754   0.000   0.000      1179.754
## 2 1178.000 1178.000 1179.754   0.000  -1.754      1178.585
## 3 1178.438 1178.000 1179.754   0.438  -1.316      1178.731
## 4 1178.367 1178.000 1179.754   0.367  -1.387      1178.707
## 5 1178.830 1178.000 1179.754   0.830  -0.924      1178.861
## 6 1178.830 1178.000 1179.754   0.830  -0.924      1178.861


来源:https://stackoverflow.com/questions/38405025/find-running-minimum-and-max-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!