Setting up, Analyzing and Evaluating Options

    In the last post on options, we performed some elementary Profit/Loss or payoff calculations, using the bid/ask prices or options quotes available from Yahoo Finance or CBOE for an ETF such as the SPY.  A simple but very powerful program was also coded to evaluate the payoffs for any strategy, however complex one could imagine that to be.

Options are much more complex than the straightforward equity or ETF trades.  For starters, we have a plethora of expiration dates to pick from, ranging all the way from a few days out to a year or so.  Then there are multiple strike prices to consider, as well as whether its a call or put type, and whether one is buying or selling to open.

This post will address these matters and provides detailed code that will help in setting up and analyzing the potential of the trade. Of course, most brokerage houses provide all kinds of tools to also assist in selecting an appropriate strategy.  For the most part, they are all based on what is being described below.

Several snippets of code are being provided in the zip file above rather than inserting them into this post;  they can be downloaded from links shown.  Because of WordPress limitations, you will need to copy and paste contents into a local file after it opens in a New Tab. Also sample quote data from CBOE has also been included and can be used to test any strategies.  Quotes data from the CBOE site can also be downloaded separately  and stored in the same directory location as the R programs themselves.

      The code is in the form a zip file that can downloaded into a directory.  It contains the following snippets

  •       Defaults
  •       Some strategy definitions  
  •      Common Options functions
  •      Sample Quotes Data previously downloaded from CBOE

    The strategy definitions piece of code has half dozen or so strategies defined in it.  It is very easy to add any other strategy that one can dream up.  There is no limit to the number of strategies that one can store in the inventory of strategies.  By pulling this in, and selecting the strategy of interest, as noted by the index number “[[n]]” one can analyze profit payoff charts and strike/premium combinations for that strategy.

    To illustrate the range of outcomes that are possible, we will look at a couple of strategies, one simple and the other a little more complex. The simple one is what’s known as a Long Straddle. The definition that  appears in the provided code is given as follows:

####
  specStrategy <- list()
  specStrategy$name = “Long Straddle”
  legsTrade <- list(ctrl = c(1,2), fml = “G”,nbrStrikes = 4)
  legsTrade$trades[[1]]  =  list(name = “Buy Call”moneyX = “ITM”lotsize = 100rangeStrike = c(0.1150.15))
  legsTrade$trades[[2]]  =  list(name = “Buy Put”moneyX = “ATM”lotsize = 100rangeStrike = 1)
  specStrategy$legs  = legsTrade
  stratList[[3]] = specStrategy
   
     Notice that the type of option, i.e., Buy Call etc., is specified, along with other parameters. At this point of time, we will only be concerned with the “moneyX” and the lotsize parameters.  The moneyX specifies whether the option is to be traded at ATM, OTM or ITM, that is to say, At/Out of/or In the Money as it relates to current market price of the underlying instrument.  In the case above, the Buy Call is at an In the Money condition, whereas the Buy Put sits right At The Money, meaning market Price.  Lotsize for most strategies will be set at 100 although for more complex ones where there are multiple stages, lotsize may be set at some fraction of 100.
 
         The driver program is shown below. The code that has been referred to above, such as Defaults, Strategy Definitions must be downloaded into the same directory and named as shown, e.g., “/OptionsDefaults.R” and so on. It is assumed that RStudio is being used to run these.
       Note how the Long Straddle strategy has been picked by using index [[3]].  A couple of other points to note, i.e., options expire on the third Friday, so we have compiled list of the forthcoming 3rd Fridays and will key on that to get specific quotes. Similarly we will use the CBOE downloaded quotes instead of Yahoo for the test – these can be downloaded at any time for any other ticker of interest – we have used SPY as the underlying instrument here.
 
###############################################
###   Options  Driver in R
###
###   Uses predefined common functions
#### #########################################
thisdir = dirname(rstudioapi::getSourceEditorContext()$path)
source(paste0(thisdir,“/OptionsDefaults.R”))
source(paste0(thisdir,“/OptionsStratDefinitions.R”))
source(paste0(thisdir,“/CommonOptionsFunctions.R”))
###############
####   Override any defaults here
PERMLEVEL = 4
###############
basicTypes=c(“Buy Put”“Buy Call”“Sell Put ““Sell Call”)
yrs=c(2020,2021)
friDates = get3rdFridays(yrs
quotesData <- getOptQuotes(list(yrs=yrs,  ticker = “SPY”fri = friDatessource = “CBOE”))  ## source = “CBOE”  “Yahoo”
rawData  =  quotesData$rawData
allQuotes = quotesData$allQuotes  
#mktPrice = fromJSON(quotesData[[1]])$optionChain$result$quote$regularMarketPrice  
mktPrice = as.numeric(quotesData$mktPrice )
##pickCols = c(“type”, “strike”, “openInterest”, “lastPrice”, “bid”, “ask”, “impliedVolatility”)
## allQuotes = allQuotes[,pickCols]
#####################################
###   get current directory of script
stratList = initstrats()
specStrategy = stratList[[3]] #<<< Long Straddle
#####    Fixed strikes vs. auto combinations
###      override default and provide strikes for each leg
###     i.e., if there are 4 legs, then four prices 
###     As many combos needed – just add to list
tradeDefaults$fixedVals = FALSE
fixedStrikes[[1]]  =  c(280304)
fixedStrikes[[2]]  =  c(285305)
fixedStrikes[[3]]  =  c(305280)
fixedStrikes[[4]]  =  c(310285)
fixedStrikes[[5]]  =  c(287295)
####  Now setup the profit vectors and range of prices to examine
PRANGE = tradeDefaults$range  * mktPrice 
p1 = mktPrice  PRANGE
p2 = mktPrice + PRANGE
incr = (p2p1)/500    ##  we will use about 500 points
#  price vector to analyze atExpiry price
atExpiry<-seq(p1,p2by=incr)
optProfit = atExpiry
###   must select option quote out at expiry needed – use value
indxDate = which(difftime(friDatesSys.Date(), units=“days”>= FIRSTEXPIRY)[1]
###   get the quote Slice that corresponds to first out 
qSlice = allQuotes %>% dplyr::filter (dtx == friDates[[indxDate]])          ###   say 3 fri out, if 90 then max 90 days
###   take next month after or any period – make sure its there firstoptGrid
oData = setRTStrategy (specStrategy = specStrategy)
####################################################
###   Now this range of possibilities can be plotted 
library(cowplot)
xyz=lapply(oDatafunction(plotData)
          ShowOptionPL(plotData$payoffstratName = specStrategy$name,  mktPricespecs = plotData$specs ))
##  to control plots across rows & cols; nr = nbr per row
nr = 2nc = 2pr1 = nr*nc
#dev.new()
nbrPlots = (length(xyz%/% pr1##  nbr of plot windows needed
if (nbrPlots < 0)  nbrPlots = 0
frac = length(xyz%% pr1 
#
for (ix in 0:nbrPlots )  {
  if  ( (ix == nbrPlots & frac == 0) )  
    pqr  = xyz[c((ix*pr1+1):length(xyz))]
  else
    pqr =  xyz[c((ix*pr1+1):(pr1*ix + pr1))] 
  print(plot_grid(plotlist= pqr,  nrow=nrncol=nc))   
}
###################################################
 
   The output payoff charts produced by this shows the 4 combinations that we selected via the PERMLEVEL parameter.  This essentially will evaluate payoffs at 4 different strike price combinations for the legs of the strategy.  In this case, since the ATM is always at the ATM, the ITM leg will have the different strike price levels.  The green vertical line is the current market price, the red lines are the different strike prices evaluated.  The value are shown as well at the top of each chart, along with the premium costs associated with them.  For the entire trade, whether the trade was initiated with a net Credit or Debit position is also shown.  In the case of the Long Straggle, since both legs were Buys there is a net cost, i.e., debit position at start.  Red areas denote losses, green profits. We get an immediate feel for the outcome of the trades were the price of asset  to be at that level on date of expiry.   It should be noted that it is not necessary to hold on to option until expiry.  They can always be closed with a countervailing transaction – i.e., if one had opened the trade by buying a call, then this can be closed by selling it to close. Vice versa if one had sold, then it needs to be bought back.  There are other terms e.g., write etc.,
    For example, per the top left hand chart, for our Buy Call at strike 269,  a profit position is encountered only if the price were to rise above 310 or fall below 240 approximately.  The payoff charts show the differences that one can expect with different strike prices, given that premiums will differ.

   We will use the same driver program but this time for another strategy, namely the Condor. However some important points to note.  This Condor strategy has all trades at either ITM or OTM, none at the ATM, meaning that prices to evaluate will vary each combination.  We want to set the combinations to a reasonable minimum, since there are 4 different legs in this strategy. If we left the PERMLEVEL at 4, there would be 4 X 4 X 4 X 4 or 256 different charts – a little too much.  So we will keep at this at 2, giving us 16.  We will see later how one can zero in at some particular strikes of interest by using the tradeDefaults$fixedVals = TRUE feature. 

      The point of this first phase analysis is to reveal what is an acceptable and profitable domain space that can be further explored.  All we did here was to change the driver program updating the parameter for the combinations and to select the proper strategy, i.e.,

          specStrategy = stratList[[2]]

      That was it.  Running this gives the following 16 charts corresponding to the total number of combinations that are being evaluated.  The varying strike prices for each of the legs are shown at the top of each chart.  They are in the same order as the order in which the legs were defined in the strategy.  Note that each of the combinations was established with a net Debit position, because of all the Sells to Open.  The eventual green areas shows the net net profits and the range of prices in which they occur.  The other critical point to note is that losses as represented by the rise in price is unlimited, in that there is no upper limit to the price increase. On the left side of the shaded red areas, the downside is limited to price going to zero, i.e., it cannot fall below this.  Still a large loss nevertheless.  But also a range of expiry prices, where there are indeed profits to be had as denoted by the green areas.

     We can print out the strikes and premiums in tabular form as well.

         Options Strategy Condor  Strikes & Premiums 

|Combo Id |Sell Call ITM |Sell Put OTM |Sell Call OTM |Buy Call OTM |
|:——–|:————-|:————|:————-|:————|
|1        |269 // 2254   |269 // 962   |297 // 551    |297 // 551  |
|2        |254 // 3417   |269 // 962   |297 // 551    |297 // 551  |
|3        |269 // 2254   |254 // 612   |297 // 551    |297 // 551  |
|4        |254 // 3417   |254 // 612   |297 // 551    |297 // 551  |
|5        |269 // 2254   |269 // 962   |311 // 143    |297 // 551  |
|6        |254 // 3417   |269 // 962   |311 // 143    |297 // 551  |
|7        |269 // 2254   |254 // 612   |311 // 143    |297 // 551  |
|8        |254 // 3417   |254 // 612   |311 // 143    |297 // 551  |
|9        |269 // 2254   |269 // 962   |297 // 551    |311 // 143  |
|10       |254 // 3417   |269 // 962   |297 // 551    |311 // 143  |
|11       |269 // 2254   |254 // 612   |297 // 551    |311 // 143  |
|12       |254 // 3417   |254 // 612   |297 // 551    |311 // 143  |
|13       |269 // 2254   |269 // 962   |311 // 143    |311 // 143  |
|14       |254 // 3417   |269 // 962   |311 // 143    |311 // 143  |
|15       |269 // 2254   |254 // 612   |311 // 143    |311 // 143  |
|16       |254 // 3417   |254 // 612   |311 // 143    |311 // 143  |
     To complete this post, we will take a look at some of the defaults, (we have already discussed the PERMALEVEL)
    tradeDefaults$incr = 0.05 ## vary strike prices by this %age
    tradeDefaults$fixedStrikes = NULL ### if fixed strikes provide separately  

    tradeDefaults$range    ###  range over which to evaluate price @ expiry

  The incr parameter determines the incremental %ages of marketPrice to use in fixing strike prices up or down as the case may be in computing payoffs.  Combinations quickly explode so we want to get a good broad view at this point before zeroing in on potential possibilities.

    Setting the fixedStrikes to TRUE, overrides the automatic combinatorial analysis, but instead requires that user provide exact values to test.  Any number of combinations may be provided.

   The evaluation can be run again with custom values exploring regions around the profit space.  Let us select 9 different custom combinations as follows and run the program again.

tradeDefaults$fixedVals =TRUE
fixedStrikes[[1]]  =  c(265270300305)
fixedStrikes[[2]]  =  c(265275300305)
fixedStrikes[[3]]  =  c(265260300305)
fixedStrikes[[4]]  =  c(270270305300)
fixedStrikes[[5]]  =  c(275270310300)
fixedStrikes[[6]]  =  c(265270300305)
fixedStrikes[[7]]  =  c(270280310315)
fixedStrikes[[8]]  =  c(270270295310)
fixedStrikes[[9]]  =  c(265260300305)

     We see the profit region around $4000 which seems to be about the highest we are able to achieve around those strike price combinations.

     Now that some preliminary tools have been established we can get deeper into the arcane world of the so-called Greeks in assessing risk and profitability.

Thanx for reading

82 Comments on “Setting up, Analyzing and Evaluating Options”

  1. Thanks a bunch for sharing this with all of us you actually know what you are talking about! Bookmarked. Please also visit my web site =). We could have a link exchange arrangement between us!

  2. Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  3. You really make it appear so easy along with your presentation however I in finding this matter to be actually something that I believe I’d by no means understand. It kind of feels too complex and extremely huge for me. I’m taking a look forward to your subsequent put up, I?¦ll try to get the cling of it!

  4. Aw, this was a very nice post. In idea I wish to put in writing like this moreover – taking time and actual effort to make an excellent article… however what can I say… I procrastinate alot and on no account seem to get something done.

  5. I want to show my appreciation to you for bailing me out of this trouble. Right after researching throughout the online world and finding tips which were not pleasant, I thought my entire life was over. Living devoid of the approaches to the problems you’ve resolved by means of this posting is a serious case, and those which could have badly affected my career if I had not discovered your web page. Your own personal expertise and kindness in maneuvering all the pieces was helpful. I don’t know what I would have done if I had not discovered such a thing like this. It’s possible to at this time look forward to my future. Thanks very much for this high quality and sensible guide. I won’t hesitate to propose your web page to anyone who should receive support on this subject.

  6. Appreciating the time and energy you put into your blog and in depth information you offer. It’s awesome to come across a blog every once in a while that isn’t the same old rehashed information. Wonderful read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  7. Yesterday, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is totally off topic but I had to share it with someone!

  8. What Is Sugar Defender? Sugar Defender is a natural blood sugar support formula created by Tom Green. It is based on scientific breakthroughs and clinical studies.

  9. Мы рекомендуем посетить веб-сайт https://telegra.ph/Sekrety-uspeshnogo-ulova-znachenie-pravilnogo-vybora-i-ispolzovaniya-oborudovaniya-pri-rybalke-03-31.

    Кроме того, не забудьте добавить сайт в закладки: [url=https://telegra.ph/Sekrety-uspeshnogo-ulova-znachenie-pravilnogo-vybora-i-ispolzovaniya-oborudovaniya-pri-rybalke-03-31]https://telegra.ph/Sekrety-uspeshnogo-ulova-znachenie-pravilnogo-vybora-i-ispolzovaniya-oborudovaniya-pri-rybalke-03-31[/url]

  10. Мы рекомендуем посетить веб-сайт https://telegra.ph/Instrumenty-dlya-udovolstviya-pochemu-kachestvennoe-rybolovnoe-oborudovanie—zalog-uspeshnoj-i-komfortnoj-rybalki-03-31.

    Кроме того, не забудьте добавить сайт в закладки: [url=https://telegra.ph/Instrumenty-dlya-udovolstviya-pochemu-kachestvennoe-rybolovnoe-oborudovanie—zalog-uspeshnoj-i-komfortnoj-rybalki-03-31]https://telegra.ph/Instrumenty-dlya-udovolstviya-pochemu-kachestvennoe-rybolovnoe-oborudovanie—zalog-uspeshnoj-i-komfortnoj-rybalki-03-31[/url]

  11. Слоты и онлайн-игры в казино способны разнообразить жизнь человека. Важно только правильно выбрать площадку — она должна быстро и честно выплачивать выигрыши, надежно хранить персональные данные клиентов, предлагать большой ассортимент развлечений и интересную бонусную программу. Важную роль играют также наличие адаптированной мобильной версии и приложений. https://enic-kazakhstan.kz/

  12. Hello, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam remarks? If so how do you reduce it, any plugin or anything you can advise? I get so much lately it’s driving me insane so any assistance is very much appreciated.

  13. Whats up very cool website!! Guy .. Excellent .. Amazing .. I’ll bookmark your site and take the feeds additionallyKI am happy to seek out numerous useful information here within the put up, we’d like work out more techniques in this regard, thank you for sharing. . . . . .

  14. Блог [url=https://akpp-korobka.blogspot.com/]https://akpp-korobka.blogspot.com/[/url] посвящен ключевым аспектам технического ухода автоматических коробок передач (АКПП) в транспортных средствах. Он подчеркивает значимость АКПП в реализации надежной передачи мощности от двигателя к колесам, что является ключевым в эффективности автомобиля. Сайт обсуждает необходимость квалифицированной диагностики АКПП для устранения проблем, что может сэкономить время и деньги. Также затрагиваются основные аспекты регулярного обслуживания АКПП, включая замену масла, проверку на утечки и замену фильтров, для гарантии долговечности трансмиссионной системы. Более подробную информацию найдете на блог по адресу https://akpp-korobka.blogspot.com/.

  15. Блог [url=https://citatystatusy.blogspot.com/]https://citatystatusy.blogspot.com/[/url] является ресурсом, посвященным мотивирующим цитатам и статусам. На сайте представлены цитаты, направленные на обогащение жизненного опыта через мудрые слова. Этот ресурс подчеркивает важность позитивного восприятия жизни, помогая найти счастье в мелочах.

    Не забудьте страницу на блог в закладки: https://citatystatusy.blogspot.com/

  16. На нашем сайте [url=https://citaty12345.blogspot.com/]https://citaty12345.blogspot.com/[/url] вы сможете обнаружить вдохновляющую коллекцию цитат, которые способны оказать глубокое влияние на вашу жизнь. Цитаты от великих мыслителей собраны здесь, чтобы предоставить вам свежие взгляды для личностного роста.

    Наш блог создан не только для любителей литературы и философии, но и для всех, кто желает найти познания в словах. Здесь вы найдете цитаты на множество темы: от жизненной мудрости до глубоких мыслей. Каждая цитата – это глубокое послание, которое имеет силу повлиять на ваш жизненный путь.

    Мы аккуратно выбираем цитаты, чтобы они были релевантными. Наши материалы позволяют вам окунуться в мир красоты слов, открывая новые возможности. Мы верим, что правильно подобранные слова могут быть источником вдохновения.

    Подписывайтесь нашего блога https://citaty12345.blogspot.com/ и открывайте для себя новые цитаты ежедневно. Вне зависимости от того, нуждаетесь ли вы мотивацию или искренне желаете вдохновляться красотой слов, наш блог подарит вам всё то, что вам нужно. Разрешите этим цитатам войти в вашего постоянного вдохновения.

  17. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but other than that, this is excellent blog. An excellent read. I’ll certainly be back.

  18. Our partners have opened a new site vipeth.site I personally supervise the work of employees. In honor of the new year we are giving new users a registration bonus with promo code: NEWUSER24. It gives +70% on the first deposit. Soon we will introduce new artificial intelligence for better work.

  19. obviously like your web-site however you need to test the spelling on quite a few of your posts. Several of them are rife with spelling issues and I in finding it very bothersome to tell the reality then again I will definitely come back again.

  20. Le monde des paris en ligne n’a jamais été aussi passionnant qu’avec le code promo 1xbet. Bonus promotionnel 1xbet Si vous recherchez la meilleure expérience de jeu, vous ne pouvez pas manquer l’opportunité d’utiliser le code promotionnel 1xbet. Avec le code promotionnel 1xbet, vous aurez accès à des offres et bonus exclusifs qui rendront vos paris encore plus excitants. Que vous soyez intéressé par les paris sportifs ou les jeux de casino, le code promotionnel 1xbet vous fera bénéficier d’avantages supplémentaires pour augmenter vos chances de gagner. Ne manquez pas cette opportunité unique de profiter au maximum de vos paris en ligne avec le code promotionnel 1xbet. Inscrivez-vous aujourd’hui et découvrez pourquoi nous sommes le leader dans le monde des paris en ligne grâce à notre code promotionnel exclusif !

  21. El mundo de las apuestas en línea nunca ha sido tan emocionante como con el código promocional 1xbet. Si buscas la mejor experiencia de juego, no puedes dejar pasar la oportunidad de utilizar el código promocional 1xbet. código promocional de bonificación 1xbet Con el código promocional 1xbet, obtendrás acceso a ofertas y bonificaciones exclusivas que harán que tus apuestas sean aún más emocionantes. Ya sea que estés interesado en apuestas deportivas o juegos de casino, el código promocional 1xbet te brindará ventajas adicionales para aumentar tus posibilidades de ganar. No pierdas esta oportunidad única de aprovechar al máximo tus apuestas en línea con el código promocional 1xbet. ¡Regístrate hoy mismo y descubre por qué somos el líder en el mundo de las apuestas en línea con nuestro código promocional exclusivo!

  22. 1xBet. Бонус на 2023 год. Промокод для регистрации. Ставки на спорт. До 32500 руб. 1XFREE777. Бесплатные промокоды 1xBet при регистрации 2023. промокод 1xbetПолучить бонус на сумму 32500 рублей могут все новые участники клуба. Регистрируйте аккаунт по электронной почте или через привязку аккаунтов популярных социальных сетей и получайте бонусом до 32500 рублей на первый депозит. Для зачисления бонусов необходимо пополнить счет с банковской карты или электронного кошелька, не забыв при этом указать рабочий промокод 1XFREE777. Для того чтобы бонус стал доступен к снятию необходимо выполнить простое условие. Выбирайте любое событие, на которое принимаются ставки с коэффициентом от 1.4 и выше.

  23. Hi! This is kind of off topic but I need some help from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to start. Do you have any tips or suggestions? Many thanks

  24. Heya i am for the primary time here. I found this board and I in finding It truly helpful & it helped me out a lot. I’m hoping to give one thing again and aid others such as you aided me.

  25. 👉 $5,000 FREE EXCHANGE BONUSES BELOW 📈 👉 PlaseFuture FREE $3,000 BONUS + 0% Maker Fees 📈 + PROMOCODE FOR NEWS USERS OF THE EXCHANGE 👉 [M0345IHZFN] — 0.01 BTC 👉 site: https://buycrypto.in.net Our site is a secure platform that makes it easy to buy, sell, and store cryptocurrency like Bitcoin, Ethereum, and More. We are available in over 30 countries worldwide.

Leave a Reply

Your email address will not be published. Required fields are marked *