0% found this document useful (0 votes)
120 views17 pages

Building A Stock Option Valuation Model With Python Part I

Building a Stock Option Valuation Model with Python Part I

Uploaded by

FabioSantos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
120 views17 pages

Building A Stock Option Valuation Model With Python Part I

Building a Stock Option Valuation Model with Python Part I

Uploaded by

FabioSantos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 17
sanz Burg 2 toc Opn Vena mn pur: Pa by es Une Maan Jacob Linger s2roliowers About [ ] Signin You have 2 tree member-only stories left this month. Sign up for Medium and get an extra one Building a Stock Option Valuation Model with Python: Part I Part |: Accessing the data and creating the payoff distribution Photo by Austin Distelo ‘This is Part I of a two-part post. Part II can be accessed here. eninetunoni@estienbulinevickanbnanate-ree-n pret faa a utr Sept Vater aa tn Py Lge eum In this article, I want to go into a basic model I developed to evaluate options. The general steps involved are to (1) identify the payoff distribution based on stock price changes, (2) identify the probability distribution of the underlying stock’s price changes, (3) calculate the expected value of the option contract based on weighting the payoffs by their respective probabilities. What is an Option? An option is a contract giving you the option to purchase shares of a stock at a specific price in the future. Let’s say that AT&T's stock is currently trading for $30. Perhaps you have some hunch that the share price will go up to $35 in the next two weeks. One way you could bet on this hunch is to buy stocks in AT&T. Let’s suppose you decide to purchase 100 shares at $30 ($3,000 investment). If the stock does go up to $35 in 2 weeks, your total investment is now worth $35 * 100 100. You've made a $500 return on $3,000 invested. MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht wr swanaeet utr Sept Vater aa tn Py Lge eum ‘Another way you could bet on this hunch is by purchasing an options contract on AT&T. This contract would expire in some time period — in this case, you could buy a contract that expires in 2 weeks. Along with this expiration date, the contract would specify a strike price. The strike price isa price at which you can buy shares of AT&T at or before 2 weeks from now. More specifically, the contract usually entitles you to purchase up to 100 shares at the strike price. Suppose you purchase an option entitling you to purchase 100 shares of AT&T at a strike price of $20 within 2 weeks, and that the contract costs $5 per share. IF the stock goes up to $35, your total investment is now worth $35 * 100 (the amount of selling 100 shares in AT&T) minus $20 * 100 (the amount of the purchase of 100 shares at the strike price) minus $5 * 100 (the cost of the option). That means you've made a return of $1,000 on a $500 investment. Options can amplify gains, but they also can amplify losses. We will show MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht wr this in more depth through the model. 1 open Van en ye Developing the Dataset ‘To begin with, I import the following modules: import pandas a8 pd import numpy a5 op import natpiotiib-pyptot ipip inatall dfply from dfply import * ipip install yfinance import yfinance as y Ipip instali ordered set from ordered sez import Orderedset import randon from copy inport copy ipip install requests hemi ipip install yahoo_fin from yahoo fin.stock info import * from yaitoo_fin-options import * import math from datetine import date from datetine import datetime Sload_ext google.colab.data table pit Tuse the ysnoc_ein module to access options and historic stock price information. More info on its uses and examples can be found here. You MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht tng So opin an a tr: aby ge Maan might also notice s1oad_sxt google.colsb.data_table. This provides a great way to view DataFrames when using Google Colab, which is what I used for creating this. ‘To begin building our dataset, we first pull stock data on the S&P 500 using the tickers_spsoo1) function: ‘The resulting sp ise isa list containing each ticker symbol within the S&P 500. One issue I found later on is that yshoo_¢in has trouble pulling info for tickers with a period in their name. Since this is only two of the stocks, I remove them for simplicity: ftheve two make errors due to the period in chem st lrenove ("SK.8") MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht wr 1 open Van en ye ge ei At this point, we can use the 498 tickers we now have (since we've gotten rid of the two stocks prone to errors) to build our options DataFrame. ‘To keep things simple, I want the options to all have the same expiration date. Some stocks have options expiring every Friday, while others might have contracts on one Friday, but not another. Let's look at the expiration dates for the first ticker in our sp. ration dates (sp List(0)) dep (august 21, 2020', ‘September 18, 2020", 'Novenber 20, 2020", January 15, 2021", ‘February 19, 2021", "January 21, 2022") Let’s go for September 18th (any of the dates will do). The following for loop will assign September 18th to expiration and then use a for-loop to generate our DataFrame: fcreating options datas. ‘expiration expiration dates(sp_list(0]) [1] #September date opt ions_a* ~ pd.DataFrane MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht wt for stock dn op list ey: rice = get_live_price(steck) option = get_calis( option[ 'curranterice") = option{'Ticker'] = stock ‘option| 'DateExp'} = expiration options_df = options_df.append (option) print (peice) print (stock) except: Print (‘Option contract not available on '+ str (expization)} pass ck, expiration) 1 Option Vat sw yer: Par by ab Line Luse a try and except statement within the for-loop due to the fact that some of tickers within >_1is: might not have options contracts available on the date specified. To give you an idea of how often this occurs, there are the print” quotes which will display with each ticker iterated over. Here is a snapshot of how the resulting DataFrame cptions_e# appears: Index ContactName __Last Trade Onto Stike Last Pice Bid Ask Change %Change Volume Openintrst Implied Voaiy 192501052 etie [Ftr) @ Coanbice Thr —ateep cn00reo9o 2000.97.17 tees 224 Is |e 7: “Seo 2 maowrscnreonn ZEN 750 aes za D408 sere ramos «Seer 1 namerecmnenron FOES toga te wo sooo erarowmesian n Sone 2 Azooerecaocesoo 2020-08-03 850 180 127 134 ry 1 4 44.53% ersropezragssz0s a Seotambe 2 reowrsconeerson 20037, ars sa 105 1298 ° sam srareomrasizes nai MoxinedinaiacningrblingenmcropionihatonnatsthpytorptiaTocbetst 4 zone eco0060000 1 peonore020082800 7 mzoierecon0s76a0 8 Azonereco0%0so00 10 azoooracoor1000 +4 azo9e19c00118000 MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht aaooa ‘tsa €bT ‘zoe umoce.s4 fovemer Sameer eap0e12 iei2eM Gor ors 1100 190 om 77 73.64 38 028 0250 os oa 025 on 00 +1026 91% 200% se 1 open Vatan ew ye: 2 180 What pieces of information do we care about here? 07% ese 250% sae 8% sas srarooer4essze3 srrooeaestces sr s7ocezassazes srvocezassecra sravocezaesez09 errocear49se209 Firstly it is useful to keep the contact ane, Ticker, and Datetxe columns for clarity. We also want to keep current. Price , Which is the price per share of the underlying stock, along with the strike, which tells us what each. share would cost to purchase if exercising the option. I also keep both vouure and oven. isterest, in order to see whether there is any liquidity in the contract we are viewing: Let’s clear up a little space: Sexte wera wa Seetere wom ‘Sesterse Seite wea Sexton wea Seater ‘eran vam ‘tig Sc Opti aan Maca Per by sec ner aon options at *currentPel os yntract Nante', ‘strike', "Bid", ‘Ask, + Wolume', ‘Open Interest*, 'Ticker', 'DateExp']} ‘One piece of information that we need, yet remains unclear, is the price of the option itself. I use an average of the eia and ask as the most likely price for the option. In order to do so, I remove rows in which either contains a ‘=’ and use the pa.to_nunerie function in order to operate on them, eptions_af[*avgPrice'] = (pd.to_mumeric(options_éf.Bid) + pate mineric(options at.ask)) 7 2 Evaluating Costs and Payoff Scenarios 94 MoxinedinaiacningrblipeckopionihatnnnasawthpytorptiaTiceesst soi ‘tig Se Opti aan Maclain Per Photo by Pepi Stjanovski on Unsplash To keep things simple, we want to first assume that we will not exercise the option until the expiration date. If not, we would need to analyze the probability of specific price changes for each day, and we would likely add unnecessary complexity to the model. Depending on how the price of the underlying security changes up to the expiration date, the option might pay off or might not. For example, if the share price at expiration is lower or equal to the strike price, we would not exercise the option, since we would lose money. In this case, our loss would be the cost of the option contract purchased (which is MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht te pt Vaan Mal a yar sc Une an the option price per share * 100 shares, since contracts are most often for 100 shares at a time), If the share price at expiration is higher than the strike price, then we have the following payoff (where P is share price at expiration, $ is strike price, Option is the price to purchase the contract) Payoff = 100P — 100S — 100(Option) Using this payoff equation, we can find a breakeven point where the payoff would be equal to 0. In order to do so, I use the following: 100(1 + x) P — 1005 — 100(Option) = 0 MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht sa ‘nanos utr Sept Vater aa tn Py Lge eum Where « is the percent change in the share price of the stock from the start date to the expiration date. We can factor out the 100s and solve for to get the breakeven percent change from the starting share price: + S + (Option) _ P fcreating colunns for to! option cost and breakeven percentage We can see a basic relationship between the breakeven point, strike price, and current share price. The further the strike price is below the current MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht sai price, the lower the breakeven percent needs to be. The greater the strike price is, the higher we need the price to move up. 1 open Van en ye We can now create visualizations of the option payoffs under different price change scenarios. Let's create a function that will generate a payoff based on the equations above: mt tx de in decimal format et +x) ° m0: Let’s now use this function to generate payoffs for some AT&T () option. We will first generate a set of scenarios for price changes (in this case, we will look at each 1% change from a 50% drop in the price to a 50% gain). MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht sw ‘moot ‘tig Sc Opti aan Maca Per payoff ~ price_percent_payoff ( percent, options df loptions af. Ticker payoffs append (payof=) by sec ner aon "T"] Alec{51) plt-bar(x axis, payotts) pltixlabel ("Price 4 Charge from start date to expir: plt-ylabel ("Payot (8)") plt-titie("Payofts for ATéT unde: plicsavefig('T_prices.pra", dpi a") various price changes"): 800) Payoff Possibilities for T200918C00022000 1500 : fl io IW 40 -20 0 20 40 Price % Change from start date to expiration Payoff ($) MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht seo swanaeet tng So opin an a tr: aby ge Maan Any price under the breakeven percent change of 0.00049 (can be accessed through ores nt) ) results in a loss equal to the full price of the option contract. In other words, if AT&T stock is $30.01 per share, we need the price to be $30.02 (1.00049 * 30.01) to breakeven. | Gf loptions_df.Ticker == © [51 [°38_pe! Now that we have generated the options dataset and created a way to find payoffs at different price changes percentages, we wi probability distribution section in Part Il move onto the ‘toslleotb research google com/oatleconomatoganialecaS0dfie7iaaS4/¢edbaS76"601672 Wunttedd ipyt ‘Stock Options Evaluation Model: PART I In [ ]: ARPACKAGES AND FORMATTING importing required modules Anport pandas. a5 pd Ainport numpy 3s np nport matplotlib-pyplot as pit Sinport randos {on copy import copy MoxinediniecningrbinpeckopionilatonnasawthpytorpatiaTicbetht ser ‘moot ‘tig Sc pti aan Masa Pen Pa by eg ip install requests tal jp install yahoo fin ‘fron yahoo_fin.stock_info inport * ‘fron yahoo Fin.options import Inport math from datetine inport date Fron datetine inport datetine oad_oxt_ gongle.colab.data_table ‘iunldod_ext google.colab.data table #to disoble ‘Stock Options Model Part Github (Crested using Cola) SlockMaruet Python Options DataSeence Finance MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteetht snr

You might also like