Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
120 views
17 pages
Building A Stock Option Valuation Model With Python Part I
Building a Stock Option Valuation Model with Python Part I
Uploaded by
FabioSantos
AI-enhanced title
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
Download
Save
Save Building a Stock Option Valuation Model with Pytho... For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
120 views
17 pages
Building A Stock Option Valuation Model With Python Part I
Building a Stock Option Valuation Model with Python Part I
Uploaded by
FabioSantos
AI-enhanced title
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
Carousel Previous
Carousel Next
Download
Save
Save Building a Stock Option Valuation Model with Pytho... For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Building a Stock Option Valuation Model with Pytho... For Later
You are on page 1
/ 17
Search
Fullscreen
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 distributionPhoto by Austin Distelo ‘This is Part I of a two-part post. Part II can be accessed here. eninetunoni@estienbulinevickanbnanate-ree-n pret faa autr 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 wrswanaeet 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 wrthis 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 MoxinediniecnbingrblinpemckopionihatonnasaswtpytarptiaTicteethttng 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 wr1 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 wtfor 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 MoxinedinaiacningrblingenmcropionihatonnatsthpytorptiaTocbetst4 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 tept 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 saiprice, 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 seoswanaeet 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
Van Der Post H. Python Fundamentals For Finance... Trading With Python 2024
PDF
No ratings yet
Van Der Post H. Python Fundamentals For Finance... Trading With Python 2024
231 pages
Options With Python
PDF
100% (1)
Options With Python
203 pages
The RSI Delta Indicator. Enhancing Momentum Trading
PDF
No ratings yet
The RSI Delta Indicator. Enhancing Momentum Trading
21 pages
Van Der Post H. Market Master. Trading With Python 2024
PDF
100% (2)
Van Der Post H. Market Master. Trading With Python 2024
336 pages
Van Der Post H. Power Trader. Options Trading With Python 2024
PDF
100% (3)
Van Der Post H. Power Trader. Options Trading With Python 2024
346 pages
Heiken-Ashi Trading - The Full Guide in Python
PDF
100% (2)
Heiken-Ashi Trading - The Full Guide in Python
14 pages
Option Trading Workbook
PDF
0% (1)
Option Trading Workbook
26 pages
Hidden Divergence - Chamane's Guidelines
PDF
100% (1)
Hidden Divergence - Chamane's Guidelines
13 pages
Options Trading Blueprint
PDF
86% (7)
Options Trading Blueprint
12 pages
Creating A Modified Fisher Transformation For Profitable Trading.
PDF
No ratings yet
Creating A Modified Fisher Transformation For Profitable Trading.
21 pages
Principles of Option Pricing
PDF
100% (1)
Principles of Option Pricing
30 pages
Option Trading Workbook
PDF
No ratings yet
Option Trading Workbook
26 pages
Option Trading Workbook
PDF
No ratings yet
Option Trading Workbook
14 pages
Algorithmic Trading Models - Breakouts
PDF
No ratings yet
Algorithmic Trading Models - Breakouts
10 pages
Option Trading Work Book
PDF
No ratings yet
Option Trading Work Book
26 pages
Full Option Greeks
PDF
No ratings yet
Full Option Greeks
26 pages
How To Trade Forex Using Roboforex Strategyquant Software
PDF
No ratings yet
How To Trade Forex Using Roboforex Strategyquant Software
44 pages
Gap Trading. An Introduction & Back-Test in Python
PDF
No ratings yet
Gap Trading. An Introduction & Back-Test in Python
15 pages
Trading Strategy - Technical Analysis With Python TA-Lib
PDF
No ratings yet
Trading Strategy - Technical Analysis With Python TA-Lib
12 pages
Test Strategy in MetaTrader 4 With Tick Precision
PDF
No ratings yet
Test Strategy in MetaTrader 4 With Tick Precision
15 pages
Option Trading Workbook
PDF
No ratings yet
Option Trading Workbook
12 pages
Using Machine Learning To Locate Support and Resistance Lines For Stocks
PDF
No ratings yet
Using Machine Learning To Locate Support and Resistance Lines For Stocks
14 pages
Building A Stock Option Valuation Model With Python Part II
PDF
No ratings yet
Building A Stock Option Valuation Model With Python Part II
18 pages
How To Export Data From Quant Data Manager and Import To Metatrader 5
PDF
No ratings yet
How To Export Data From Quant Data Manager and Import To Metatrader 5
18 pages
Options and Corporate Finance: Mcgraw-Hill/Irwin
PDF
No ratings yet
Options and Corporate Finance: Mcgraw-Hill/Irwin
76 pages
Excel 97 - 2003
PDF
No ratings yet
Excel 97 - 2003
42 pages
4.chapter 22 Option Concept
PDF
No ratings yet
4.chapter 22 Option Concept
77 pages
The Augmented Bollinger Bands
PDF
No ratings yet
The Augmented Bollinger Bands
23 pages
Option Trading Work Book
PDF
No ratings yet
Option Trading Work Book
28 pages
Lecture Slides
PDF
No ratings yet
Lecture Slides
52 pages
Lecture 13 - Option Valuation 2025.3.17
PDF
No ratings yet
Lecture 13 - Option Valuation 2025.3.17
56 pages
Visualizing Option Trading Strategies in Python - by Abhijith Chandradas - DataDrivenInvestor
PDF
No ratings yet
Visualizing Option Trading Strategies in Python - by Abhijith Chandradas - DataDrivenInvestor
11 pages
Time Series Forecasting With 2D Convolutions
PDF
No ratings yet
Time Series Forecasting With 2D Convolutions
33 pages
Unit III Option Pricing, Principals and Model
PDF
No ratings yet
Unit III Option Pricing, Principals and Model
54 pages
Importing High Quality Tick Data On MetaTrader 4 & 5
PDF
No ratings yet
Importing High Quality Tick Data On MetaTrader 4 & 5
34 pages
Lecture 6.1 Optionsfinal
PDF
No ratings yet
Lecture 6.1 Optionsfinal
37 pages
A Review of Reinforcement Learning For Financial Time Series Prediction and Portfolio Optimization
PDF
No ratings yet
A Review of Reinforcement Learning For Financial Time Series Prediction and Portfolio Optimization
38 pages
Option Trading Workbook
PDF
No ratings yet
Option Trading Workbook
26 pages
CF06
PDF
No ratings yet
CF06
19 pages
12 Investment Under Uncertainty 2
PDF
No ratings yet
12 Investment Under Uncertainty 2
20 pages
Technical Indicators and GRU-LSTM To Predict Stock Price
PDF
No ratings yet
Technical Indicators and GRU-LSTM To Predict Stock Price
36 pages
Basic Options Trading
PDF
No ratings yet
Basic Options Trading
38 pages
4 Pricing Models
PDF
No ratings yet
4 Pricing Models
38 pages
Using Machine Learning To Locate Support and Resistance Lines For Stocks - by Suhail Saqan - The Startup - Jan, 2021 - Medium
PDF
No ratings yet
Using Machine Learning To Locate Support and Resistance Lines For Stocks - by Suhail Saqan - The Startup - Jan, 2021 - Medium
14 pages
7.2 Options - Valuation & Put-Call Parity-1
PDF
No ratings yet
7.2 Options - Valuation & Put-Call Parity-1
36 pages
Options and Embedded Options: Ramamoorthi Srinivasan BSC Fca, Fafd, RV & RP ICMA RVO - Bangalore 08-Dec-2019
PDF
No ratings yet
Options and Embedded Options: Ramamoorthi Srinivasan BSC Fca, Fafd, RV & RP ICMA RVO - Bangalore 08-Dec-2019
35 pages
Final Year Project
PDF
No ratings yet
Final Year Project
34 pages
Derivative Pricing Project 1725218827
PDF
No ratings yet
Derivative Pricing Project 1725218827
42 pages
Financial Derivatives
PDF
No ratings yet
Financial Derivatives
30 pages
F Options
PDF
No ratings yet
F Options
29 pages
Modelling Option Prices
PDF
No ratings yet
Modelling Option Prices
28 pages
Development of Algorithmic Volatility Trading Strategies For Equity Options
PDF
No ratings yet
Development of Algorithmic Volatility Trading Strategies For Equity Options
18 pages
Foptions
PDF
No ratings yet
Foptions
26 pages
Real Options and Mergers: P.V. Viswanath
PDF
No ratings yet
Real Options and Mergers: P.V. Viswanath
26 pages
Estimate Support and Resistance of A Stock With Python
PDF
No ratings yet
Estimate Support and Resistance of A Stock With Python
18 pages
Revision Notes For FIN312 - Unit 5
PDF
No ratings yet
Revision Notes For FIN312 - Unit 5
15 pages
Derivative Unit III
PDF
No ratings yet
Derivative Unit III
19 pages
Finance Functions Python
PDF
No ratings yet
Finance Functions Python
13 pages
Options and Option Strategies: by Surya B. Rana
PDF
No ratings yet
Options and Option Strategies: by Surya B. Rana
12 pages
Option Trading Workbook
PDF
No ratings yet
Option Trading Workbook
28 pages
Option Trading Workbook
PDF
No ratings yet
Option Trading Workbook
28 pages
How I Created A Bitcoin Trading Algorithm Using Sentiment Analysis With A 29% Return
PDF
No ratings yet
How I Created A Bitcoin Trading Algorithm Using Sentiment Analysis With A 29% Return
10 pages
MA 271 2025 Lecture 21
PDF
No ratings yet
MA 271 2025 Lecture 21
9 pages
Module 5
PDF
No ratings yet
Module 5
13 pages
NSEpy
PDF
No ratings yet
NSEpy
9 pages
Assignment 2 Computational Part
PDF
No ratings yet
Assignment 2 Computational Part
9 pages
Assessment - Machine Learning
PDF
No ratings yet
Assessment - Machine Learning
6 pages
Quant Option Pricing Model English
PDF
No ratings yet
Quant Option Pricing Model English
3 pages
Option Pricing
PDF
No ratings yet
Option Pricing
4 pages
Volatiltiy Skew, Term Structure: Importing Libraries
PDF
No ratings yet
Volatiltiy Skew, Term Structure: Importing Libraries
4 pages
Term Structure and Volatility Skew 1710855184
PDF
No ratings yet
Term Structure and Volatility Skew 1710855184
4 pages
Liam Mescall Imp Probs
PDF
No ratings yet
Liam Mescall Imp Probs
3 pages