Answer the question
In order to leave comments, you need to log in
How to iterate over values in a table without for?
I broke my head in an attempt to solve the problem, I really ask for help.
There is a data table:
date
type
price
exp.price
There is also a vector: a <- c(65000, 55000, 45000, 80000, ...)
It is necessary to run each value of the vector a, performing some actions with the fields of the data (price, exp.price) table, forming a new vector, which consists of the sum of the values of the results of actions with the table parameters for each value of the vector a.
I understand that you need to use apply and others like that, but I’ll never know how.
Answer the question
In order to leave comments, you need to log in
fun <- function(num){здесь функция, которая берет число num и делает что то с data}
result <- mapply(fun,a)
All the same, it doesn’t reach, I’ll try to explain more clearly what is required, because it’s really not clear from what I wrote.
there is a table of options:
opt.type oper strike price.open
CALL buy 66000 800
CALL buy 66000 700
PUT sell 65000 750
...
there is a price vector of the underlying asset:
it is necessary to calculate the profit/loss for each line for each value in the vector of the underlying asset, here is the calculation algorithm one line at a time, with one value of the underlying asset
underline <- seq(40000, 80000, by=500)
if(oper.type == 'BUY' & option.type == 'CALL' & underline <= strike) {
return(-price.open)
}
else if(oper.type == 'BUY' & option.type == 'CALL' & underline > strike) {
return(underline - strike - price.open)
}
else if(oper.type == 'BUY' & option.type == 'PUT' & underline <= strike) {
return(strike - underline - price.open)
}
else if(oper.type == 'BUY' & option.type == 'PUT' & underline > strike) {
return(-price.open)
}
if(oper.type == 'SELL' & option.type == 'CALL' & underline <= strike) {
return(price.open)
}
else if(oper.type == 'SELL' & option.type == 'CALL' & underline > strike) {
return(-(underline - strike - price.open))
}
else if(oper.type == 'SELL' & option.type == 'PUT' & underline <= strike) {
return(-(strike - underline - price.open))
}
else if(oper.type == 'SELL' & option.type == 'PUT' & underline > strike) {
return(price.open)
}
Turn a trading rule into a function. Then just set this function on the data via
apply(data, 1, function(x) {
fun_name(options_data[x, ])
})
Or so
foreach(i=nrow(options_data), .combine=rbind) %do% {
fun_name (options_data[i, ]) %>% as.data.frame(.)
}
And one more thing - rewrite the trading rule using ifelse() functions (instead of basic if {} else {} constructions)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question