I'd like to calculate the 1st quartile of numbers in a column that shows the Gap. In this column there are both positive and negative numbers, so I'd like to filter out only positive numbers and calculate the quartile (1st) but I'm having problems with the function (see code below)
#I have tried a function with ">0" and "0.25" to get the 1st quartile but somehow is failing and I don't know why.
library(quantmod)
Symbols <- c("FB","AAPL","AMZN","NFLX","GOOG")
getSymbols(Symbols,from="2018-06-01")
stock_data = sapply(.GlobalEnv, is.xts)
all_stocks <- do.call(list, mget(names(stock_data)[stock_data]))
# Calculate gap
Gap_function <- function(x) {
stock_name <- stringi::stri_extract(names(x)[1], regex = "^[A-Z]+")
stock_name <- paste0(stock_name, ".Gap")
column_names <- c(names(x), stock_name)
x$rgap <- quantmod::Op(x) - lag(quantmod::Cl(x))
x <- setNames(x, column_names)
return(x)
}
all_stocks <- lapply(all_stocks, Gap_function)
# Calculate 1st Quantile of positive numbers in .GAP column, currently it is not working.
# I don't know how to indicate to use only positive numbers (>0) and (1st quartile 0.25)
Quartile1_function <- function(x) {
stock_name <- stringi::stri_extract(names(x)[1], regex = "^[A-Z]+")
stock_name <- paste0(stock_name, ".GapQ1")
column_names <- c(names(x), stock_name)
x$quartile1 <- (quantile(x,na.rm=TRUE [,grep(".Gap" >0, colnames(x))], 0.25))
x <- setNames(x, column_names)
return(x)
}
all_stocks <- lapply(all_stocks, Quartile1_function)
#The desired result is to get a 1st quartile of .Gap column (taking only positive numbers) in a new column =(7.609986)
#If you run this code you will get AMZN quartiles only for positive numbers in the .Gap column. but I don't know what is failing to get a function to do this for all stocks.
quantile(all_stocks$AMZN$AMZN.Gap[which(all_stocks$AMZN$AMZN.Gap >0)])
0% 25% 50% 75% 100%
0.060059 7.609986 11.709961 21.319946 88.640015