The goal is to find the closest strike price from an option chain. This is as far as I have gotten.
library(quantmod)
tickers = c("AAPL", "MSFT", "GS")
price = getQuote(tickers)
chains = lapply(tickers, getOptionChain, exp = "2019-01-25")
calls = lapply(chains, function(x) x$calls)
##I was thinking to use a function such as
which.min(abs(calls - price))
However I am not to sure in how to put this into lapply or if there is a better alternative. Price is a data frame and calls is a list. Thanks in advance
To get the corresponding rows we may use
Map(function(cl, p) cl[which.min(abs(p - cl$Strike)), ], calls, price$Last)
# [[1]]
# Strike Last Chg Bid Ask Vol OI
# AAPL190104C00148000 148 0.3 0.21 0.24 0.42 43235 4344
#
# [[2]]
# Strike Last Chg Bid Ask Vol OI
# MSFT190104C00102000 102 0.04 0 0.02 0.09 6397 3250
#
# [[3]]
# Strike Last Chg Bid Ask Vol OI
# GS190104C00175000 175 0.25 0.13 0 0.25 2624 678
where
price$Last
# [1] 148.26 101.93 175.05
In this case lapply
is not the best option since we have to work with two objects at the same time: price
and calls
. In that case mapply
and Map
do the job, with Map
being the same as mapply
with SIMPLIFY = FALSE
.
So, we go over both calls
and price$Last
simultaneously and apply
function(cl, p) cl[which.min(abs(p - cl$Strike)), ]